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

前端 未结 2 1688
情歌与酒
情歌与酒 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)
    
    0 讨论(0)
  • 2020-12-14 00:34

    Use the psycopg2 module.

    You will need to use the ssl options in your connection string, or add them as key word arguments:

    import psycopg2
    
    conn = psycopg2.connect(dbname='yourdb', user='dbuser', password='abcd1234', host='server', port='5432', sslmode='require')
    

    In this case sslmode specifies that SSL is required.

    To perform server certificate verification you can set sslmode to verify-full or verify-ca. You need to supply the path to the server certificate in sslrootcert. Also set the sslcert and sslkey values to your client certificate and key respectively.

    It is explained in detail in the PostgreSQL Connection Strings documentation (see also Parameter Key Words) and in SSL Support.

    0 讨论(0)
提交回复
热议问题