可以通过localhost连接到postgres而无需密码,但不能通过127.0.0.1。为什么?

时间:2014-11-18 23:13:25

标签: postgresql ubuntu

我安装了PostgreSQL 9.4数据库的Kubuntu 14.10桌面。 我通过执行SQL:

更改了数据库中postgres用户的密码
ALTER USER postgres PASSWORD 'password';

我可以通过psql -h localhost -U postgres -W连接到数据库服务器并提供该密码我也可以通过简单的psql -h localhost -U postgres连接而无需密码。

另一方面,如果我运行psql -h 127.0.0.1 -U postgres,它会提示我输入之前设置的密码。

localhost127.0.0.1主机及其登录方式有何区别?它在哪里设置?我在localhost文件中看不到与pg_hba.conf相关的条目。

1 个答案:

答案 0 :(得分:10)

您看到的行为可能是由密码文件引起的。密码文件在Unix系统上通常命名为〜/ .pgpass,但可以通过PGPASSFILE环境变量给出不同的文件名。

我认为包含“localhost”行但包含“127.0.0.1”行的密码文件将显示您所看到的行为。我自己的〜/ .pgpass文件包含这一行。

localhost:*:*:postgres:password

以下是我尝试连接时发生的情况。

$ psql -h localhost -U postgres
psql (9.3.5)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
Type "help" for help.

sandbox=# \q
$ psql -h 127.0.0.1 -U postgres
Password for user postgres: 

将行127.0.0.1:*:*:postgres:password添加到〜/ .pgpass允许我使用127.0.0.1登录并且没有密码。

$ psql -h 127.0.0.1 -U postgres
psql (9.3.5)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
Type "help" for help.

sandbox=#