1

I want to establish an SSH tunnel on an existing connection. The tricky part is doing it from a script (a custom shell I need to allow users only some specific things, like setting up this tunnel).

Normally you can do:

<enter>
~C
ssh> -L 8080:localhost:80

But I need to be able to do this from a running python script. I tried:

print("\n~C -L 8080:localhost:80")

but that unfortunately was too simple a thought.

So, how do I setup the tunnel from a running Python script?

(as a side-issue, I also have to prevent ssh -N -L x:host:y host.example.com, but still allow port forwards to be set up with my custom shell).

  • I don't get it: were you planning to run that script on the client or on the server? – Gilles Feb 24 '15 at 17:28
  • On the server, as a shell where people log in. However, I think I have a working solution now: I just setup the tunnel with nc -l 2222 0<backpipe | nc host.example.com 22 1>backpipe – Halfgaar Feb 25 '15 at 9:07
  • the client specifies a tunnel to set up; the server allows it or not. – Skaperen Feb 27 '15 at 12:45
  • I actually ran into more problems. I solved it by writing a proxy tool myself in C++/Qt. – Halfgaar Jun 19 '15 at 8:38
2

Try use sshtunnel lib.

Example:

from sshtunnel import SSHTunnelForwarder
from time import sleep

with SSHTunnelForwarder(
    ('localhost', 2222),
    ssh_username="vagrant",
    ssh_password="vagrant",
    remote_bind_address=('127.0.0.1', 3306)) as server:

    print(server.local_bind_port)
    while True:
        # press Ctrl-C for stopping
        sleep(1)

print('FINISH!')

or CLI:

python -m sshtunnel -U vagrant -P vagrant -L :3306 -R 127.0.0.1:3306 -p 2222 localhost
  • I'll keep it in mind for the future. For now, I solved it by writing a proxy in C++/Qt myself. – Halfgaar Jun 19 '15 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.