gpt4 book ai didi

python - paramiko python 模块卡在 stdout.read()

转载 作者:太空狗 更新时间:2023-10-29 18:22:56 25 4
gpt4 key购买 nike

我正在使用下面的代码:

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 == 0

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

通常我会收到 True 并且只能使用 stdout.read(),但为了安全起见我使用了这个解决方法(有效!):等待超时,强制执行 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)

希望这有助于...

关于python - paramiko python 模块卡在 stdout.read(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266753/

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