postgresql 身份验证失败,用户与 dbuser 不同

4 投票
1 回答
3625 浏览
提问于 2025-04-18 07:50

我在CentOS 6.5上安装并运行了PostgreSQL,版本是9.3。目前我有一个Python脚本,使用psycopg2库向一个叫“testdb”的PostgreSQL数据库插入数据。当我在服务器上运行这个脚本时,遇到了一个错误:

Traceback (most recent call last):
File "collector2.py", line 10, in <module>
con = psycopg2.connect(database='testdb', host = 'localhost', user = 'foo', password = '12345')  
File "/usr/lib64/python2.6/site-packages/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: FATAL:  Ident authentication failed for user "foo"

这是我的pg_hba.conf文件。我不太明白哪里出了问题。

#TYPE  DATABASE        USER            ADDRESS                 METHOD

local   all             postgres                                peer
# "local" is for Unix domain socket connections only
local   all             all                                     peer
local   all             all                                     ident
local   testdb     foo                              peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            ident
# IPv6 local connections:
host    all             all             ::1/128                 ident
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            ident
#host    replication     postgres        ::1/128                 ident

我已经给用户'foo'在testdb上赋予了所有权限。

1 个回答

3

Ident认证的意思是,数据库用户“foo”只能由系统用户“foo”来访问。

如果你不是以用户“foo”的身份运行你的Python程序,那就无法连接。

如果你不知道什么是“ident”认证,也懒得去了解,可以换成密码认证,这样可能更符合你的需求。

哦,对了,你还可以创建一个.pgpass文件,里面写上用户名和密码的详细信息。具体可以查看相关文档。

撰写回答