python-3.x - 在 stdout.read( ),paramiko python 模块挂起

我使用以下代码:


import paramiko



def runSshCmd(hostname, username, password, cmd, timeout=None): 


 client = paramiko.SSHClient()


 client.set_missing_host_key_policy(paramiko.AutoAddPolicy())


 client.connect(hostname, username=username, password=password,


 allow_agent=False, look_for_keys=False, timeout=timeout) 


 stdin, stdout, stderr = client.exec_command(cmd)


 stdin.flush()


 data = stdout.read()


 print (data)


 client.close()



runSshCmd("10.128.12.32","root","C0mput3Gr!d","ts_menu")



当涉及到stdout.read()时,它挂起了...有时它会长时间打印输出。

我看到这个问题已报告在:

https://bugs.python.org/issue24026

python中是否有更好的模块,可用于ssh连接和运行命令?

时间:

可能与https://github.com/paramiko/paramiko/issues/109相关。

我也遇到了这个问题,是由于stdout.channel.eof_received =


import paramiko


client = paramiko.SSHClient()


client.set_missing_host_key_policy(paramiko.AutoAddPolicy())


client.connect("1.1.1.1", username="root", password="pass")


stdin, stdout, stderr = client.exec_command("service XXX start")



stdin,stdout和stderr保持打开状态。


>>> print stdin


<paramiko.ChannelFile from <paramiko.Channel 3 (open) window=2097152 in-buffer=50 -> <paramiko.Transport at 0x17eff90L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>


>>> print stdout


<paramiko.ChannelFile from <paramiko.Channel 3 (open) window=2097152 in-buffer=50 -> <paramiko.Transport at 0x17eff90L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>


>>> print stderr


<paramiko.ChannelFile from <paramiko.Channel 3 (open) window=2097152 in-buffer=50 -> <paramiko.Transport at 0x17eff90L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>



未收到EOF。


>>> print stdin.channel.eof_received


0



等待超时,强制stdout.channel.close(),然后执行stdout.read():


>>> timeout = 30


>>> import time


>>> endtime = time.time() + timeout


>>> while not stdout.channel.eof_received:


... sleep(1)


... if time.time() > endtime:


... stdout.channel.close()


... break


>>> stdout.read()


'Starting XXX: n[ OK ]rProgram started . . .n'


>>>



我使用:


Python 2.6.6


paramiko (1.15.2)



希望这有帮助。

尝试设置'get_pty = True ',然后仅读取stdout中的字节。为了避免无限循环,最好在continue语句中设置超时和睡眠:


stdin, stdout, stderr = ssh.exec_command("your-command",get_pty=True)


stdout.flush()


nbytes = 0


while (len(stdout.channel.in_buffer)==0):


 continue



nbytes=len(stdout.channel.in_buffer)


print(nbytes)


stdout.read(nbytes)



...