Reputation: 99
Here is my ssh
command that establish a tunnel with Postgres database by proxying through bastion host -
ssh -i C:/public/keys/my_key.pem -o "ProxyCommand ssh -W %h:%p username1@bastion_host.com" username2@ssh_host_ip -N -L 12345:postgres_host.com:5432 ssh_host_ip
I want to convert it into Python script using sshtunnel
utility. But have hard time to figure out what to pass where in the utility as depicted:
I went through few posts on Stack Overflow but did not see a straightforward way of doing it. Developers are using agent forwarding as a solution to Proxy command. Any straightforward conversion of above command to sshtunnel
or Paramiko or any other pythonic way would be really helpful.
Upvotes: 2
Views: 2084
Reputation: 202262
Based on Connecting to PostgreSQL database through SSH tunneling in Python, the following should do:
with SSHTunnelForwarder(
'bastion_host',
ssh_username="username1", ssh_password="password1",
remote_bind_address=('ssh_host_ip', 22)) as bastion:
bastion.start()
with SSHTunnelForwarder(
('127.0.0.1', bastion.local_bind_port),
ssh_username="username2", ssh_pkey="C:/public/keys/my_key.pem",
remote_bind_address=('postgres_host', 5432)) as ssh:
ssh.start()
engine = create_engine(
'postgresql://<db_username>:<db_password>@127.0.0.1:' +
str(ssh.local_bind_port) + '/database_name')
Upvotes: 2