如何在postgresql 9.1中设置用户postgres密码

时间:2019-08-20 17:58:19  来源:igfitidea点击:

在本教程中,我们将学习如何在postgresql9.1中设置用户postgres密码并强制提示输入密码。

当我们刚安装Postgresql并使用命令“psql”后,它将允许我们登录到Postgresql服务器,而无需提示或者询问密码。

服务器系统

操作系统:Ubuntu12.10

架构:i386

数据库postgresql9.1

重置用户postgres的密码的步骤:

以root用户登录或者切换到超级用户(root)

sudo su -

or 

su -

安装Postgresql server

==== 在 Debian 和 Ubuntu 中===
apt-get install postgresql

=== 在 Red Hat 和 CentOS 中===
yum install postgresql

切换到用户postgres

root@theitroad:~# su -l postgres

登录postgresql服务器

运行以下命令并重置密码

密码重置语法ALTER USER postgres WITH ENCRYPTED passwd'

postgres@theitroad:~$ 
postgres@theitroad:~$ psql
psql (9.1.9)
Type "help" for help.

postgres=# 
postgres=# ALTER USER postgres WITH ENCRYPTED PASSWORD 'passwd';
ALTER ROLE
postgres=# q

退出用户postgres

postgres@theitroad:~$exit

备份pg_hba.conf文件

退出postgres用户登录后,回到root用户的终端,备份配置文件

cp -p /etc/postgresql/9.1/main/pg_hba.conf /etc/postgresql/9.1/main/pg_hba.conf.orig

编辑/etc/postgresql/9.1/main/pg_hba.conf文件

  1. 注释掉文件最底下的local all postgres peer

  2. 添加新的一行 local all postgres md5

vim /etc/postgresql/9.1/main/pg_hba.conf
# Database administrative login by Unix domain socket
#local   all             postgres                                peer
local   all             postgres                                md5

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            md5

重启posgresql服务。

/etc/init.d/postgresql restart

现在登录postgresql server,注意这次它将会询问我们登录密码

(a) 切换到用户postgressu-l postgres

(b) 运行命令psql

(c) 提供postgres密码

root@theitroad:/etc/postgresql/9.1/main# su -l postgres
postgres@theitroad:~$ 
postgres@theitroad:~$ psql
Password: 
psql (9.1.9)
Type "help" for help.

postgres=# 
postgres=# q
postgres@theitroad:~$

如何重置忘记的postgres密码

如果忘记了postgres的密码,可以恢复到旧的pg_hba.conf文件,并重新启动postgresql服务

即,将行local all postgres md5注释。
local all postgres peer这行取消注释。

然后重启posgresql服务。

/etc/init.d/postgresql restart