如何更改PostgreSQL用户的密码?


当前回答

要在没有密码的情况下登录,请执行以下操作:

sudo -u user_name psql db_name

如果您忘记了重置密码:

ALTER USER user_name WITH PASSWORD 'new_password';

其他回答

以及Bash和expect的完全自动化方式(在本例中,我们在OS和PostgreSQL运行时级别为新的PostgreSQL管理员提供新设置的PostgreQL密码):

  # The $postgres_usr_pw and the other Bash variables MUST be defined
  # for reference the manual way of doing things automated with expect bellow
  #echo "copy-paste: $postgres_usr_pw"
  #sudo -u postgres psql -c "\password"
  # The OS password could / should be different
  sudo -u root echo "postgres:$postgres_usr_pw" | sudo chpasswd

  expect <<- EOF_EXPECT
     set timeout -1
     spawn sudo -u postgres psql -c "\\\password"
     expect "Enter new password: "
     send -- "$postgres_usr_pw\r"
     expect "Enter it again: "
     send -- "$postgres_usr_pw\r"
     expect eof
EOF_EXPECT

  cd /tmp/
  # At this point the 'postgres' executable uses the new password
  sudo -u postgres PGPASSWORD=$postgres_usr_pw psql \
    --port $postgres_db_port --host $postgres_db_host -c "
  DO \$\$DECLARE r record;
     BEGIN
        IF NOT EXISTS (
           SELECT
           FROM   pg_catalog.pg_roles
           WHERE  rolname = '"$postgres_db_useradmin"') THEN
              CREATE ROLE "$postgres_db_useradmin" WITH SUPERUSER CREATEROLE
              CREATEDB REPLICATION BYPASSRLS
 PASSWORD '"$postgres_db_useradmin_pw"' LOGIN ;
        END IF;
     END\$\$;
  ALTER ROLE "$postgres_db_useradmin" WITH SUPERUSER CREATEROLE
  CREATEDB REPLICATION BYPASSRLS
PASSWORD  '"$postgres_db_useradmin_pw"' LOGIN ;
 "

要使用Linux命令行更改密码,请使用:

sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"

转到PostgreSQL配置并编辑文件pg_hba.conf:

sudo vim/etc/postgresql/9.3/main/pg-hba.conf

然后更改此行:

Database administrative login by Unix domain socket
local      all              postgres                                md5

to:

Database administrative login by Unix domain socket
local   all             postgres                                peer

然后通过“sudo”命令重新启动PostgreSQL服务。然后

psql-U postgres

现在您将进入并看到PostgreSQL终端。

然后输入

\密码

并为PostgreSQL默认用户输入新密码。再次成功更改密码后,转到pg_hba.conf并将更改还原为“md5”。

现在您将以身份登录

psql -U postgres

使用新密码。

检查文件pg_hba.conf。

如果身份验证方法为“对等”,则客户端的操作系统用户名/密码必须与数据库用户名和密码匹配。在这种情况下,将Linux用户“postgres”和DB用户“post格雷斯”的密码设置为相同。

有关详细信息,请参阅文档:19.1。pg_hba.conf文件

为postgres角色设置密码

sudo -u postgres psql

您将得到如下提示:

postgres=#

将用户postgres的密码更改为PostgreSQL

ALTER USER postgres WITH ENCRYPTED PASSWORD 'postgres';

您将获得以下内容:

ALTER ROLE

为此,我们需要编辑pg_hba.conf文件。

(请随意选择编辑器来替换nano。)

sudo nano /etc/postgresql/9.5/main/pg_hba.conf

在pg_hba.conf文件中更新

查找包含以下内容的未注释行(不以#开头的行)。间距略有不同,但单词应该相同。

    local   postgres   postgres   peer

to

    local   postgres   postgres   md5

现在我们需要重新启动PostgreSQL,以便更改生效

sudo service postgresql restart