Skip to content

Instantly share code, notes, and snippets.

@anthonycarminati
Created December 9, 2016 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonycarminati/24b0441e9185d52d42ac07e807b9c2e5 to your computer and use it in GitHub Desktop.
Save anthonycarminati/24b0441e9185d52d42ac07e807b9c2e5 to your computer and use it in GitHub Desktop.
psycopg2_with_ssh_tunneling
import psycopg2
from sshtunnel import SSHTunnelForwarder
try:
with SSHTunnelForwarder(
('<server ip address>', 22),
#ssh_private_key="</path/to/private/ssh/key>",
### in my case, I used a password instead of a private key
ssh_username="<server username>",
ssh_password="<mypasswd>,
remote_bind_address=('localhost', 5432)) as server:
server.start()
print "server connected"
params = {
'database': '<dbname>',
'user': '<dbusername>',
'password': '<dbuserpass>',
'host': 'localhost',
'port': local_bind_port
}
conn = psycopg2.connect(**params)
curs = conn.cursor()
print "database connected"
except:
print "Connection Failed"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment