问题
无法远程连接
报错: -bash-4.2$ psql psql: FATAL: no pg_hba.conf entry for host "[local]", user "postgres", database "postgres", SSL off 无法进入系统
报错:The specified database user/password combination is rejected: [28P01] FATAL: password authentication failed for user "postgres"
一、最终定性(非常关键)
你当前的状态是:
-
PostgreSQL 13
-
password_encryption = scram-sha-256 -
pg_hba.conf已允许host all all 0.0.0.0/0 -
本地 socket 之前被锁死(已修)
-
现在 无论本地 TCP / 远程都 28P01
👉 这不是 pg_hba.conf 了,也不是你输错密码
❗ 这是 postgres 用户的密码 hash 与认证方式不一致
换句话说:
postgres 用户现在的密码是“坏的”
这种情况在下面场景极常见:
-
pg_hba 在 md5 / scram 间多次切换
-
升级过 PG
-
初始化后被 ALTER ROLE 反复改
-
早期 md5 密码残留
二、最稳的解决策略(不要再试零散命令)
⚠️ 不要再用 md5 / scram 纠结了
⚠️ 直接重建 postgres 用户密码信息
我们分三步,必解。
第一步:确保你能“无密码进库”(救援模式)
1️⃣ 临时改 pg_hba.conf(只针对本机)
在 pg_hba.conf 最前面加:
local all all trust
host all all 127.0.0.1/32 trust
⚠️ 不要删原规则,只是临时加
2️⃣ 重启(不是 reload)
systemctl restart postgresql
# 或
systemctl restart postgresql-13
3️⃣ 验证你能否进库
su - postgres
psql
✅ 必须成功
❌ 如果这里还失败,那 PG 实例本身已异常(概率极低)
第二步:彻底“清洗”postgres 用户密码(重点)
进入 psql 后,一条一条执行,不要合并:
-- 1. 确认当前状态
SHOW password_encryption;-- 2. 强制切换为 scram
SET password_encryption = 'scram-sha-256';-- 3. 清空再设(关键)
ALTER ROLE postgres PASSWORD NULL;
ALTER ROLE postgres PASSWORD 'Pg@22349999!';-- 4. 确认角色状态
SELECT rolname, rolcanlogin, rolpassword
FROM pg_authid
WHERE rolname='postgres';
你应该看到:
-
rolcanlogin = t -
rolpassword以SCRAM-SHA-256$开头
👉 如果不是 SCRAM 开头,说明你前面步骤没生效
第三步:恢复正常认证方式
1️⃣ 改回 pg_hba.conf(推荐配置)
# 本地
local all postgres peer
host all postgres 127.0.0.1/32 scram-sha-256# 远程
host all all 0.0.0.0/0 scram-sha-256
2️⃣ 重启 PostgreSQL
systemctl restart postgresql-13
第四步:逐级验证(不能跳)
1️⃣ 本地 TCP
psql -h 127.0.0.1 -U postgres -d postgres
2️⃣ 远程
psql -h 124.11.18.14 -U postgres -d postgres
改完之后配置文件
# 本地 local all postgres peer host all postgres 127.0.0.1/32 scram-sha-256 # # # 远程 host all all 0.0.0.0/0 scram-sha-256
总结
PG数据库平时使用较少,这个问题核心原因就是之前密码使用了MD5加密存储,后来使用scram-sha-256进行验证密码导致报错。所以进行轻松重新设置密码就好了,保证密码编码一致。