0

我正在使用连接到服务器,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 ~]$ 
>>> 
4

1 回答 1

0

you define outp in the scope of the context manager that you create with the with statement. try printing inside the suite of the context manager i.e.

while channel.recv_ready():
    outp = channel.recv(1024)
    print outp

or do this:

outp = ""
while channel.recv_ready():
    outp = channel.recv(1024)
print outp
于 2013-04-25T19:04:15.063 回答