如何使用Python通过SSL连接到远程PostgreSQL数据库 [英] How to connect to a remote PostgreSQL database through SSL with Python

查看:427
本文介绍了如何使用Python通过SSL连接到远程PostgreSQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Python连接到远程PostgreSQL数据库以进行一些基本数据分析。该数据库需要SSL(verify-ca),以及三个文件(我拥有):

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):


  • 服务器根证书文件

  • 客户端证书文件

  • 客户端密钥文件

我还没有能够找到描述如何与Python建立连接的教程。
感谢您的帮助。

I have not been able to find a tutorial which describes how to make this connection with Python. Any help is appreciated.

推荐答案

使用 psycopg2 模块。

您需要在连接字符串中使用ssl选项,或将它们添加为关键字参数:

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')

在这种情况下, sslmode 指定需要SSL。

In this case sslmode specifies that SSL is required.

要执行服务器证书验证,可以将 sslmode 设置为 verify-full verify-ca 。您需要在 sslrootcert 中提供服务器证书的路径。还要分别将 sslcert sslkey 的值分别设置为客户端证书和密钥。

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.

在PostgreSQL 连接字符串文档(另请参阅参数关键字)以及 SSL支持

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

这篇关于如何使用Python通过SSL连接到远程PostgreSQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆