在postgres用户上设置密码是否意味着即使将pg_hba.conf设置为trust也需要密码


Does setting a password on the postgres user mean that a password is required even when setting pg_hba.conf to trust?

我在Windows7下完成了大部分PHP/PostgreSQL开发,但正在迁移到Linux。我最近在Debian Wheezy上安装了PHP和PostgreSQL,并且很难与postgres用户连接到我的PostgreSQL数据库。我在stackoverflow上发现了一个帖子,上面说要做以下事情:

template1=# ALTER USER postgres WITH PASSWORD 'password';

最初,对于密码,我使用了一个空字符串,但不起作用。接下来我使用了一个文本字符串,它允许我通过pg_connect()进行连接。

在做了更多的研究后,我发现更改pg_hba.conf文件并使postgres用户受到信任才是我真正想做的……在进行此更改时,当没有通过pg_connect()为postgres提供密码时,我仍然会遇到错误,所以我的问题是:

使用密码更改postgres用户是否会导致即使身份验证方法设置为信任,pg_connect()也需要密码?当我使用通过命令行连接时

psql -U postgres

我没有问题。。。当使用pg_connect()通过PHP进行连接时,问题就开始了。

pg_hba.conf文件:

local   all             postgres                                trust
local   all             all                                     trust
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5

PHP连接线:

pg_connect('host=localhost dbname=dev user=postgres');

pg_hba.conf更改为:

local   all             postgres                                trust
local   all             all                                     trust
host    all             all             127.0.0.1/32            trust
host    all             all             ::1/128                 trust

这将允许您在没有密码的情况下进行连接。

请记住在编辑pg_hba.conf之后重新启动(或重新加载)postgresql。

或者,您可以尝试更改您的php代码,如下所示:

pg_connect('dbname=dev user=postgres');

即使pg_hba.conf没有任何更改,这也应该起作用。

解释:

您可以通过unix套接字(建议更快)或TCP/IP连接到postgres。pg_hba.conf中的第一行和第二行与套接字有关,第三行与ipv4有关,第四行与ipv6有关。如果您在代码中指定localhost,那么您是通过TCP/IP(ipv4)进行连接的,这就是为什么它不起作用,并询问您密码。

如果您只使用psql -U postgres通过控制台进行连接,那么您使用的是unix套接字,这就是它在没有密码的情况下工作的原因。

不用担心,即使更改了配置,也只允许本地连接访问,而无需密码。