SSH tunnel forwarding with jump host and remote database
I figured it out. It works with a combination of ssh config settings and the SSHTunnelForwarder context manager from the sshtunnel library.
Using the following model and naming conventions:
[A: local host] -> [B: jump host] -> [C: target host] => [D: RDS MySQL host]
I set up my ~/.ssh/config to get from A to C through B:
Host C_ssh_shortcut
HostName C_host
User C_user
Port 22
ForwardAgent yes
ProxyCommand ssh B_user@B_host -W %h:%p
I added the key/keys I used to log in to B and C to my ssh-agent:
ssh-add
And finally I set up SSHTunnelForwarder:
import sqlalchemy
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(
"C_ssh_shortcut", # The SSHTunnelForwarder "ssh_address_or_host" argument, which takes care of bypassing B through the ProxyCommand set up in ~/.ssh/config
remote_bind_address=(D_host, 3306), # Points to your desired destination, ie. database host on 3306, which is the MySQL port
local_bind_address=('', 1111) # Gives a local way to access this host and port on your machine. '' is localhost / 127.0.0.1, 1111 is an unused port
) as server:
connection_string = "mysql+pymysql://D_user:D_password@localhost:1111/D_dbname" # note that D_host and D_port were replaced by the host and port defined in "local_bind_address"
engine = sqlalchemy.create_engine(connection_string)
# do your thing
From here, I am able to use my engine as usual to interact with my database.
How to ssh into another machine immediately after logging into a machine
Say you first execute ssh server1
, then on server1
, you execute ssh server2
. The thing you want is when you execute ssh server1
on your local computer, you can automatically login to server2
.
The way to do this is add a script that runs automatically when you login to server1
. You can do this by just adding the code ssh server2
into your ~/.bashrc
file (if you are using Ubuntu. Or in other OS, the file name is similar to ~/.bashxxx
).
But after doing so, you still need to type password for server2
every time you login into server1
. If you don't want to type server2
's password by hand, you can use a password-free ssh connection from server1
to server2
. See this page to find out how.
Related Topics
How to Put All Command Arguments in One Variable
Unanticipated Segmentation Fault in C
How to Do an Initial Setup of Slapd Olc with Ldapmodify
Why This Shell Won't Work If It's Called from Rc.Local But Ssh
Cuda-Gdb Not Working in Nsight on Linux
How to Delay Pipe Netcat to Connect on First Input
Why Does Cat <<< $Var1 Lose Newlines
How to Make Webdriver Testsuite Created in Windows Machine to Run in a Linux Box
How to Add External References in Monodevelop
Linux Shell Script - Find All Files and Run a Command on Each One of Them
Make Command Not Working in Ns 2.35
Command Execution with Nohup in Background
Ssl/Qsslsocket_Openssl.Cpp:1414: Error: Q_Ssl_Ctrl Was Not Declared in This Scope Error