24

I'm trying to do some port forwarding from a python app using Paramiko. I can set up the SSH connection just fine, but I'm a bit stumped as to how to use paramiko.Transport. I've already found this file, but I can't work out what's going on in it. From looking at the paramiko.Transport docs, it seems that a single line using the open_channel function, but I can't work out how to implement that. I'm trying to replicate a simple ssh -L 8000:localhost:8000.

Can anyone help me out?

Martin Prikryl
  • 167,268
  • 50
  • 405
  • 846
TimD
  • 1,341
  • 3
  • 11
  • 20
  • 2
    So I've managed to get a little further with this, and think I'm probably barking up the wrong tree. I've worked out how to operate the open_channel command by calling get_transport() on the origninal connection, but then when I try to open a direct or forwarded tcpip connection with it, I get Administratively Prohibited from the server, which is fine with a -L port forward from a normal SSH session. Any ideas? – TimD Jul 02 '12 at 15:08
  • 1
    Can you please post your code / a section of the code you're using? – Adam Baxter Aug 14 '12 at 06:54

2 Answers2

19

Please find some code using paramiko-1.7.7.1, pycrypto-2.6 and the forward.py script from which I did remove code from the line 115 to the end (to avoid options parsing).

import paramiko, sys
from forward import forward_tunnel

remote_host = "target_host"
remote_port = 8000
local_port  = 8000
ssh_host    = "my_ssh_host"
ssh_port    = 22

user     = "login"
password = "s3cr3t"

transport = paramiko.Transport((ssh_host, ssh_port))

# Command for paramiko-1.7.7.1
transport.connect(hostkey  = None,
                  username = user,
                  password = password,
                  pkey     = None)

try:
    forward_tunnel(local_port, remote_host, remote_port, transport)
except KeyboardInterrupt:
    print 'Port forwarding stopped.'
    sys.exit(0)

I've tested it successfully from a Windows station, using a ssh server under Red Hat and pointing to a 3rd server. (I'm using Python 2.7.2)

Hope it helps,

Tzach
  • 12,240
  • 11
  • 63
  • 104
Y__
  • 1,619
  • 1
  • 11
  • 23
  • 3
    The `forward.py` link is broken. Please see this one: https://github.com/paramiko/paramiko/blob/master/demos/forward.py – alanjds Oct 29 '15 at 20:39
8

You can use https://github.com/pahaz/sshtunnel

pip install sshtunnel

Code example:

import sshtunnel

with sshtunnel.open(
    (ssh_host, ssh_port),
    ssh_host_key=None,
    ssh_username=ssh_user,
    ssh_password=ssh_password,
    ssh_private_key=None,
    remote_bind_address=(REMOTE_HOST, REMOTE_PORT)) as server:

    def do_something(port):
        # Do something with port
        pass

    print("LOCAL PORT:", server.local_bind_port)

    do_something(server.local_bind_port)
pahaz
  • 771
  • 8
  • 13