cli.py 文件源码

python
阅读 25 收藏 0 点赞 0 评论 0

项目:stups-gotthard 作者: zalando-stups 项目源码 文件源码
def setup_tunnel(user, odd_host, remote_host, remote_port, tunnel_port):
    tunnel_port = get_port(tunnel_port)

    if not tunnel_port:
        raise ClickException('Could not get a free local port for listening')

    ssh_command = ['ssh',
                   '-oExitOnForwardFailure=yes',
                   '-oBatchMode=yes',
                   '-L', '{}:{}:{}'.format(tunnel_port, remote_host, remote_port),
                   '{}@{}'.format(user, odd_host),
                   '-N']

    process = subprocess.Popen(ssh_command, preexec_fn=os.setpgrp)

    logging.debug("Testing if tunnel is listening")
    for i in range(10):
        try:
            time.sleep(0.1)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect(('localhost', tunnel_port))
            s.close()
            return tunnel_port, process
        except Exception:
            pass
        finally:
            s.close()

    logging.warning("Could not connect to port {}, killing ssh process with pid {}".format(tunnel_port, process.pid))
    process.kill()
    process, tunnel_port = None, None

    return tunnel_port, process
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号