paramiko 无法实例化 transport

背景

Paramiko is a pure-Python [1] (2.7, 3.4+) implementation of the SSHv2 protocol [2], providing both client and server functionality. It provides the foundation for the high-level SSH library Fabric, which is what we recommend you use for common client use-cases such as running remote shell commands or transferring files.

Direct use of Paramiko itself is only intended for users who need advanced/low-level primitives or want to run an in-Python sshd.

以上是 paramiko 的官网介绍,简而言之,paramiko 是一个实用的 python ssh 库。

目前遇到一个问题,尝试用 paramiko 构建 ssh 连接,ssh 连接是基于 paramiko 的 transport 对象,因此需要先实例化 transport 对象,但是如果服务器宕机了,paramiko 会一直 pending 在实例化 transport 对象的过程中。

原因

Create a new SSH session over an existing socket, or socket-like object. This only creates the Transport object; it doesn’t begin the SSH session yet. Use connect or start_client to begin a client session, or start_server to begin a server session.

查看 paramiko 文档,发现 transport 是基于 socket 进行通信的,实例化 transport 对象需要传入 socket 对象或是类 socket 对象。而所谓类 socket 对象,其实就是 IP + port 的信息,这也是一般实例化 transport 的方法:

self.transport = paramiko.Transport((hostname, port))
self.transport.connect(username=username, password=password, **kwargs)

其实查看源码可以发现,这种类 socket 对象是 paramiko 对其做了向真实 socket 对象的转化:

...
if isinstance(sock, string_types):
    # convert "host:port" into (host, port)
    hl = sock.split(":", 1)
    self.hostname = hl[0]
    if len(hl) == 1:
        sock = (hl[0], 22)
    else:
        sock = (hl[0]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值