-
-
Save MediaByte/2f972c6d9a71eebfebdd5f23fce373b1 to your computer and use it in GitHub Desktop.
How to Connect To PostgreSQL Using SSHTunnelForwarder and Psycopg2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import psycopg2 | |
| from sshtunnel import SSHTunnelForwarder | |
| # For interactive work (on ipython) it's easier to work with explicit objects | |
| # instead of contexts. | |
| # Create an SSH tunnel | |
| tunnel = SSHTunnelForwarder( | |
| ('128.199.169.188', 22), | |
| ssh_username='<username>', | |
| ssh_private_key='</path/to/private/key>', | |
| remote_bind_address=('localhost', 5432), | |
| local_bind_address=('localhost', 5434), | |
| ) | |
| # Start the tunnel | |
| tunnel.start() | |
| # Create a database connection | |
| conn = psycopg2.connect( | |
| database='<database>', | |
| user='<db_user>', | |
| host=tunnel.local_bind_host, | |
| port=tunnel.local_bind_port, | |
| ) | |
| # Get a database cursor | |
| cur = conn.cursor() | |
| # Execute SQL | |
| cur.execute(""" | |
| SQL-Statements; | |
| """) | |
| # Get the result | |
| cur.fetchall() | |
| # Close connections | |
| conn.close() | |
| # Stop the tunnel | |
| tunnel.stop() | |
| # Alternatively use contexts... | |
| with SSHTunnelForwarder(...) as tunnel: | |
| with psycopg2.connect(...) as connect: | |
| cur = conn.cursor() | |
| ... | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment