使用 Python 连接到 AWS EC2 上托管的 PostgreSQL 数据库

问题描述 投票:0回答:1

我是AWS EC2和PostgreSQL领域的新手。我已经共享了托管的 PostgreSQL 数据库的一些访问 ID,并且我测试了是否可以使用 TablePlus 连接到数据库并成功做到了这一点。截图是,

enter image description here

它有数据库的这些详细信息,


  • 主机 = 127.0.0.1(本地)
  • 端口 = 5432(默认)
  • 用户:测试
  • 密码:********(1)
  • 数据库=测试数据
  • SSL模式:首选

EC2 服务器的详细信息,


  • 服务器:aa.bbb.ccc.dd
  • 端口:23(默认)
  • 用户:星爵
  • 密码:************(2)

我想使用 python 连接到数据库,特别是使用 psycopg2 和 parmiko,我使用了下面的代码,但没有成功。有人可以指导我吗?

aws_db_config.json

{
    "user": "test" (your_postgres_username),
    "password": "*********(1)" (your_postgres_password),
    "host": "aa.bbb.ccc.dd" (your_ec2_public_dns_or_ip),
    "port": "5432" (your_postgres_port),
    "database": "test_data",
    "sslmode": "prefer"  // or "disable" depending on your setup
}

我的代码,

import paramiko
import psycopg2
import json
import socket

def read_db_config_json(file_path):
    """Read database connection configuration from JSON file."""
    with open(file_path, 'r') as file:
        db_config = json.load(file)
    return db_config

def create_ssh_tunnel(ssh_host, ssh_port, ssh_user, ssh_key_path, local_port, remote_host, remote_port):
    """Create an SSH tunnel to the PostgreSQL server."""
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ssh_host, port=ssh_port, username=ssh_user, key_filename=ssh_key_path)

    # Create a tunnel for the PostgreSQL connection
    transport = ssh.get_transport()
    tunnel = transport.open_channel(
        'direct-tcpip',
        (remote_host, remote_port),
        ('localhost', local_port)
    )
    return ssh, tunnel

def test_postgres_connection_via_ssh(config_file_path, ssh_config):
    """Connect to the PostgreSQL server via SSH tunneling and test the connection."""
    try:
        # Read the JSON config file
        db_config = read_db_config_json(config_file_path)

        # Create an SSH tunnel
        ssh, tunnel = create_ssh_tunnel(
            ssh_config['ssh_host'],
            ssh_config['ssh_port'],
            ssh_config['ssh_user'],
            ssh_config['ssh_key_path'],
            ssh_config['local_port'],
            db_config['host'],
            db_config['port']
        )

        # Update database config to use the local port
        db_config['host'] = 'localhost'
        db_config['port'] = ssh_config['local_port']

        # Establish the connection to PostgreSQL through the SSH tunnel
        connection = psycopg2.connect(**db_config)

        # Create a cursor object to execute SQL queries
        cursor = connection.cursor()

        # Query to get PostgreSQL version
        cursor.execute("SELECT version();")
        db_version = cursor.fetchone()
        print(f"Connected to PostgreSQL server: {db_version}\n")

        # Close the cursor and connection
        cursor.close()
        connection.close()

        # Close the SSH tunnel
        tunnel.close()
        ssh.close()

    except Exception as error:
        print(f"Error connecting to the PostgreSQL database: {error}")

if __name__ == "__main__":
    # Provide the path to your aws_db_config.json
    # SSH configuration for the EC2 instance
    ssh_config = {
        'ssh_host': 'aa.bbb.ccc.dd',
        'ssh_port': 23,  # default SSH port
        'ssh_user': 'starlord',
        'ssh_key_path': r'./saved.pem',
        'local_port': 5432  # local port for the tunnel
    }
    test_postgres_connection_via_ssh('aws_db_config.json', ssh_config)

但这给我带来了错误,

Error connecting to the PostgreSQL database: encountered RSA key, expected OPENSSH key

连接和测试连接的最佳方式是什么?

python postgresql amazon-ec2 psycopg2 ssh-tunnel
1个回答
0
投票

检查用于通过 ssh 隧道连接的密钥格式,消息指出它需要以

(-----BEGIN OPENSSH PRIVATE KEY-----)
开头的 OPENSSH 格式:

RSA 密钥格式:SSH 密钥的传统格式

(-----BEGIN RSA PRIVATE KEY-----)
。 OPENSSH 密钥格式:一种较新的私钥格式
(-----BEGIN OPENSSH PRIVATE KEY-----)

如果您需要转换它,请使用 ssh-keygen 或 putty。

© www.soinside.com 2019 - 2024. All rights reserved.