【问题标题】:How to keep ssh session not expired using paramiko?如何使用 paramiko 保持 ssh 会话不过期?
【发布时间】:2016-07-29 05:00:52
【问题描述】:

我打算使用 paramiko 在远程主机上运行多个命令,但运行命令后 ssh 会话关闭。
代码如下:

from paramiko import SSHClient  
import paramiko  
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, 22, user, passwd, timeout=3)
stdin, stdout, stderr = ssh.exec_command('uname -a')

那么有什么方法可以阻止 ssh 会话关闭吗?或者 paramiko 的任何替代品?

更新
当连接到 Linux 服务器时,我能够在我的 Macbook 上继续调用 exec_command,但是当连接到 switch 并引发了一个 SSHException: paramiko.ssh_exception.SSHException: SSH session not active

>>> print ssh.get_transport()  
>>> <paramiko.Transport at 0xf00216d0L (unconnected)>  
>>> print ssh.get_transport().is_active()  
>>> False  
>>> print ssh.get_transport().is_authenticated()  
>>> False

有什么方法可以让 paramiko ssh 会话一直处于活动状态?

paramiko 调试模式信息返回如下:

启动线程(客户端模式):0x2657e10L
已连接(版本 1.99,客户端 Comware-5.20)
kex 算法:[u'diffie-hellman-group-exchange-sha1',u'diffie-hellman-group14-sha1',u'diffie-hellman-group1-sha1'] 服务器密钥:[u'ssh-rsa']客户端加密:[u'aes128-cbc', u'3des-cbc', u'des-cbc'] 服务器加密:[u'aes128-cbc', u'3des-cbc', u'des-cbc']客户端mac:[u'hmac-sha1', u'hmac-sha1-96', u'hmac-md5', u'hmac-md5-96'] 服务器mac:[u'hmac-sha1', u'hmac -sha1-96', u'hmac-md5', u'hmac-md5-96'] 客户端压缩:[u'none'] 服务器压缩:[u'none'] 客户端语言:[u''] 服务器语言:[u''] kex 跟随?错误
密码同意:本地=aes128-cbc,远程=aes128-cbc
使用 kex diffie-hellman-group14-sha1;服务器密钥类型 ssh-rsa;密码:本地aes128-cbc,远程aes128-cbc; mac:本地 hmac-sha1,远程 hmac-sha1;压缩:本地无,远程无
切换到新键 ...
userauth 没问题
验证(密码)成功!
[chan 0] 最大数据包输入:32768 字节
[chan 1] 最大数据包:32768 字节
[chan 0] 最大数据包输出:32496 字节
Secsh 通道 0 已打开。
Secsh 通道 2 打开失败:
资源短缺:资源短缺
[chan 0] Sesch 频道 0 请求正常
[chan 0] 发送 EOF (0)

【问题讨论】:

  • 脚本还有更多内容吗?您应该可以继续拨打exec_command
  • 喂?您是在脚本中运行多个命令,还是在运行多个脚本时各运行一个命令?
  • 我能够在我的 Macbook 上继续调用 exec_command,但它在 Linux 服务器上不起作用并引发了 SSHException: paramiko.ssh_exception.SSHException: SSH session not active Mac 上的 Python 版本是 2.7.11,但在 Linux 服务器上是 2.6 .6. @tdelaney
  • 很奇怪。它是一个特别糟糕的开关吗?您可以在 DEBUG 级别启用日志记录(请参阅How to use paramiko logging?)以获取更多详细信息。
  • 这不是真正的答案,但可能有用。如果您只运行几个命令,则可以将它们链接在一起:ssh.exec_command("whoami; cd dir; ls")

标签: python python-2.7 ssh paramiko switching


【解决方案1】:

我看到您在连接调用中使用了timeout 参数:

ssh.connect(host, 22, user, passwd, timeout=3)

来自文档:

timeout (float) – TCP 连接的可选超时(以秒为单位)

在我的一个脚本中,我只是这样做:

ssh = paramiko.SSHClient()
ssh.connect(host, username=settings.user)

在我打电话之前保持连接打开

ssh.close()

【讨论】:

  • 从 Linux 服务器连接到 switch 时结果相同,但从另一台 Linux 服务器连接到 Linux 服务器时工作正常。是否添加timeout参数似乎没有什么不同。 @LarsVegas
  • 它确实解决了不活动的 ssh 会话问题,但是当我并行运行它时,发送第一个命令后通道一直挂在那里。 @LarsVegas
【解决方案2】:

您可以使用 paramiko 实现交互式 shell,这样在远程 shell 上执行命令后通道不会关闭。

import paramiko
import re


class ShellHandler:

    def __init__(self, host, user, psw):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(host, username=user, password=psw, port=22)

        channel = self.ssh.invoke_shell()
        self.stdin = channel.makefile('wb')
        self.stdout = channel.makefile('r')

    def __del__(self):
        self.ssh.close()

    @staticmethod
    def _print_exec_out(cmd, out_buf, err_buf, exit_status):
        print('command executed: {}'.format(cmd))
        print('STDOUT:')
        for line in out_buf:
            print(line, end="")
        print('end of STDOUT')
        print('STDERR:')
        for line in err_buf:
            print(line, end="")
        print('end of STDERR')
        print('finished with exit status: {}'.format(exit_status))
        print('------------------------------------')
        pass

    def execute(self, cmd):
        """

        :param cmd: the command to be executed on the remote computer
        :examples:  execute('ls')
                    execute('finger')
                    execute('cd folder_name')
        """
        cmd = cmd.strip('\n')
        self.stdin.write(cmd + '\n')
        finish = 'end of stdOUT buffer. finished with exit status'
        echo_cmd = 'echo {} $?'.format(finish)
        self.stdin.write(echo_cmd + '\n')
        shin = self.stdin
        self.stdin.flush()

        shout = []
        sherr = []
        exit_status = 0
        for line in self.stdout:
            if str(line).startswith(cmd) or str(line).startswith(echo_cmd):
                # up for now filled with shell junk from stdin
                shout = []
            elif str(line).startswith(finish):
                # our finish command ends with the exit status
                exit_status = int(str(line).rsplit(maxsplit=1)[1])
                if exit_status:
                    # stderr is combined with stdout.
                    # thus, swap sherr with shout in a case of failure.
                    sherr = shout
                    shout = []
                break
            else:
                # get rid of 'coloring and formatting' special characters
                shout.append(re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]').sub('', line).
                             replace('\b', '').replace('\r', ''))

        # first and last lines of shout/sherr contain a prompt
        if shout and echo_cmd in shout[-1]:
            shout.pop()
        if shout and cmd in shout[0]:
            shout.pop(0)
        if sherr and echo_cmd in sherr[-1]:
            sherr.pop()
        if sherr and cmd in sherr[0]:
            sherr.pop(0)

        self._print_exec_out(cmd=cmd, out_buf=shout, err_buf=sherr, exit_status=exit_status)
        return shin, shout, sherr

【讨论】:

    猜你喜欢
    • 2018-01-19
    • 2021-12-12
    • 2011-07-21
    • 2020-08-16
    • 2020-09-12
    • 1970-01-01
    • 2010-12-27
    • 2018-06-01
    • 2015-07-11
    相关资源
    最近更新 更多