我正在运行一个远程命令:
ssh = paramiko.SSHClient()
ssh.connect(host)
stdin, stdout, stderr = ssh.exec_command(cmd)
Run Code Online (Sandbox Code Playgroud)
现在我想得到输出.我见过这样的事情:
# Wait for the command to finish
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
stdoutLines = stdout.readlines()
Run Code Online (Sandbox Code Playgroud)
但这似乎有时从不运行readlines()(即使应该有关于stdout的数据).这似乎对我意味着stdout.channel.exit_recat_ready()一旦stdout.channel.exit_status_ready()为True,stdout.channel.recv_ready()就不一定准备就绪(True).
这样的事情合适吗?
# Wait until the data is available
while not stdout.channel.recv_ready():
pass
stdoutLines = stdout.readlines()
Run Code Online (Sandbox Code Playgroud)
也就是说,在等待recv_ready()数据准备就绪之前,我是否真的必须首先检查退出状态?
如果stdout.channel.recv_ready()在无限循环中等待成为True(如果不应该是任何stdout输出则不会),我怎么知道是否应该在stdout上有数据?
我尝试使用 Paramiko 和 ssh 来备份服务器以调用tar命令。当文件数量有限时,一切正常,但当文件夹很大时,脚本会无休止地等待。下面的测试告诉我问题出在标准输出的大小上。
有没有办法纠正它并执行这种命令?
案例大输出:
query = 'cd /;ls -lshAR -h'
chan.exec_command(query)
while not chan.recv_exit_status():
if chan.recv_ready():
data = chan.recv(1024)
while data:
print data
data = chan.recv(1024)
if chan.recv_stderr_ready():
error_buff = chan.recv_stderr(1024)
while error_buff:
print error_buff
error_buff = chan.recv_stderr(1024)
exist_status = chan.recv_exit_status()
if 0 == exist_status:
break
Run Code Online (Sandbox Code Playgroud)
结果是(不行 - 阻止 - 死??)
query = 'cd /;ls -lshAR -h'
chan.exec_command(query)
while not chan.recv_exit_status():
if chan.recv_ready():
data = chan.recv(1024)
while data:
print data
data = chan.recv(1024)
if chan.recv_stderr_ready(): …Run Code Online (Sandbox Code Playgroud) 我有这个简单的python代码:
import time
print "1"
time.sleep(3)
print "2"
time.sleep(2)
Run Code Online (Sandbox Code Playgroud)
然后我使用 paramiko 远程运行它:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('X.X.X.X', username='user', key_filename='/home/user/.ssh/id_rsa')
stdin, stdout, stderr = ssh.exec_command('python /home/user/test.py')
print stdout.read()
ssh.close()
Run Code Online (Sandbox Code Playgroud)
它将等到 Python 代码完成,然后打印所有内容。但我希望它实时打印每一行。我该怎么做?
谢谢你。
更新:我尝试通过 ssh 命令运行 Python 代码:
ssh user@X.X.X.X "python /home/user/test.py"
Run Code Online (Sandbox Code Playgroud)
并且输出是一样的。它等待 Python 代码完成,然后打印出所有内容。如果我远程运行 shell 脚本,则 ssh 命令和 paramiko 都很好。
注意:我看过其他帖子,但没有一个帖子可以解释答案,也没有一个有效的帖子。
有没有办法获得 的输出exec_command,专门用于exec_command('docker run <CONTAINER_ID>')Paramiko 包的实时输出?