如何更改PostgreSQL用户的密码?
当前回答
为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
其他回答
将用户“postgres”的密码更改为“postgress”:
# ALTER USER postgres WITH ENCRYPTED 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 ;
"
您可以并且应该对用户的密码进行加密:
ALTER USER username WITH ENCRYPTED PASSWORD 'password';
更改密码:
sudo -u postgres psql
Then
\password postgres
现在输入新密码并确认。
然后\q退出。
TLDR:
在许多系统中,用户的帐户通常包含句点或某种标点符号(用户:john.smith,horise.johnson)。在这些情况下,必须对上面接受的答案进行修改。更改要求用户名加上双引号。
实例
ALTER USER "username.lastname" WITH PASSWORD 'password';
理论基础:
PostgreSQL对何时使用“双引号”和何时使用“单引号”非常挑剔。通常,当提供字符串时,您将使用单引号。
推荐文章
- PostgreSQL删除所有内容
- 为什么PostgreSQL要对索引列进行顺序扫描?
- PostgreSQL INSERT ON冲突更新(upsert)使用所有排除的值
- 如何检查一个表是否存在于给定的模式中
- 如何将整数转换为字符串作为PostgreSQL查询的一部分?
- Psycopg2:用一个查询插入多行
- PostgreSQL返回JSON数组的结果集?
- PostgreSQL通配符LIKE用于单词列表中的任何一个
- 检查Postgres JSON数组是否包含字符串
- psql: FATAL: Peer authentication failed for user "dev"
- 如何在Postgres/SQL中获得两个整数的最小/最大值?
- 如何在postgresql中显示函数,过程,触发器源代码?
- 如何用postgres将间隔转换为小时数?
- 在postgresql中将查询结果按月和年分组
- 如何改变一个列的数据类型在PostgreSQL表?