How to connect to a remote PostgreSQL database through SSL with Python

前端 未结 2 1689
情歌与酒
情歌与酒 2020-12-13 23:46

I want to connect to a remote PostgreSQL database through Python to do some basic data analysis. This database requires SSL (verify-ca), along with three files (which I have

2条回答
  •  一个人的身影
    2020-12-14 00:29

    You may also use an ssh tunnel with paramiko and sshtunnel:

    import psycopg2
    import paramiko
    from sshtunnel import SSHTunnelForwarder
    
    mypkey = paramiko.RSAKey.from_private_key_file('/path/to/private/key')
    
    tunnel =  SSHTunnelForwarder(
            (host_ip, 22),
            ssh_username=username,
            ssh_pkey=mypkey,
            remote_bind_address=('localhost', psql_port))
    
    tunnel.start()
    conn = psycopg2.connect(dbname='gisdata', user=psql_username, password=psql_password, host='127.0.0.1', port=tunnel.local_bind_port)
    

提交回复
热议问题