我正在使用 paramiko
连接到服务器,并尝试使用 channel.send
接收顺序输出。下面的脚本无法捕获 channel.recv
的输出。有什么想法吗?
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("xx.xx.xx.xx",username='kshk',password='xxxxxxxx',key_filename='/home/krisdigitx/.ssh/id_rsa')
channel = ssh.invoke_shell()
channel.send('df -h\n')
while channel.recv_ready():
outp = channel.recv(1024)
print outp
给予:
krisdigitx@krisdigitx-Dell-System-XPS-L702X:~/SCRIPTS$ python test.py
Traceback (most recent call last):
File "test.py", line 11, in <module>
print outp
NameError: name 'outp' is not defined
在解释器模式下运行脚本可以工作...
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect("xx.xx.xx.xx",username='kshk',password='xxxxx',key_filename='/home/krisdigitx/.ssh/id_rsa')
>>> channel = ssh.invoke_shell()
>>> channel.send('df -h\n')
6
>>> while channel.recv_ready():
... outp = channel.recv(1024)
...
>>> print outp
/dec/sda
7.2T 6.6T 622G 92% /tmp/xxx
[kshk@server ~]$
>>>
最佳答案
您可以在使用 with 语句创建的上下文管理器的范围内定义 outp。 尝试在上下文管理器套件中进行打印,即
while channel.recv_ready():
outp = channel.recv(1024)
print outp
或者这样做:
outp = ""
while channel.recv_ready():
outp = channel.recv(1024)
print outp
关于python - ssh paramiko 无法读取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16222645/