在python中打印paramiko中其他命令的输出/stdout



我使用Python 2.7中的Paramiko连接到linux服务器,程序工作正常。问题是,当我运行它时,我从IDE得到这个输出:

Start
This is a test program
before the cd..
after the cd ..
after the pwd
after the ls
/home/11506499
End

我的代码是这样的:

import paramiko
ssh = paramiko.SSHClient()
print('Start')
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('XXX.XX.XXX.XX', port = 22, username = 'tester', password = 'test')
print("This is a test program")
stdin, stdout, stderr = ssh.exec_command('pwd')
print('before the cd..')
stdin.write('cd ..')
stdin.write('n')
stdin.flush()
print('after the cd ..')
stdin.write('pwd')
stdin.write('n')
stdin.flush()
print('after the pwd')
stdin.write('ls')
stdin.write('n')
stdin.flush()
print('after the ls')
output = stdout.readlines()
print 'n'.join(output)
ssh.close()
print('End')

从打印结果中可以看到,程序运行所有命令,但stdout只显示第一次ssh的输出。Exec_command ('pwd'),而不是从所有的stdin.write。我想知道的是,是否有一种方法或命令可以从我通过终端发送的其他命令中获得输出?我正在考虑的命令,如第二个'pwd'或'ls'命令?

是否有一种方法可以显示我在终端中采取的每个操作的响应输出,就像我在Linux中使用cmd.exe或终端一样?

我试着在网上看,但没有看到任何东西,因为例子只显示了第一个命令的输出。所以我希望有人能帮我解决这个问题。


编辑:我离开了客户端连接,而是去了一个shell,它将保持连接,直到我注销。我使用recv来存储终端的输出,并使用print来打印出来。这产生了奇迹。

我做了导入时间,所以脚本可以休息一下,它可以在打印出来之前收集其余的输出。通过这种方式,我可以打印出终端上出现的所有内容,而不会缺少它。

您在脚本中只执行一个命令。根据我的理解,在您的示例中,stdin将用于向正在运行的命令传递参数。这意味着您必须分别为pwd、cd和ls运行ssh.exec_command(<cmd>)。初始执行后,会话关闭,您不能发出更多命令。

这就像发出命令

ssh user@hostname "pwd"

会话已完成,连接已关闭。它不太像telnet,您只需键入命令并添加'n'来执行它,也不像bash提示,因为您没有启动tty。


问候,Lisenby

最新更新