python - ssh paramiko 无法读取输出

标签 python linux

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

相关文章:

python - 获取选定对象的列表作为字符串 Blender python

python - 如何用仅包含原子条目的更改的 pdb 文件替换 pdb 原子条目

python - 我想输入任意长度的数字,然后我想将其转换为单词形式。例如,如果我输入 615,它应该打印 ' six one five'

python - Mypy:得到 "function",预期 "Callable[..., Any]"

linux - 支持 FIPS 的 OpenSSL 和 openssl/fips.h : No such file or directory

linux - 如何在 EC2 中的 RHEL 上安装 Rust 工具集?

python - 如何在Linux环境下读取Windows文件?

c - 在 Linux 中使用 C 实现零 RAM

linux - 我需要 RHEL v6.6 的 libapr-1.so.0 rpm

linux - Linux 容器中的 setcap cap_net_admin 阻止用户访问每个文件