python decorator ssh_如何知道paramiko SSH通道是否断开连接?

我正在设计使用paramiko进行SSH连接的测试用例。测试用例通常包含有包装器的paramiko.exec_command()调用(称为run_command())。这里self.ssh是paramiko.SSHClient()的维持。在每次调用之前,我使用decorator检查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

>>>

问题:如何确定连接是否处于活动状态?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值