python使用libpq-pgpass连接到PostgreSQL [英] python connect to postgresql with libpq-pgpass

查看:130
本文介绍了python使用libpq-pgpass连接到PostgreSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到有一种更安全的方法,无需使用 http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html 。但是不幸的是,我无法找到任何有关如何将其导入我的python程序以及如何使我的postgresql服务器使用此文件的示例。请帮忙。

I read there is a more secure way to connect to postgresql db without specifying password in source code using http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html. But unfortunatelly I was not able to find any examples of how to import it to my python program and how made my postgresql server to use this file. Please help.

推荐答案

您不会将其导入到 Python 程序中。 .pgpass 的要点是,它是受系统文件许可权约束的常规文件,而 libpq 驱动程序受诸如 psycopg2 用于连接到 Postgres ,它将在该文件中查找密码,而不是要求密码在源代码中或提示输入密码。

You don't import it into your Python program. The point of .pgpass is that it is a regular file subject to the system's file permissions, and the libpq driver which libraries such as psycopg2 use to connect to Postgres will look to this file for the password instead of requiring the password to be in the source code or prompting for it.

此外,这不是服务器端文件,而是客户端文件。因此,在* nix框上,您将有一个〜/ .pgpass 文件,其中包含要建立的各种连接的凭据。

Also, this is not a server-side file, but a client-side one. So, on a *nix box, you would have a ~/.pgpass file containing the credentials for the various connections you want to be able to make.

根据OP的评论进行编辑:

为了实现 psycopg2 通过 .pgpass 正确地进行身份验证:

Two main things need to happen in order for psycopg2 to correctly authenticate via .pgpass:


  1. 在传递给 psycopg2.connect

  2. 的字符串中指定密码到将通过 psycopg2 连接的用户的 .pgpass 文件。

  1. Do not specify a password in the string passed to psycopg2.connect
  2. Make sure the correct entry is added to the .pgpass file for the user who will be connecting via psycopg2.

例如,要使此特定用户在 localhost 端口 5432 上的所有数据库中都可以使用,请将以下行添加到该用户的 .pgpass 文件:

For example, to make this work for all databases for a particular user on localhost port 5432, you would add the following line to that user's .pgpass file:

localhost:5432:*:<username>:<password>

然后调用 connect

conn = psycopg2.connect("host=localhost dbname=<dbname> user=<username>")

psycopg2 的基础 libpq 驱动程序然后,用户将使用 .pgpass 文件获取密码。

The underlying libpq driver that psycopg2 uses will then utilize the .pgpass file to get the password.

这篇关于python使用libpq-pgpass连接到PostgreSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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