简体   繁体   中英

python paramiko timeout for commands

I need some help with paramiko(python). I have a server with non-standard SSH interface so I used interactive mode and I am running couple of commands under the same channel(exec_command doesn't work for me). Everything is fine however I would like to introduce some timeout per command because the application stays in the while loop when the data is not received. Channel.settimeout doesn't seem to work properly as the application timeouts after 1st command. I cannot use signals due to threading. When I used time() to count the time after data variable is empty I noticed is that the whole code execution hangs, most probably waiting for the channel data. Any advise how to solve this would be highly appreciated.

    ssh=paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        connect = ssh.connect(host,username=,password=,timeout=20)
        file=open("test.txt","w+")
        channel = ssh.invoke_shell()
        data = channel.recv(5000)
        set_of_commands = ["cmd\n","reset\n"]

        while set_of_commands is not None:

            file.write(data)
            # New command might be executed here if we have 'system:'
            if re.match("system:",data) is not None:
                try:
                    command=set_of_commands.pop()
                    channel.send(command)
                except:
                    break
            data=channel.recv(5000)

You could probably use below for having timeout for each command. I have taken reference from this post. Python Paramiko timeout with long execution, need full output

chan = ssh.get_transport().open_session()

cmd = "timeout {0} {1}\n".format(timeouttime, cmd)

chan.exec_command(cmd)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM