Skip to content

Instantly share code, notes, and snippets.

@MediaByte
Forked from deehzee/psycopg2_sshtunnel.py
Created August 5, 2019 00:37
Show Gist options
  • Select an option

  • Save MediaByte/2f972c6d9a71eebfebdd5f23fce373b1 to your computer and use it in GitHub Desktop.

Select an option

Save MediaByte/2f972c6d9a71eebfebdd5f23fce373b1 to your computer and use it in GitHub Desktop.

Revisions

  1. @deehzee deehzee revised this gist Feb 8, 2017. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions psycopg2_sshtunnel.py
    Original file line number Diff line number Diff line change
    @@ -10,7 +10,7 @@
    ssh_username='<username>',
    ssh_private_key='</path/to/private/key>',
    remote_bind_address=('localhost', 5432),
    local_bind_address=('localhost', 5434),
    local_bind_address=('localhost',6543), # could be any available port
    )
    # Start the tunnel
    tunnel.start()
    @@ -32,7 +32,8 @@
    """)

    # Get the result
    cur.fetchall()
    result = cur.fetchall()
    print(result)

    # Close connections
    conn.close()
  2. @deehzee deehzee created this gist Feb 8, 2017.
    48 changes: 48 additions & 0 deletions psycopg2_sshtunnel.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    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()
    ...