Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a SSH tunnel using Python and Paramiko?

I need to create tunneling to read information from a database. I use Paramiko, but I have not worked with tunneling yet. Please provide an example of a simple code that creates and closes a tunnel.

like image 947
Ivan Avatar asked Nov 17 '11 15:11

Ivan


People also ask

How do I use Paramiko in Python?

A Paramiko SSH Example: Connect to Your Server Using a Password. This section shows you how to authenticate to a remote server with a username and password. To begin, create a new file named first_experiment.py and add the contents of the example file. Ensure that you update the file with your own Linode's details.

How do I create a SSH connection in python?

sshserver.py will run an SSH server on port 2222. Connect to this server with an SSH client using the username admin and password aaa, and try typing some commands: $ ssh admin@localhost -p 2222 admin@localhost's password: aaa >>> Welcome to my test SSH server.


2 Answers

At work we usually create ssh tunnels forwarding ports. The way we do that is, by using the standard command ssh -L port:addr:port addr with subprocess running in a separate thread. I found this useful link: https://github.com/paramiko/paramiko/blob/master/demos/forward.py with an example of doing port forwarding with paramiko.

like image 75
dario Avatar answered Oct 19 '22 06:10

dario


I used sshtunnel for my projects. Example of the forwarding remote local MySQL port to the host local port:

pip install sshtunnel
python -m sshtunnel -U root -P password -L :3306 -R 127.0.0.1:3306 -p 2222 localhost
like image 15
pahaz Avatar answered Oct 19 '22 07:10

pahaz