首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果在使用Paramiko的远程服务器上启动命令没有响应,则在一定时间后终止远程会话。

如果在使用Paramiko的远程服务器上启动命令没有响应,则在一定时间后终止远程会话。
EN

Stack Overflow用户
提问于 2019-11-21 08:12:47
回答 1查看 698关注 0票数 2

在远程服务器上运行命令时,我遇到了一些Paramiko模块的问题。

代码语言:javascript
复制
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()
代码语言:javascript
复制
[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,但两者似乎都不起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-22 08:53:29

.read将等到命令完成时,才执行它从未执行的操作。

相反,先等待命令完成。如果花费的时间太长,则终止命令(使用stdout.channel.close())。

您可以使用来自Python Paramiko exec_command timeout doesn't work?的代码

代码语言:javascript
复制
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()

尽管您可以使用上面的代码,但只有当命令产生的输出很少时才能使用。否则,代码可能会死锁。对于健壮的解决方案,需要连续读取输出。

请参阅A command does not finish when executed using Python Paramiko exec_command

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58970148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档