How do I change the password for PostgreSQL user?
To login without a password:
sudo -u user_name psql db_name
To reset the password if you have forgotten:
ALTER USER user_name WITH PASSWORD 'new_password';
-
148
-
143
-
52off topic but if anyone looking for "how to change name of user" than do
ALTER USER myuser RENAME TO newname;
...for some reason google was pointing me here when I was googling that :) – equivalent8 Apr 14 '14 at 15:58 -
10Why are you using both " and ' quotes? I mean, there's a difference, and in a DML query you have to use ' when dealing with strings, but is there a special reason to use both of them here? – Boyan Mar 23 '16 at 11:17
-
9The user is an object, not a string. Compare with ALTER TABLE "table_name" or even SELECT * FROM "table_name". You couldn't use single quotes in these contexts with tables, and it's the same with users/roles. – P Daddy Apr 13 '16 at 5:11
Then type:
$ sudo -u postgres psql
Then:
\password postgres
Then to quit psql
:
\q
If that does not work, reconfigure authentication.
Edit /etc/postgresql/9.1/main/pg_hba.conf
(path will differ) and change:
local all all peer
to:
local all all md5
Then restart the server:
$ sudo service postgresql restart
-
3whats the default password for postgres? changed it accidently; possible to reset? – Saad Oct 4 '12 at 5:51
-
2(on psql 9.2) if I type in
\p
, it gives me the password; if I type in\password postgres
it gives the password and then warnings\p extra argument "assword" ignored; \p extra argument "postgres" ignored
– David LeBauer Jul 26 '13 at 14:49 -
3
-
1
-
2To change the password on the postgres user in Linux:
sudo passwd postgres
– Punnerud Aug 28 '19 at 6:31
You can and should have the users's password encrypted:
ALTER USER username WITH ENCRYPTED PASSWORD 'password';
-
52This keyword doesn't matter for the current version. From postgresql.org/docs/current/static/sql-createrole.html
The password is always stored encrypted in the system catalogs. The ENCRYPTED keyword has no effect, but is accepted for backwards compatibility.
– John29 Nov 3 '17 at 19:03 -
7Beware! @John29 comment is only true from Postgresql 10 and above. For all other versions the ENCRYPTED flag matters. – phep May 7 '19 at 11:35
-
the unencrypted password is rememberd by
psql
history or shell... How to use hashed (ex. SHA1) password? – Peter Krauss Jul 19 '20 at 11:12
I believe the best way to change the password is simply to use:
\password
in the Postgres console.
Per ALTER USER
documentation:
Caution must be exercised when specifying an unencrypted password with this command. The password will be transmitted to the server in cleartext, and it might also be logged in the client's command history or the server log. psql contains a command \password that can be used to change a role's password without exposing the cleartext password.
Note: ALTER USER
is an alias for ALTER ROLE
To change password using Linux command line, use:
sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"
-
6Just remember that this will probably save the db's user password in your command history. – Pedro Cordeiro Apr 24 '18 at 20:01
-
3can you use environment variables here? I want to automate this in a deploy script – TheRealChx101 Jul 21 '19 at 20:46
To Change Password
sudo -u postgres psql
then
\password postgres
now enter New Password and Confirm
then \q
to exit
-
-
1
Go to your Postgresql Config and Edit pg_hba.conf
sudo vim /etc/postgresql/9.3/main/pg_hba.conf
Then Change this Line :
Database administrative login by Unix domain socket
local all postgres md5
to :
Database administrative login by Unix domain socket
local all postgres peer
then Restart the PostgreSQL service via SUDO command then
psql -U postgres
You will be now entered and will See the Postgresql terminal
then enter
\password
and enter the NEW Password for Postgres default user, After Successfully changing the Password again go to the pg_hba.conf and revert the change to "md5"
now you will be logged in as
psql -U postgres
with your new Password.
Let me know if you all find any issue in it.
-
It doesn't work :
user@user-NC10:~$ psql -U postgres psql: FATAL: Peer authentication failed for user "postgres"
– G M Jul 4 '15 at 22:12 -
Ok, Do another method sudo su - postgres psql You will enter the terminal and then change the password there, This is an alternate way for this. Let me know if this works for you or you need a full explanation – Murtaza Kanchwala Jul 5 '15 at 18:43
-
mm i have tried but I have another error:/usr/bin/psql: line 19: use: command not found /usr/bin/psql: line 21: use: command not found /usr/bin/psql: line 23: use: command not found /usr/bin/psql: line 24: use: command not found /usr/bin/psql: psql: line 26: syntax error near unexpected token
$version,' /usr/bin/psql: psql: line 26:
my ($version, $cluster, $db, $port, $host);' thanks for your help! – G M Jul 11 '15 at 15:08
This was the first result on google, when I was looking how to rename a user, so:
ALTER USER <username> WITH PASSWORD '<new_password>'; -- change password
ALTER USER <old_username> RENAME TO <new_username>; -- rename user
A couple of other commands helpful for user management:
CREATE USER <username> PASSWORD '<password>' IN GROUP <group>;
DROP USER <username>;
Move user to another group
ALTER GROUP <old_group> DROP USER <username>;
ALTER GROUP <new_group> ADD USER <username>;
To request a new password for the postgres user (without showing it in the command):
sudo -u postgres psql -c "\password"
Configuration that I've got on my server was customized a lot and I managed to change password only after I set trust authentication in the pg_hba.conf
file:
local all all trust
Don't forget to change this back to password or md5
-
1you also need to restart your postgres service for changes to take effect
sudo systemctl restart postgresql.service
– samsri May 28 '17 at 7:52 -
For my case on Ubuntu 14.04 installed with postgres 10.3. I need to follow the following steps
su - postgres
to switch user topostgres
psql
to enter postgres shell\password
then enter your password\q
to quit the shell sessionThen you switch back to root by executing
exit
and configure yourpg_hba.conf
(mine is at/etc/postgresql/10/main/pg_hba.conf
) by making sure you have the following linelocal all postgres md5
- Restart your postgres service by
service postgresql restart
- Now switch to
postgres
user and enter postgres shell again. It will prompt you with password.
-
I don't think you really need to restart the postgresql service after changing the password. I have been able to reset the password with restarting it. \password is the quickest way. Or else you need the ALTER USER command. – Archit Kapoor Jul 27 '18 at 10:19
If you are on windows.
Open pg_hba.conf
file and change from md5
to peer
Open cmd, type psql postgres postgres
Then type \password
to be prompted for a new password.
Refer to this medium post for further information & granular steps.
-
2While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review – Brian Minton Jun 13 '20 at 21:47
-
-
1
use this:
\password
enter the new password you want for that user and then confirm it. If you don't remember the password and you want to change it, you can log in as postgres and then use this:
ALTER USER 'the username' WITH PASSWORD 'the new password';
TLDR:
On many systems, a user's account often contains a period, or some sort of punction (user: john.smith, horise.johnson). IN these cases a modification will have to be made to the accepted answer above. The change requires the username to be double-quoted.
Example:
ALTER USER "username.lastname" WITH PASSWORD 'password';
Rational:
Postgres is quite picky on when to use a 'double quote' and when to use a 'single quote'. Typically when providing a string you would use a single quote.
Similar to other answers in syntax but it should be known that you can also pass a md5 of the password so you are not transmitting a plain text password.
Here are a few scenarios of unintended consequences of altering a users password in plain text.
- If you do not have SSL and are modifying remotely you are transmitting the plain text password across the network.
- If you have your logging configuration set to log DDL Statements
log_statement = ddl
or higher, then your plain text password will show up in your error logs.- If you are not protecting these logs its a problem.
- If you collect these logs/ETL them and display them where others have access they could end up seeing this password, etc.
- If you allow a user to manage their password, they are unknowingly revealing a password to an admin or low level employee tasked with reviewing logs.
With that said here is how we can alter a user's password by building an md5 of the password.
- Postgres when hash a password as md5, salts the password with the user name then prepends the text "md5" to the resulting hash.
ex: "md5"+md5(password + username)
In bash:
~$ echo -n "passwordStringUserName" | md5sum | awk '{print "md5"$1}'
md5d6a35858d61d85e4a82ab1fb044aba9d
- In PowerShell:
[PSCredential] $Credential = Get-Credential
$StringBuilder = New-Object System.Text.StringBuilder
$null = $StringBuilder.Append('md5');
[System.Security.Cryptography.HashAlgorithm]::Create('md5').ComputeHash([System.Text.Encoding]::ASCII.GetBytes(((ConvertFrom-SecureStringToPlainText -SecureString $Credential.Password) + $Credential.UserName))) | ForEach-Object {
$null = $StringBuilder.Append($_.ToString("x2"))
}
$StringBuilder.ToString();
## OUTPUT
md5d6a35858d61d85e4a82ab1fb044aba9d
- So finally our
ALTER USER
command will look like
ALTER USER UserName WITH PASSWORD 'md5d6a35858d61d85e4a82ab1fb044aba9d';
- Relevant Links (Note I will only link to the latest versions of the docs for older it changes some but md5 is still support a ways back.)
- create role
The password is always stored encrypted in the system catalogs. The ENCRYPTED keyword has no effect, but is accepted for backwards compatibility. The method of encryption is determined by the configuration parameter password_encryption. If the presented password string is already in MD5-encrypted or SCRAM-encrypted format, then it is stored as-is regardless of password_encryption (since the system cannot decrypt the specified encrypted password string, to encrypt it in a different format). This allows reloading of encrypted passwords during dump/restore.
- configuration setting for password_encryption
- postgres password authentication doc
- building postgres password md5
and the fully automated way with bash and expect ( in this example we provision a new postgres admin with the newly provisioned postgres pw both on OS and postgres run-time level )
# the $postgres_usr_pw and the other bash vars 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 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 ;
"
In general, just use pg admin UI for doing db related activity.
If instead you are focusin more in automating database setup for your local development, or CI etc...
For example, you can use a simple combo like this.
(a) Create a dummy super user via jenkins with a command similar to this:
docker exec -t postgres11-instance1 createuser --username=postgres --superuser experiment001
this will create a super user called experiment001 in you postgres db.
(b) Give this user some password by running a NON-Interactive SQL command.
docker exec -t postgres11-instance1 psql -U experiment001 -d postgres -c "ALTER USER experiment001 WITH PASSWORD 'experiment001' "
Postgres is probably the best database out there for command line (non-interactive) tooling. Creating users, running SQL, making backup of database etc... In general it is all quite basic with postgres and it is overall quite trivial to integrate this into your development setup scripts or into automated CI configuration.
check pg_hba.conf
In case the authentication method is 'peer', the client's operating system user name/password must match the database user name and password. In that case, set the password for Linux user 'postgres' and the DB user 'postgres' to be the same.
see the documentation for details: https://www.postgresql.org/docs/9.1/auth-pg-hba-conf.html