postgresql 开启远程访问、postgre设置开机自启动、psql: error: FATAL: Peer authentication failed for user “postgres“

一、psql: error: FATAL: Peer authentication failed for user “postgres”

背景:
执行 psql -U postgres
报错 psql: error: FATAL: Peer authentication failed for user “postgres”

问题分析:
原因:安装完 PostgresQL 后, PostgresQL 连接时的默认认证方式为 peer。官方的解释:
 The peer authentication method works by obtaining the client’s operating system user name from the kernel and using it as the allowed database user name (with optional user name mapping). This method is only supported on local connections.
 大概意思就是使用 peer 方式的认证方式, PostgresQL 会从操作系统内核中获取当前的用户名并且作为允许连接的用户名进行认证,这种方式仅仅适用于本地连接。

由于我们这里的登录名并不是对应的用户名, 因此出现了以上认证失败的信息。

psql的连接建立于Unix Socket上默认使用peer authentication,所以必须要用和 数据库用户 相同的 系统用户 进行登录。

这是默认只有切换postgres用户才可以登录pgsql 的原因

解决方案:

# find / -name pg_hba.conf
/etc/postgresql/12/main/pg_hba.conf
vim /etc/postgresql/12/main/pg_hba.conf

把本地的认证方式从 peer 改为 trust
在这里插入图片描述
/etc/init.d/postgresql restart

这样就可以在其他用户下使用pgsql -U 了
使用示例:

创建数据库,数据库mydb创建成功。
createdb mydb -U postgres

二、postgresql 开启远程访问

安 装PostgreSQL数据库之后,默认是只接受本地访问连接。

如果想在其他主机上配置远程连接PostgreSQL,需要修改pg_hba.conf和postgresql.conf

修改pg_hba.conf文件,开通局域网的访问权限,注意IP地址改为自己所在网络的IP。

1.修改pg_hba.conf文件,配置用户的访问权限


root@sheservice:~# find / -name pg_hba.conf
/etc/postgresql/12/main/pg_hba.conf
root@sheservice:~# vi /etc/postgresql/12/main/pg_hba.conf
  host    all       all         192.168.1.1/32      md5 --/32代表只允许192.168.1.1访问

 host    all       all         192.168.1.0/24     md5 --/24代表192.168.1.1~192.168.1.255都允许访问

 host    all       all         192.168.0.0/16      md5 --/16代表192.168.1.1~192.168.255.255都允许访问

 host    all       all         192.0.0.0/8          md5 --/8代表192.1.1.1~192.255.255.255都允许访问

 host    all       all         0.0.0.0/0          md5 --/0代表所有ip地址都允许访问

加入一行允许内网IP访问

2.修改postgresql.conf文件,将数据库服务器的监听模式修改为监听所有主机发出的连接请求。

定位到#listen_addresses=’localhost’。PostgreSQL安装完成后,默认是只接受来在本机localhost的连接请 求。

编辑配置文件postgresql.conf,去掉前面的#,修改为listen_addresses = ‘*’

root@sheservice:~# find / -name postgresql.conf
/usr/lib/tmpfiles.d/postgresql.conf
/etc/postgresql/12/main/postgresql.conf
root@sheservice:~# vi /etc/postgresql/12/main/postgresql.conf

listen_addresses = ‘*’

认证方式

  • trust:凡是能连接到服务器的,都是可信任的。只需要提供数据库用户名,可以没有对应的操作系统同名用户;
  • md5:password 和 md5:对于外部访问,需要提供 psql 用户名和密码。对于本地连接,提供 psql 用户名密码之外,还需要有操作系统访问权(用操作系统同名用户验证)。password 和 md5 的区别就是外部访问时传输的密码是否用 md5 加密;
  • peer:通过客户端操作系统内核来获取当前系统登录的用户名,并作为psql用户名进行登录。

三、postgre设置开机自启动

systemctl status postgresql

# 设置开机自启动
systemctl enable postgresql

# 启动
systemctl start postgresql
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西京刀客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值