如何使用paramiko执行远程命令

1 投票
1 回答
6799 浏览
提问于 2025-04-16 05:25

我想要压缩一个远程机器上的文件夹。为此,我正在使用paramiko这个库。可是我不知道怎么用paramiko来实现这个功能。有没有什么建议呢?

这是我的代码:

dpath = '/var/mysql/5.1/mysql.zip'    
port = 22    
host = '10.88.36.7'    
transport = paramiko.Transport((host, port))    
transport.connect(username=suser, password=spass)    
channel = transport.open_channel(kind="session")    
channel.exec_command('zip -r /var/db/mysql /var/db/mysql')    
transport.close()

这段代码有什么问题吗?

1 个回答

3

channel.exec_command(...)

之后,你需要等这个命令执行完毕,可以用下面的方式:

while not channel.exit_status_ready()
    ... wait ... ( you can read the output with channel.recv, or sleep a bit)

另外,你的压缩命令有点奇怪……难道你不是想说

zip -r /var/db/mysql.zip /var/db/mysql

撰写回答