如何更改PostgreSQL用户的密码?


当前回答

我在服务器上获得的配置进行了大量定制,只有在pg_hba.conf文件中设置了信任身份验证后,我才成功更改了密码:

local   all   all   trust

不要忘记将其改回密码或md5。

其他回答

通常,只需使用pgAdmin UI执行与数据库相关的活动。

如果相反,您更专注于为本地开发、CI等自动化数据库设置。

例如,可以使用这样的简单组合。

(a) 通过Jenkins创建一个虚拟超级用户,命令如下:

docker exec -t postgres11-instance1 createuser --username=postgres --superuser experiment001

这将在PostgreSQL数据库中创建一个名为experience001的超级用户。

(b) 通过运行NON Interactive SQL命令为该用户提供一些密码。

docker exec -t postgres11-instance1 psql -U experiment001 -d postgres -c "ALTER USER experiment001 WITH PASSWORD 'experiment001' "

PostgreSQL可能是命令行(非交互式)工具的最佳数据库。创建用户、运行SQL、备份数据库等。

一般来说,PostgreSQL都是非常基础的,将其集成到开发设置脚本或自动化CI配置中总体来说非常简单。

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

sudo -u postgres psql -c "\password"

使用pgAdmin 4:

菜单对象→ 更改密码。。。

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

使用此项:

\password

输入该用户的新密码,然后确认。如果您不记得密码,并且想更改密码,您可以以“postgres”登录,然后使用此选项:

ALTER USER 'the username' WITH PASSWORD 'the new password';