python 您所在的位置:网站首页 python判断联网成功 python

python

2023-10-01 20:18| 来源: 网络整理| 查看: 265

我正在设计使用 paramiko 进行 SSH 连接的测试用例。测试用例通常包含 paramiko.exec_command() 调用,我有一个包装器(称为 run_command())。这里的self.ssh是paramiko.SSHClient()的一个实例。我使用装饰器在每次调用之前检查 ssh 连接。 (self.get_ssh() 协商连接)

def check_connections(function): ''' A decorator to check SSH connections. ''' def deco(self, *args, **kwargs): if self.ssh is None: self.ssh = self.get_ssh() else: ret = getattr(self.ssh.get_transport(), 'is_active', None) if ret is None or (ret is not None and not ret()): self.ssh = self.get_ssh() return function(self, *args, **kwargs) return deco @check_connections def run_command(self, command): ''' Executes command via SSH. ''' stdin, stdout, stderr = self.ssh.exec_command(command) stdin.flush() stdin.channel.shutdown_write() ret = stdout.read() err = stderr.read() if ret: return ret elif err: return err else: return None

在我的远程节点重新启动之前,它可以完美运行,这有时会发生。当它发生时,下一个 run_command() 调用会生成一个 socket.error 异常。问题是,paramiko.Transport 对象似乎一直处于事件状态,直到抛出异常:

Python 2.7.3 (default, Mar 7 2013, 14:03:36) [GCC 4.3.4 [gcc-4_3-branch revision 152973]] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> import paramiko >>> ssh = paramiko.SSHClient() >>> print ssh >>> print ssh.get_transport() None >>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) >>> ssh.load_host_keys(os.path.expanduser('~') + '/.ssh/known_hosts') >>> ssh.connect(hostname = '172.31.77.57', username = 'root', password = 'rootroot', timeout = 5.0) >>> print ssh >>> print ssh.get_transport() >>> print ssh.get_transport().is_active() True >>> ssh.exec_command('ls') (>, >, >) >>> print ssh >>> print ssh.get_transport() >>> print ssh.get_transport().is_active() True >>> ssh.exec_command('reboot') (>, >, >) >>> print ssh >>> print ssh.get_transport() >>> print ssh.get_transport().is_active() True >>> ssh.exec_command('ls') No handlers could be found for logger "paramiko.transport" Traceback (most recent call last): File "", line 1, in File "/home/pytest/lib/python2.7/site-packages/paramiko/client.py", line 370, in exec_command chan = self._transport.open_session() File "/home/pytest/lib/python2.7/site-packages/paramiko/transport.py", line 662, in open_session return self.open_channel('session') File "/home/pytest/lib/python2.7/site-packages/paramiko/transport.py", line 764, in open_channel raise e socket.error: [Errno 104] Connection reset by peer >>> print ssh >>> print ssh.get_transport() >>> print ssh.get_transport().is_active() False >>>

问题:如何确定连接是否真的处于事件状态?

最佳答案

在 python 中,它是 easier to ask for forgiveness than permission .

像这样包装对 ssh.exec_command 的每次调用:

try: ssh.exec_command('ls') except socket.error as e: # Crap, it's closed. Perhaps reopen and retry?

关于python - 如何知道 paramiko SSH channel 是否断开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20147902/



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有