如何更改PostgreSQL用户的密码?
当前回答
以及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文档:
使用此命令。密码将在cleartext,并且它也可能记录在客户端的命令历史记录中或服务器日志。psql包含可以使用的命令\密码在不暴露明文密码的情况下更改角色的密码。
注意:ALTER USER是ALTER ROLE的别名
转到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
使用新密码。
这是谷歌上的第一个结果,当时我正在研究如何重命名用户,所以:
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>;
TLDR:
在许多系统中,用户的帐户通常包含句点或某种标点符号(用户:john.smith,horise.johnson)。在这些情况下,必须对上面接受的答案进行修改。更改要求用户名加上双引号。
实例
ALTER USER "username.lastname" WITH PASSWORD 'password';
理论基础:
PostgreSQL对何时使用“双引号”和何时使用“单引号”非常挑剔。通常,当提供字符串时,您将使用单引号。
使用此项:
\password
输入该用户的新密码,然后确认。如果您不记得密码,并且想更改密码,您可以以“postgres”登录,然后使用此选项:
ALTER USER 'the username' WITH PASSWORD 'the new password';
推荐文章
- 如何关闭mysql密码验证?
- 查询JSON类型内的数组元素
- 获得PostgreSQL数据库中当前连接数的正确查询
- 纬度和经度的数据类型是什么?
- 如何在PostgreSQL中临时禁用触发器?
- 输入文件似乎是一个文本格式转储。请使用psql
- 使用LIMIT/OFFSET运行查询,还可以获得总行数
- 当恢复sql时,psql无效命令\N
- 货币应该使用哪种数据类型?
- 如何添加列,如果不存在PostgreSQL?
- 如何在Postgres中获得两个字段的MIN() ?
- 截断Postgres数据库中的所有表
- 如何连接列在Postgres选择?
- 将varchar字段的类型更改为整数:"不能自动转换为整数类型"
- PostgreSQL可以索引数组列吗?