2

How do I implement remote port forwarding with Paramiko? I have seen examples doing the local port forward but this puzzles me. I would like to implement

ssh -N -R 2210:localhost:5000 username@remotehost

with paramiko. (forward remotehost port 2210 to localhost port 5000, do not open shell as it is not permitted). I have tried

ssh=paramiko.SSHClient()
ssh.connect(remotehost, username=remoteusername, key_filename="/....")
transport = ssh.get_transport()
transport.open_channel(......)

but all combinations of dest_addr, src_addr and action (direct-tcpip, forwarded-tcpip) seem to fail to ChannelException (administrately prohibited). My command line ssh works, so I am authorised to do this, but I don't know how to do the Paramiko implementation.

Any ideas?

Hannu

Hannu
  • 11,685
  • 4
  • 35
  • 51
  • I can of course revert back to just subprocess.Call and execute ssh but I would like to keep it in code to help monitoring connection status. – Hannu Sep 14 '16 at 18:06
  • This answer solved this for me: http://stackoverflow.com/questions/11294919/port-forwarding-with-paramiko#answer-12106387 – IxDay Nov 07 '16 at 16:46

1 Answers1

3

Sample script showing how to do remote port forwarding over paramiko. This script connects to the requested SSH server and sets up remote port forwarding (the openssh -R option) from a remote port through a tunneled connection to a destination reachable from the local machine.

Example: ssh -R 4000:internal.example.com:80 public.example.com

import socket
import select
import sys
import threading

import paramiko


def handler(chan, host, port):
    sock = socket.socket()
    try:
        sock.connect((host, port))
    except Exception as e:
        print("Forwarding request to %s:%d failed: %r" % (host, port, e))
        return

    print(
        "Connected!  Tunnel open %r -> %r -> %r"
        % (chan.origin_addr, chan.getpeername(), (host, port))
    )
    while True:
        r, w, x = select.select([sock, chan], [], [])
        if sock in r:
            data = sock.recv(1024)
            if len(data) == 0:
                break
            chan.send(data)
        if chan in r:
            data = chan.recv(1024)
            if len(data) == 0:
                break
            sock.send(data)
    chan.close()
    sock.close()


def reverse_forward_tunnel(server_port, remote_host, remote_port, transport):
    transport.request_port_forward("", server_port)
    while True:
        chan = transport.accept(1000)
        if chan is None:
            continue
        thr = threading.Thread(
            target=handler, args=(chan, remote_host, remote_port)
        )
        thr.setDaemon(True)
        thr.start()


def main():
    """
    ssh -R 4000:internal.example.com:80 public.example.com
    """
    ssh_host = 'public.example.com'
    ssh_port = 22
    ssh_user = 'root'
    ssh_pass = 'password'
    remote_bind_port = 4000  # port on server to forward
    forward_host = 'internal.example.com'  # dest host to forward to
    forward_port = 80  # dest port to forward to

    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())

    try:
        client.connect(
            ssh_host,
            ssh_port,
            username=ssh_user,
            password=ssh_pass,
        )
    except Exception as e:
        print("*** Failed to connect to %s:%d: %r" % (ssh_host, ssh_port, e))
        sys.exit(1)

    print(
        "Now forwarding remote port %d to %s:%d ..."
        % (remote_bind_port, forward_host, forward_port)
    )

    try:
        reverse_forward_tunnel(
            remote_bind_port, forward_host, forward_port, client.get_transport()
        )
    except KeyboardInterrupt:
        print("C-c: Port forwarding stopped.")
        sys.exit(0)


if __name__ == "__main__":
    main()

FeiXia
  • 101
  • 5