我在paramiko中写了这段代码:
def TryExecute(hostname='192.168.1.1', user='root', passwd='root'): ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.connect(hostname, username=user, password=passwd, timeout=3) #stdin, stdout, stderr = ssh.exec_command("uname -a") session = ssh.invoke_shell() session.send("\n") session.send("echo step 1\n") time.sleep(1) session.send("sleep 30\n") time.sleep(1) while not session.recv_ready(): time.wait(2) output = session.recv(65535) session.send("echo step 2\n") time.sleep(1) output += session.recv(65535)
我尝试在我的linux服务器上执行更多命令,问题是我的python代码不等待完成执行命令,例如,如果我尝试执行"sleep 30",则python不等待30秒完成执行命令,怎么解决这个问题?我试试白衣,而recv_ready()蝙蝠不等待:(
使用exec_command
:http://docs.paramiko.org/en/1.16/api/channel.html
stdin, stdout, stderr = ssh.exec_command("my_long_command --arg 1 --arg 2")
以下代码适用于我:
from paramiko import SSHClient, AutoAddPolicy import time ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.connect('111.111.111.111', username='myname', key_filename='/path/to/my/id_rsa.pub', port=1123) sleeptime = 0.001 outdata, errdata = '', '' ssh_transp = ssh.get_transport() chan = ssh_transp.open_session() # chan.settimeout(3 * 60 * 60) chan.setblocking(0) chan.exec_command('ls -la') while True: # monitoring process # Reading from output streams while chan.recv_ready(): outdata += chan.recv(1000) while chan.recv_stderr_ready(): errdata += chan.recv_stderr(1000) if chan.exit_status_ready(): # If completed break time.sleep(sleeptime) retcode = chan.recv_exit_status() ssh_transp.close() print(outdata) print(errdata)
请注意,命令history
无法按原样执行.请参见此处的示例:https://superuser.com/questions/962001/incorrect-output-of-history-command-of-ssh-how-to-read-the-timestamp-info-corre