Python 如果使用Paramiko在远程服务器上启动的命令没有响应,则在特定时间后终止远程会话
在远程服务器上运行命令时,我在使用Paramiko模块时遇到一些问题Python 如果使用Paramiko在远程服务器上启动的命令没有响应,则在特定时间后终止远程会话,python,ssh,paramiko,Python,Ssh,Paramiko,在远程服务器上运行命令时,我在使用Paramiko模块时遇到一些问题 def check_linux(cmd, client_ip, client_name): port = 22 username = 'xxxxxxx' password = 'xxxxxxxx' try: sse = paramiko.SSHClient() sse.set_missing_host_key_policy(paramiko.AutoAddPoli
def check_linux(cmd, client_ip, client_name):
port = 22
username = 'xxxxxxx'
password = 'xxxxxxxx'
try:
sse = paramiko.SSHClient()
sse.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sse.connect(client_ip, port, username, password, timeout=5)
(stdin, stdout, stderr) = sse.exec_command("my cmd")
del stdin
status = stdout.read()
status = status.decode('ascii')
return status
except (paramiko.SSHException, socket.error, socket.timeout, Exception) as error:
print "Unable to Authenticate/logon:" ,client_name,client_ip,
sys.exit()
[root@xxxxxxxstar_脚本]#python
Python 2.7.5(默认,2015年10月11日,17:47:16)
[GCC 4.8.3 20140911(红帽4.8.3-9)]关于linux2
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>进口帕拉米科
>>>端口=22
>>>用户名='xxxxxxxx'
>>>密码='xxxxxxxxx'
>>>客户机ip='xxxxxxx'
>>>cmd='openssl s_客户端-连接xxxxxxx:xxxxx'
>>>sse=paramiko.SSHClient()
>>>sse.set_缺少_主机_密钥_策略(paramiko.AutoAddPolicy())
>>>连接(客户端ip、端口、用户名、密码、超时=5)
>>>(stdin、stdout、stderr)=sse.exec_命令(cmd)
>>>status=stderr.read()
对于某些服务器,命令不会执行,程序也不会进一步执行。我已经尝试了
readlines()
和stdout.channel.eof_接收到了
,但两者似乎都不起作用。.read
将等待命令完成,这是它从未做过的
相反,请先等待命令完成。如果花费的时间太长,请终止该命令(使用stdout.channel.close()
)
您可以从以下位置使用代码:
尽管您可以使用上面的代码,但前提是该命令只产生很少的输出。否则代码可能会死锁。对于健壮的解决方案,您需要连续读取输出。
参见非常感谢马丁。它有效!。。我接受答案!。。再次感谢。
timeout = 30
import time
endtime = time.time() + timeout
while not stdout.channel.eof_received:
time.sleep(1)
if time.time() > endtime:
stdout.channel.close()
break
status = stdout.read()