在远程客户端上运行命令时,我在使用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.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@xxxxxxx star_script]# python
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> port = 22
>>> username = 'xxxxxxxx'
>>> password = 'xxxxxxxxxx'
>>> client_ip = 'xxxxxxx'
>>> cmd = 'openssl s_client -connect xxxxxxx:xxxxx'
>>> 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(cmd)
>>> status = stderr.read()
对于某些客户端的命令不会执行,并且我的程序不会进一步执行。我已经尝试过readlines()和stdout.channel.eof_received:,但是两者似乎都无法正常工作。谁能帮忙..
.read
将等待命令执行完毕,从不执行。
相反,请先等待命令完成。如果花费的时间太长,请终止命令(使用stdout.channel.close()
)。
您可以使用Python Paramiko exec_command timeout doesn't work?中的代码:
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()