【问题标题】:Tunneling TCP ports through ssh without blocking通过 ssh 隧道 TCP 端口而不阻塞
【发布时间】:2011-09-20 00:59:59
【问题描述】:

我正在尝试使用以下代码通过 pexpect 设置 ssh 隧道:

#!/bin/env python2.4

import pexpect, sys
child = pexpect.spawn('ssh -CfNL 0.0.0.0:3306:127.0.0.1:3306 user@server.com')
child.logfile = sys.stdout
while True:
    code = child.expect([
        'Are you sure you want to continue connecting \(yes/no\)\?',
        'password:',
        pexpect.EOF,
        pexpect.TIMEOUT
    ])
    if code == 0:
        child.sendline('yes')
    elif code == 1:
        child.sendline('passwordhere')
    elif code == 2:
        print ".. EOF"
        break
    elif code == 3:
        print ".. Timeout"
        break

我希望在发送密码并建立 ssh 隧道后,退出 while 循环,以便我可以继续处理其他业务逻辑。

但如果 ssh 隧道建立,上面的代码会阻止 util 超时(大约 30 秒)。

谁能给我一些关于如何避免阻塞的建议?

【问题讨论】:

  • 你愿意在没有密码的情况下使用ssh key auth吗?
  • 感谢您的评论。使用密钥进行 ssh 身份验证是可以的,但这能解决这个问题吗?恐怕问题是因为s​​sh进程在auth通过后没有立即退出。

标签: python pexpect ssh-tunnel


【解决方案1】:

我认为最简单的解决方案是使用 ssh 主机密钥身份验证,结合后台 ssh&... 这是一个非常基本的实现,但您可以增强它以在您完成后终止进程完成...另外,请注意我将-n 添加到您的ssh 参数中,因为我们正在后台处理该过程。

import subprocess

USER = 'user'
HOST = 'server.com'
cmd = r"""ssh -CfNnL 0.0.0.0:3306:127.0.0.1:3306 %s@%s &""" % (USER, HOST)
subcmd = cmd.split(' ')
retval = subprocess.Popen(subcmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stat = retval.poll()
while stat == None:
    stat = retval.poll()
print "ssh in background"

最后,如果您的ssh_config 中还没有ServerAliveInterval,请考虑将ssh 称为ssh -o ServerAliveInterval=30 <other_options_and_args>,以确保您尽快检测到隧道丢失,并防止其老化路径中的任何 NAT 实现(在不活动期间)。

【讨论】:

    猜你喜欢
    • 2021-05-24
    • 2020-01-28
    • 2021-05-11
    • 2016-11-10
    • 2016-09-09
    • 2014-09-03
    • 2013-05-26
    • 2016-09-17
    • 1970-01-01
    相关资源
    最近更新 更多