Dec-24-2023, 09:28 AM
I want to connect my remote database using python. Below are the frontend configuration for DBever. I need to know how to connect to the DB.
[attachment=2690]
[attachment=2691]
[attachment=2690]
[attachment=2691]
psycopg2
library for PostgreSQL connectivity and paramiko
for SSH tunneling.pip install psycopg2 paramikoStep 2: Create an SSH Tunnel
paramiko
library for this task. Here's a sample script:python import paramiko # Jump server details jump_server_host = 'jump_server_ip' jump_server_port = 22 jump_server_username = 'your_username' jump_server_private_key_path = 'path/to/your/private/key.pem' # PostgreSQL server details database_host = 'postgres_server_ip' database_port = 5432 database_username = 'your_db_username' database_password = 'your_db_password' # Create SSH client ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect( jump_server_host, port=jump_server_port, username=jump_server_username, key_filename=jump_server_private_key_path ) # Create the SSH tunnel ssh_tunnel = ssh_client.get_transport().open_dynamic_tunnel( ('localhost', 0), (database_host, database_port) ) # Leave the SSH connection open in the background # You can now connect to the PostgreSQL database through the SSH tunnel ```Step 3: Connect to PostgreSQL
psycopg2
library to connect to the PostgreSQL database through the tunnel:```python import psycopg2 # Connect to PostgreSQL through the SSH tunnel database_connection = psycopg2.connect( host='localhost', # Connect to the local end of the SSH tunnel port=ssh_tunnel.local_address[1], # Use the local port assigned by the SSH tunnel user=database_username, password=database_password, database='your_database_name' ) # Now you can perform database operations using the database_connection object ```Conclusion