Connect to remote PostgresDB from local Development-Server

Mein Problem war, dass ich lokal mit Python entwickle, jedoch auf meine Postgresql-DB auf dem Uberspace-Server zugreifen möchte. Hierzu war es notwendig einen SSL-Tunnel mit der Python-Library „sshtunnel“ einzurichten.

import psycopg2
from sshtunnel import SSHTunnelForwarder

try:
    uberspace_server = 'xxx'
    my_ssh_username = 'xxx'
    my_ssh_password = 'xxx'
    my_ssh_port = xxx
    my_postgres_db = 'xxx'
    my_postgres_user ='xxx'
    my_postgres_password = 'xxx'

    with SSHTunnelForwarder(
         (uberspace_server, 22),
         ssh_username = my_ssh_username,
         ssh_password = my_ssh_password, 
         remote_bind_address=('localhost', my_ssh_port)) as server:
         server.start()
         print ("server connected")
         params = {
             'database': my_postgres_db,
             'user': my_postgres_user,
             'password': my_postgres_password,
             'host': 'localhost',
             'port': server.local_bind_port
             }
         conn = psycopg2.connect(**params)
         curs = conn.cursor()
         print("database connected")
except:
    print("Connection Failed")

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert