1450

How do I change the password for PostgreSQL user?

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
Saad
  • 22,746
  • 13
  • 44
  • 68

22 Answers22

2069

To log in 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';
rmtheis
  • 6,552
  • 11
  • 58
  • 75
solaimuruganv
  • 23,738
  • 1
  • 17
  • 23
  • 174
    This let the clear password in the user's postgresql command history. – greg Oct 04 '12 at 07:42
  • 175
    @greg: so delete it: `rm ~/.psql_history` – RickyA Oct 30 '13 at 13:03
  • 65
    off 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
  • 5
    @RickyA Don't forget to clear the db logs too, those might contain plaintext passwords as well. – Rescribet Feb 06 '15 at 17:14
  • 11
    Why 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
  • 2
    Using single quote ' for the role name doesn't work, but I am still curious why? – Boyan Mar 23 '16 at 11:18
  • 9
    The 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 05:11
  • 2
    @RickyA deleting the file doesn't mean that the password would be deleted on the system tough, it could be found through forensics with stuff like photorec, so you would need to `shred` it, etc... – tforgione Dec 03 '16 at 12:31
  • 2
    @DragonRock won't help you on SSDs either or even probably newer versions of ext in general. – dualed Feb 15 '17 at 15:03
  • 1
    @dualed yeah, you're right. Getting totally rid of a file is kind of complicated. It's way better to never have it saved in the first place ! – tforgione Feb 15 '17 at 16:39
  • Just curious but why is an (now unused) password a problem in the log files? It got changed and thus is useless or am I wrong? – Andi-lo Aug 07 '17 at 12:32
  • what does the first line do? – sekmo Oct 16 '17 at 10:48
  • 5
    @greg @RickyA instead of deleting the whole `.psql_history` it is sufficient to issue the command with some whitespace before `ALTER USER`, and it will not be stored in `.psql_history`. This same handy trick is available in standard shell as well. – Alphaaa Jan 23 '18 at 16:45
  • 4
    please use `ENCRYPTED PASSWORD` – Natim Feb 08 '18 at 09:16
  • 1
    @Alphaaa I think that only works if you have `\set HISTCONTROL ignorespace` set in the .psqlrc file. – Gregory Arenius Mar 20 '18 at 19:05
  • Yes @GregoryArenius, your .psqlrc file should contain `\set HISTCONTROL ignorespace` or `\set HISTCONTROL ignoreboth` for my suggestion to work. – Alphaaa Mar 21 '18 at 18:25
  • 4
    @Natim From the docs: `The password is always stored encrypted in the system catalogs. The ENCRYPTED keyword has no effect, but is accepted for backwards compatibility.` But you can send an encrypted password: `If the presented password string is already in MD5-encrypted or SCRAM-encrypted format, then it is stored as-is regardless of password_encryption.` https://www.postgresql.org/docs/current/static/sql-createrole.html – Rohmer Aug 02 '18 at 23:04
  • 3
    If you use the `\password` command in `psql` then the history will not contain the password. (At least in Version 9.2.24) – Laryx Decidua Dec 19 '18 at 12:51
  • 1
    ### Use DOUBLE QUOTE for the user if it contains a period. – FlyingV Jun 01 '20 at 18:25
  • the **unencrypted password is rememberd by `psql` history** or shell... Same for SQL command `ENCRYPTED PASSWORD` (!). **How to use encrypted/hashed (ex. SHA256) password?** – Peter Krauss Jul 19 '20 at 11:14
  • This way (without quotes around the user name) will only work for certain user names. – AndreKR Feb 23 '21 at 07:09
  • -bash: -u: command not found – Max Raskolnikov Oct 03 '21 at 15:12
915

To change the the postgres user's password follow this steps

  1. Login into the psql:
$ sudo -u postgres psql
  1. Then in the psql console change the password and quit:
postgres=# \password postgres
Enter new password: <new-password>
postgres=# \q

or using a query

ALTER USER postgres PASSWORD '<new-password>';

or in one line

sudo -u postgres psql -c "ALTER USER postgres PASSWORD '<new-password>';"

Note:

If that does not work, reconfigure authentication by editing /etc/postgresql/9.1/main/pg_hba.conf (path will differ) and change:

local   all         all                  peer # change this to md5

## to

local   all         all                  md5 # like this

Then restart the server:

$ sudo service postgresql restart
Teocci
  • 5,312
  • 1
  • 41
  • 41
Clint Bugs
  • 9,363
  • 1
  • 10
  • 11
  • 4
    whats the default password for postgres? changed it accidently; possible to reset? – Saad Oct 04 '12 at 05:51
  • 3
    (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
  • If you have made the change using \password and you are on the same host as the postgres server, the try specifying that you want your connection to go over an inet instead of unix socket. i.e. use the -h parameter: psql -h 127.0.0.1. Doing this saved me from editing the pg_hba configuration file – Lmwangi Sep 03 '14 at 18:28
  • If only for my reference, `local all postgres md5` allows local logins for postgres with interactive password entry but better yet is existing `host all all 127.0.0.1/32 md5` allows `sudo psql --host 127.0.0.1 --username postgres --password` to log in interactively for postgres login without pg_hba.conf changes. – Zachary Scott Aug 28 '17 at 21:04
  • 12
    This is much better than leaving the password in SQL command history. – otocan Feb 13 '19 at 11:14
  • 1
    @ZacharyScott What are you saying? – TheRealChx101 Jul 21 '19 at 20:45
  • 3
    To change the password on the postgres user in Linux: `sudo passwd postgres` – Punnerud Aug 28 '19 at 06:31
  • 1
    If you want to change the password for someone other then `postgres` user, the `\password` command accepts the role name as the 1st argument: `\password ` https://www.postgresql.org/docs/9.0/sql-alterrole.html – levibostian Feb 26 '20 at 13:12
  • This is the correct answer. Thanks a lot, I see I've upvoted it long time ago, so glad I found it *again*! – Dimitar Dimitrov Mar 28 '21 at 19:35
  • 1
    @Punnerud, _"To change the password on the postgres user in Linux: `sudo passwd postgres`"_ Holy Smokes! I was so confoosed. Both Postgres and Linux have the same user. I'm new to postgres and using it with a new Django site. I needed a backup of the DB and picking 5 random tutorials, this was not explained well. LSS this solved the password problem so I could make a backup. – xtian Jun 09 '21 at 13:00
122

You can and should have the users's password encrypted:

ALTER USER username WITH ENCRYPTED PASSWORD 'password';
yglodt
  • 12,552
  • 14
  • 82
  • 121
  • 66
    This keyword doesn't matter for the current version. From https://www.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 03 '17 at 19:03
  • 13
    Beware! @John29 comment is only true from Postgresql 10 and above. For all other versions the ENCRYPTED flag matters. – phep May 07 '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
102

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

xlm
  • 5,564
  • 13
  • 48
  • 52
Viktor Nordling
  • 7,996
  • 3
  • 25
  • 23
50

To change password using Linux command line, use:

sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"
Vajira Lasantha
  • 2,335
  • 3
  • 21
  • 35
45

To Change Password

 sudo -u postgres psql

then

\password postgres

now enter New Password and Confirm

then \q to exit

Akitha_MJ
  • 3,156
  • 20
  • 16
33

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.

Murtaza Kanchwala
  • 2,386
  • 23
  • 33
  • It doesn't work : `user@user-NC10:~$ psql -U postgres psql: FATAL: Peer authentication failed for user "postgres"` – G M Jul 04 '15 at 22:12
  • 1
    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 05 '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
16

To request a new password for the postgres user (without showing it in the command):

sudo -u postgres psql -c "\password"
lcnicolau
  • 2,864
  • 4
  • 36
  • 51
15

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>;
Salvador Dali
  • 199,541
  • 138
  • 677
  • 738
13

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.

Timothy Macharia
  • 2,281
  • 1
  • 19
  • 26
13

Setting up a password for the Postgres role

$ sudo -u postgres psql

you will get something like are as under:

postgres=#

change password to Postgres for user Postgres

# ALTER USER postgres WITH ENCRYPTED PASSWORD 'postgres';

you will get something like are as under:

ALTER ROLE
postgres=#

To do this we need to edit the pg_hba.conf file.

=====> Feel free to replace nano with an editor of your choice

$ sudo nano /etc/postgresql/9.5/main/pg_hba.conf

Update in the pg_hba.conf

Look for an uncommented line (a line that doesn’t start with #) that has the contents shown below. The spacing will be slightly different, but the words should be the same.

        local   postgres   postgres   peer
        
    to

        local   postgres   postgres   md5
    

Now we need to restart Postgres so the changes take effect.

$ sudo service postgresql restart
CHAVDA MEET
  • 559
  • 6
  • 11
10

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

Randall
  • 2,604
  • 1
  • 19
  • 22
ruruskyi
  • 1,941
  • 2
  • 25
  • 37
9

For my case on Ubuntu 14.04 installed with postgres 10.3. I need to follow the following steps

  • su - postgres to switch user to postgres
  • psql to enter postgres shell
  • \password then enter your password
  • \q to quit the shell session
  • Then you switch back to root by executing exit and configure your pg_hba.conf (mine is at /etc/postgresql/10/main/pg_hba.conf) by making sure you have the following line

    local 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.
haxpor
  • 2,187
  • 2
  • 25
  • 43
  • 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
8

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';
Chris Dare
  • 151
  • 1
  • 8
7

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.

FlyingV
  • 1,577
  • 15
  • 15
5

change password to postgres for user postgres

# ALTER USER postgres WITH ENCRYPTED PASSWORD '<NEW-PASSWORD>';
rams zipppp
  • 51
  • 1
  • 3
4

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.

  1. If you do not have SSL and are modifying remotely you are transmitting the plain text password across the network.
  2. 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.
    1. If you are not protecting these logs its a problem.
    2. If you collect these logs/ETL them and display them where others have access they could end up seeing this password, etc.
    3. 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
jkdba
  • 2,093
  • 3
  • 19
  • 31
4

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 ;
 "
Yordan Georgiev
  • 4,572
  • 1
  • 48
  • 52
2

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.

99Sono
  • 3,428
  • 25
  • 37
2

I was on Windows (Server 2019; PG 10) so local type connections (pg_hba.conf: local all all peer) are not supported. The following should work on Windows and Unix systems alike:

  1. backup pg_hba.conf to pg_hba.orig.conf e.g.
  2. create pg_hba.conf with only this: host all all 127.0.0.1/32 trust
  3. restart pg (service)
  4. execute psql -U postgres -h 127.0.0.1
  5. enter (in pgctl console) alter user postgres with password 'SomePass';
  6. restore pg_hba.conf from 1. above
Andreas Covidiot
  • 3,888
  • 5
  • 45
  • 87
1

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

1

Most of the answers were mostly correct, but you need to look out for minor things. The problem I had was that I didn't ever set the password of postgres, so I couldn't log into an SQL command line that allowed me to change passwords. These are the steps that I used successfully (note that most or all commands need sudo/root user):

  • Edit the pg_hba.conf in the data directory of the DB cluster you're trying to connect to.
    • The folder of the data directory can be found by inspecting the systemd command line, easily obtained with systemctl status postgresql@VERSION-DB_CLUSTER. Replace VERSION with your PSQL version and DB_CLUSTER with the name of your database cluster. This may be main if it was automatically created, so eg. postgresql@13-main. Alternatively, my bash provided auto-complete after entering postgresql@, so you could try that or look for the postgresql services in the list of all services (systemctl -a). Once you have the status output, look for the second command line after CGroup, which should be rather long, and start with /usr/lib/postgresql/13/bin/postgres or similar (depending on version, distro, and installation method). You are looking for the directory after -D, for example /var/lib/postgresql/13/main.
  • Add the following line: host all all 127.0.0.1/32 trust. This allows for all users on all databases to connect to the database via IPv4 on the local machine unconditionally, without asking for a password. This is a temporary fix and don't forget to remove this line again later on. Just to be sure, I commented out the host all all 127.0.0.1/32 md5 (md5 may be replaced by scram-sha-256), which is valid for the same login data, just requiring a password.
  • Restart the database service: systemctl restart postgresql@... Again, use the exact service you found earlier.
  • Check that the service started properly with systemctl status postgresql@....
  • Connect with psql, and very importantly, force psql to not ask for a password. In my experience, it will ask you for a password even though the server doesn't care, and will still reject your login if your password was wrong. This can be accomplished with the -w flag. The full command line looks something like this: sudo -u postgres psql -w -h 127.0.0.1 -p 5432. Here, postgres is your user and you may have changed that. 5432 is the port of the cluster-specific server and may be higher if you are running more than one cluster (I have 5434 for example).
  • Change the password with the \password special command.
  • Remember to remove the password ignore workaround and restart the server to apply the configuration.