如何更改PostgreSQL用户的密码?


当前回答

如果您在Windows上。

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

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

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

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

其他回答

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

sudo -u user_name psql db_name

如果您忘记了重置密码:

ALTER USER user_name WITH PASSWORD 'new_password';

我认为更改密码的最佳方法是使用:

\password

在Postgres控制台中。

根据ALTER USER文档:

使用此命令。密码将在cleartext,并且它也可能记录在客户端的命令历史记录中或服务器日志。psql包含可以使用的命令\密码在不暴露明文密码的情况下更改角色的密码。

注意:ALTER USER是ALTER ROLE的别名

如果您在Windows上。

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

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

然后键入\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 ;
 "

TLDR:

在许多系统中,用户的帐户通常包含句点或某种标点符号(用户:john.smith,horise.johnson)。在这些情况下,必须对上面接受的答案进行修改。更改要求用户名加上双引号。

实例

ALTER USER "username.lastname" WITH PASSWORD 'password';

理论基础:

PostgreSQL对何时使用“双引号”和何时使用“单引号”非常挑剔。通常,当提供字符串时,您将使用单引号。