配置

  • 本地:本地计算机,它将创建ssh连接并在REMOTE框上发出命令。
  • PROXY:一个EC-2实例,通过ssh可以访问LOCAL和REMOTE。
  • 远程:位于NAT路由器后面的远程计算机(LOCAL无法访问,但将打开与PROXY的连接并允许LOCAL隧道连接到它)。

  • 端口转发步骤(通过命令行)
  • 创建从REMOTE到PROXY的SSH连接,以将REMOTE机器上端口22上的SSH流量转发到PROXY服务器上的端口8000。

  • 创建从LOCAL到PROXY的ssh隧道,并将ssh流量从LOCAL:1234转发到PROXY:8000(然后将其转发到REMOTE:22)。

  • 创建从LOCAL到REMOTE(通过PROXY)的转发ssh连接。


  • Paramiko 研究
    我看过handfulquestions与使用Paramiko进行端口转发有关,但是它们似乎无法解决这种特定情况。
    我的问题
    如何使用Paramiko运行上面的步骤2和3?我基本上想运行:
    import paramiko
    
    # Create the tunnel connection
    tunnel_cli = paramiko.SSHClient()
    tunnel_cli.connect(PROXY_HOSTNAME, PROXY_PORT, PROXY_USER)
    
    # Create the forwarded connection and issue commands from LOCAL on the REMOTE box
    fwd_cli = paramiko.SSHClient()
    fwd_cli.connect('localhost', LOCAL_PORT, REMOTE_USER)
    fwd_cli.exec_command('pwd')
    

    最佳答案

    可以在@bitprohet's blog here中找到有关Paramiko在“幕后”所做的详细说明。

    假设上面的配置,我正在工作的代码如下所示:

    from paramiko import SSHClient
    
    # Set up the proxy (forwarding server) credentials
    proxy_hostname = 'your.proxy.hostname'
    proxy_username = 'proxy-username'
    proxy_port = 22
    
    # Instantiate a client and connect to the proxy server
    proxy_client = SSHClient()
    proxy_client.load_host_keys('~/.ssh/known_hosts/')
    proxy_client.connect(
        proxy_hostname,
        port=proxy_port,
        username=proxy_username,
        key_filename='/path/to/your/private/key/'
    )
    
    # Get the client's transport and open a `direct-tcpip` channel passing
    # the destination hostname:port and the local hostname:port
    transport = proxy_client.get_transport()
    dest_addr = ('0.0.0.0', 8000)
    local_addr = ('127.0.0.1', 1234)
    channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)
    
    # Create a NEW client and pass this channel to it as the `sock` (along with
    # whatever credentials you need to auth into your REMOTE box
    remote_client = SSHClient()
    remote_client.load_host_keys(hosts_file)
    remote_client.connect('localhost', port=1234, username='remote_username', sock=channel)
    
    # `remote_client` should now be able to issue commands to the REMOTE box
    remote_client.exec_command('pwd')
    

    关于python - Paramiko:围绕NAT路由器进行端口转发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18968069/

    10-12 14:00