Paramiko官网文档链接: http://docs.paramiko.org/en/stable/
一、执行指令路径
exec_command是在登录时默认路径下执行命令,且每次执行都是在登录时的默认路径下执行命令,即使执行了client.exec_command('cd XXX'),再执行下一条指令时,仍然在登录时的默认路径。
要规避该问题有三种方法
1、每次与路径相关的指令用绝对路径
2、一条字符串包含多条指令,指令间用分号间隔,一起传递。
client.exec_command('cd /home/; ls -al')
3、交互式编程,通过invoke_shell开启一个会话,然后用会话的send,recv方法分别发送和接收指令。
二、SFTP传递文件情况实时监测
当SFTP需要发送或接收的文件较大时,传递时间较长,等待过程中需要提示文件传递情况。
注意put方法中的callback,可以定义一个回调函数,以实时检测文件传递情况。
put
(localpath, remotepath, callback=None, confirm=True)
Copy a local file (localpath
) to the SFTP server as remotepath
. Any exception raised by operations will be passed through. This method is primarily provided as a convenience.
The SFTP operations use pipelining for speed.
Parameters: |
|
---|
sftp_client.put(src_file, dst_file,callback=self.PutCallback)
回调函数调用的非常频繁,具体时间未测试。为减少提示次数,定义每增加5%提示一次。
def PutCallback(self,TransferredSize, ToBeTransferred):
rate = int(TransferredSize * 100 / ToBeTransferred)
if rate > self.percent + 5:
self.percent = rate
三、执行指令持续输出
https://stackoverflow.com/questions/25260088/paramiko-with-continuous-stdout
stdin, stdout, stderr = client.exec_command(str_command) #str_command为需要执行的指令 for l in self.line_buffered(stdout): #stdout为持续输出的结果,l为结果的每一行。如果行中包含update_prog_percent则输出给界面显示 if "update_prog_percent" in l: self.MsgSigOut.emit(addr + l, 1) self.log.info(addr + l)
def line_buffered(self, f): #每读取一行执行结果就输出一行 line_buf = "" while not f.channel.exit_status_ready(): line_buf += f.read(1).decode('utf8') if line_buf.endswith('\n'): yield line_buf line_buf = ''