gpt4 book ai didi

python - ssh paramiko 无法读取输出

转载 作者:太空宇宙 更新时间:2023-11-04 04:16:16 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com