用户 postgres 的 Psycopg2 对等身份验证

Psycopg2 peer authentication for user postgres

我似乎已经正确安装了 PostgreSQL 9.5.5。和 Ubuntu 16.04 上的 Psycopg2,可以通过以下方式登录:

sudo -u postgres psql

如果我然后发出 \conninfo,我得到以下信息:

You are connected to database "postgres" as user "postgres" via socket in "/var/run/postgresql" at port "5432".

我当然应该能够以与 here 所示相同的方式通过 psycopg2 进行连接,但是脚本:

#!/usr/bin/python
import psycopg2
conn = psycopg2.connect("dbname=postgres user=postgres") 
conn.close()

给我:

psycopg2.OperationalError: FATAL:  Peer authentication failed for user "postgres"

我只希望 PostgreSQL 供个人使用,所以我不想启用 TCP 身份验证。

如何在 Psycopg2 中正确使用用户 "postgres" 的对等身份验证?

这就是你打电话的样子。

!/usr/bin/python
import psycopg2
conn = psycopg2.connect(database="postgres", user="postgres", password="postgres", port=5432)

conn.close()

对等身份验证的工作原理是将连接字符串中的 Postgres 用户名与作为 运行 脚本的 Linux 用户的名称进行比较。

使用 sudo -u postgres 尝试 运行 您的 Python 脚本。

您需要提供主机

conn = psycopg2.connect("dbname='template1' user='dbuser' host='localhost' password='dbpass'")

这些是postgresql的一些认证方式

peer 表示它将信任 UNIX 用户的身份(真实性)。所以不要求密码。

md5 表示它会一直要求输入密码,并在用 MD5 散列后验证它。

trust 表示它永远不会要求输入密码,并且始终信任任何连接。

根据你的情况,你必须像这样兑换:

host all all all 127.0.0.1/32 ident

host all all 127.0.0.1/32 md5

host all all ::1/128 ident

host all all ::1/128 md5