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

sil*_*eth 8 postgresql ubuntu

我安装了PostgreSQL 9.4数据库的Kubuntu 14.10桌面.我postgres通过执行SQL 更改了数据库中用户的密码:

ALTER USER postgres PASSWORD 'password';
Run Code Online (Sandbox Code Playgroud)

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

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

localhost127.0.0.1主机及其登录方法有什么区别?它在哪里设置?我localhostpg_hba.conf文件中看到没有相关的条目.

Mik*_*ll' 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=#