Skip to content

Instantly share code, notes, and snippets.

@riddhi89
Created October 22, 2018 00:32
Show Gist options
  • Save riddhi89/9d53140dec7c17e63e22a0b5ab43f99f to your computer and use it in GitHub Desktop.
Save riddhi89/9d53140dec7c17e63e22a0b5ab43f99f to your computer and use it in GitHub Desktop.
Connecting to a private AWS RDS instance in python
from sshtunnel import SSHTunnelForwarder
import pymysql
with SSHTunnelForwarder(
('ec2-52-202-194-76.public-ec2-instance.amazonaws.com'),
ssh_username="ec2-user",
ssh_pkey="~/ssh-tunnel-rds.pem",
remote_bind_address=('private-rds-instance.ckfkidfytpr4.us-east-1.rds.amazonaws.com', 3306)
) as tunnel:
print("****SSH Tunnel Established****")
db = pymysql.connect(
host='127.0.0.1', user="rdsuser",
password="rdspassword", port=tunnel.local_bind_port
)
# Run sample query in the database to validate connection
try:
# Print all the databases
with db.cursor() as cur:
cur.execute('SHOW DATABASES')
for r in cur:
print(r)
finally:
db.close()
print("YAYY!!")
@Roan1669
Copy link

Hi there,

I am very new to this and was wondering if you could help. I have a postgres database that I SSH into via dbeaver.

I am not 100% sure which credentials I will put in where on the script

@pnost
Copy link

pnost commented Sep 5, 2022

saved my day. thanks a lot.

@lamhfada
Copy link

lamhfada commented Oct 3, 2022

thank you!!

@Fhernd
Copy link

Fhernd commented Jul 1, 2023

It worked! Thanks a lot!

Previously I was using the mysql-connector-python Python module but the MySQL server connection was impossible.

@pwinterfive
Copy link

It worked! Thank you

@nadavkav
Copy link

nadavkav commented Jun 8, 2024

Thanks! that was very helpful :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment