重置 PostgreSQL 超级用户的密码
本文介绍重置 PostgreSQL 超级用户的密码详细步骤。
在 PostgreSQL 中, postgres 是超级用户。如果您忘记了 postgres 的密码,您可以按照以下步骤进行重置。
-
找到 PostgreSQL 数据库服务器的配置文件
pg_hba.conf。在 Windows 上, PostgreSQL 数据库服务器的配置文件位于 PostgreSQL 安装目录的
data目录下,比如:C:\Program Files\PostgreSQL\14\data。在 Linux 上, PostgreSQL 数据库服务器的配置文件位于
/etc/postgresql/14/main/pg_hba.conf。 -
修改配置文件之前备份 配置文件,以便后面进行恢复。
cp pg_hba.conf pg_hba.conf.bak -
修改配置文件以信任本地连接不需要密码。 将配置文件中的
scram-sha-256或者md5修改为trust,如下:local all all peer # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. local replication all peer host replication all 127.0.0.1/32 trust host replication all ::1/128 trust -
重启 PostgreSQL 数据库服务器。
在 Windows 中, 您可以在服务列表窗口重启 PostgreSQL。
在 Linux 中,您可以使用
systemctl restart postgresql命令重启 PostgreSQL。 -
登录到 PostgreSQL 数据库服务器。
psql -U postgres您并不需要输入密码。
-
使用以下命令修改
postgres用户的密码:ALTER USER postgres WITH PASSWORD 'new_password'; -
恢复
pg_hba.conf配置文件。 将pg_hba.conf.bak文件的内容覆盖pg_hba.conf。 -
重启 PostgreSQL 数据库服务器。 当您登陆时, PostgreSQL 应该会提示您输入密码。
结论
本文阐述了重置 PostgreSQL 超级用户 postgres 的密码的详细步骤。