如何更改PostgreSQL用户的密码?


当前回答

将用户“postgres”的密码更改为“postgress”:

# ALTER USER postgres WITH ENCRYPTED PASSWORD '<NEW-PASSWORD>';

其他回答

如果您在Windows上。

打开pg_hba.conf文件并从md5更改为对等。

打开cmd并键入psql-postgres-postgres。

然后键入\password以提示输入新密码。

有关更多信息和详细步骤,请参阅本中帖。

要请求postgres用户的新密码(不在命令中显示):

sudo -u postgres psql -c "\password"

这是谷歌上的第一个结果,当时我正在研究如何重命名用户,所以:

ALTER USER <username> WITH PASSWORD '<new_password>';  -- change password
ALTER USER <old_username> RENAME TO <new_username>;    -- rename user

其他一些有助于用户管理的命令:

CREATE USER <username> PASSWORD '<password>' IN GROUP <group>;
DROP USER <username>;

将用户移动到其他组

ALTER GROUP <old_group> DROP USER <username>;
ALTER GROUP <new_group> ADD USER <username>;

以及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 ;
 "

我使用的是Windows(Windows Server 2019;PostgreSQL 10),因此不支持本地类型连接(pg_hba.conf:本地所有对等)。

以下各项应适用于Windows和Unix系统:

将pg_hba.conf备份到pg_hba.org.conf,例如。仅使用以下命令创建pg_hba.conf:host all all 127.0.0.1/32信任重新启动pg(服务)执行psql-U postgres-h 127.0.0.1输入(在pgctl控制台中)使用密码“SomePass”更改用户postgres;从1还原pg_hba.conf。在上面