PostgreSQL 如何重置root密码

  • 第1步,找到 pg_hba.conf 文件的位置
find / -name "pg_hba.conf"
  • 第2步,修改配置文件,找到针对本地连接的行,临时修改认证方式,改成 trust 免密登录
#.查看认证方式
root@localhost:~# cat /etc/postgresql/9.5/main/pg_hba.conf | grep "^local"
local   all             postgres                                peer
local   all             all                                     peer

#.改成如下 trust 意味着无需密码即可连接
root@localhost:~# cat /etc/postgresql/9.5/main/pg_hba.conf | grep "^local"
local   all             postgres                                peer
local   all             all                                     trust
  • 第3步,重启服务使配置生效
systemctl status postgresql
systemctl restart postgresql
  • 第4步,无密码登录,修改管理员密码或创建备用管理员账号 [推荐]
root@localhost:~# sudo -u postgres psql

--.重置管理员密码
ALTER USER postgres WITH PASSWORD 'Admin_147';

#.新建备用管理员账号
CREATE ROLE dba_admin SUPERUSER PASSWORD 'cf_rB1NKCzbaQuPH' LOGIN;

--.查看账号
SELECT * FROM pg_shadow;
\q
  • 第5步,修改配置文件,将 trust 改回 peer
root@localhost:~# cat /etc/postgresql/9.5/main/pg_hba.conf | grep "^local"
local   all             postgres                                peer
local   all             all                                     peer
  • 第6步,重启服务
systemctl restart postgresql
  • 第7步,登录测试,示例使用 dba_admin 登录,密码为 cf_rB1NKCzbaQuPH
root@localhost:~# psql -h 127.0.0.1 -p 5432 -U dba_admin -d postgres
postgres=# \q
Copyright © www.sqlfans.cn 2021 - 2026 All Right Reserved更新时间: 2026-09-30 10:40:44

results matching ""

    No results matching ""