How do I change the password for a PostgreSQL user?
asked Oct 4, 2012 at 5:45
3
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,01212 gold badges61 silver badges79 bronze badges
answered Oct 4, 2012 at 5:55
solaimuruganvsolaimuruganv
27.3k1 gold badge20 silver badges23 bronze badges
22
To change the PostgreSQL user’s password, follow these steps:
-
log in into the psql console:
sudo -u postgres psql
-
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
(the 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
answered Oct 4, 2012 at 5:50
Clint BugsClint Bugs
12.4k1 gold badge12 silver badges11 bronze badges
11
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
6,90414 gold badges53 silver badges55 bronze badges
answered Aug 30, 2017 at 16:55
Viktor NordlingViktor Nordling
8,7244 gold badges26 silver badges23 bronze badges
6
You can and should have the users’ password encrypted:
ALTER USER username WITH ENCRYPTED PASSWORD 'password';
answered Feb 21, 2015 at 8:58
yglodtyglodt
13.9k14 gold badges91 silver badges129 bronze badges
4
To change the password using the Linux command line, use:
sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"
answered May 25, 2015 at 23:14
Vajira LasanthaVajira Lasantha
2,4553 gold badges24 silver badges39 bronze badges
4
To the change password:
sudo -u postgres psql
Then
\password postgres
Now enter the new password and confirm.
Then \q
to exit.
answered Jun 29, 2019 at 19:09
Akitha_MJAkitha_MJ
3,91225 silver badges20 bronze badges
1
Go to your PostgreSQL configuration and edit file 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 the ‘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 the PostgreSQL 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.
answered Oct 9, 2014 at 14:03
3
Setting up a password for the postgres role
sudo -u postgres psql
You will get a prompt like the following:
postgres=#
Change password to PostgreSQL for user postgres
ALTER USER postgres WITH ENCRYPTED PASSWORD 'postgres';
You will get something as follows:
ALTER ROLE
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 file
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 PostgreSQL, so the changes take effect
sudo service postgresql restart
answered Oct 30, 2021 at 10:05
CHAVDA MEETCHAVDA MEET
7778 silver badges14 bronze badges
0
To request a new password for the postgres user (without showing it in the command):
sudo -u postgres psql -c "\password"
answered Mar 3, 2018 at 4:05
lcnicolaulcnicolau
3,2624 gold badges37 silver badges53 bronze badges
If you are on Windows.
Open pg_hba.conf
file and change from md5
to peer
.
Open cmd and type psql postgres postgres
.
Then type \password
to be prompted for a new password.
Refer to this Medium post for further information & granular steps.
answered Jun 13, 2020 at 19:27
Timothy MachariaTimothy Macharia
2,6611 gold badge20 silver badges27 bronze badges
3
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>;
answered Apr 21, 2016 at 20:53
Salvador DaliSalvador Dali
215k147 gold badges705 silver badges753 bronze badges
The configuration that I’ve got on my server was customized a lot, and I managed to change the 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.
answered Jan 11, 2014 at 20:39
ruruskyiruruskyi
2,0182 gold badges26 silver badges37 bronze badges
2
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';
answered Feb 12, 2018 at 11:52
Chris DareChris Dare
1711 silver badge9 bronze badges
For my case on Ubuntu 14.04 (Trusty Tahr), installed with PostgreSQL 10.3: I need to follow the following steps
-
su - postgres
to switch the user topostgres
-
psql
to enter the PostgreSQL shell -
\password
and then enter your password -
Q to quit the shell session
-
Then 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 PostgreSQL service by
service postgresql restart
-
Now switch to the
postgres
user and enter the PostgreSQL shell again. It will prompt you for a password.
answered Mar 25, 2018 at 19:47
haxporhaxpor
2,4613 gold badges27 silver badges46 bronze badges
1
TLDR:
On many systems, a user’s account often contains a period, or some sort of punctuation (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';
Rationale:
PostgreSQL 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.
answered Jun 1, 2020 at 18:28
FlyingVFlyingV
2,2371 gold badge19 silver badges18 bronze badges
1
This is similar to other answers in syntax, but it should be known that you can also pass the MD5 hash value 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, it’s 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 administrator 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 hash value of the password.
-
PostgreSQL, when hashing a password as MD5, salts the password with the user name and then prepends the text «md5» to the resulting hash.
-
Example: «md5″+md5(password + username)
-
In Bash:
echo -n "passwordStringUserName" | md5sum | awk '{print "md5"$1}'
Output:
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 likeALTER USER UserName WITH PASSWORD 'md5d6a35858d61d85e4a82ab1fb044aba9d';
-
Relevant links (note I will only link to the latest versions of the documentation. For older, it changes some, but MD5 is still supported 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
-
PostgreSQL password authentication documentation
-
Building PostgreSQL password MD5 hash value
answered Aug 20, 2019 at 19:52
jkdbajkdba
2,3983 gold badges23 silver badges33 bronze badges
And the fully automated way with Bash and expect (in this example we provision a new PostgreSQL administrator with the newly provisioned PostgreSQL password both on OS and PostgreSQL run-time level):
# 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 ;
"
answered Oct 20, 2019 at 8:35
Yordan GeorgievYordan Georgiev
5,1141 gold badge56 silver badges53 bronze badges
Change password to «postgres» for user «postgres»:
# ALTER USER postgres WITH ENCRYPTED PASSWORD '<NEW-PASSWORD>';
answered Oct 30, 2021 at 10:34
1
I was on Windows (Windows Server 2019; PostgreSQL 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:
- backup
pg_hba.conf
topg_hba.orig.conf
e.g. - create
pg_hba.conf
with only this:host all all 127.0.0.1/32 trust
- restart pg (service)
- execute
psql -U postgres -h 127.0.0.1
- enter (in pgctl console)
alter user postgres with password 'SomePass';
- restore
pg_hba.conf
from 1. above
answered Mar 5, 2021 at 13:46
Andreas CovidiotAndreas Covidiot
4,3365 gold badges51 silver badges97 bronze badges
One hacky way of changing your pgsql password is executing this command in the terminal as a superuser
ALTER USER username WITH PASSWORD 'your password'
You may have to restart your server for this to take effect.
I hope this helps!
answered Jul 10 at 12:04
1
In general, just use the pgAdmin UI for doing database-related activity.
If instead you are focusing more in automating database setup for your local development, CI, etc.
For example, you can use a simple combination 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 PostgreSQL database.
(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' "
PostgreSQL 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 PostgreSQL, and it is overall quite trivial to integrate this into your development setup scripts or into automated CI configuration.
answered Nov 1, 2019 at 17:41
99Sono99Sono
3,55428 silver badges39 bronze badges
Changing password of a PostgreSQL User is fairly simple task.
After starting Postgres, use the following command.
ALTER ROLE username
WITH PASSWORD 'password';
Instead of username write the user you want to alter and in » where password is written, write the new password, you want for the user.
For further understanding, visit following article: How To Change The Password of a PostgreSQL User
answered Jul 31 at 6:05
You can easily change the password by executing the following command line code:
sudo -u postgres psql -c "ALTER USER postgres PASSWORD '<new password>'
However, it should be noted that your unencrypted password will still be visible in plaintext in the command line history.
It would be best if you also used the ENCRYPTED
keyword explicitly if using PostgreSQL version 10 or less.
answered Aug 25 at 19:10
Check file 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: 19.1. The pg_hba.conf File
answered Oct 2, 2020 at 17:30
1
Using pgAdmin 4:
Menu Object → Change password…
answered Sep 8, 2022 at 12:59
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 or root user):
-
Edit the
pg_hba.conf
file 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, e.g.,postgresql@13-main
. Alternatively, my Bash shell provided auto-complete after enteringpostgresql@
, 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
.
- The folder of the data directory can be found by inspecting the systemd command line, easily obtained with
-
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.
answered Apr 13, 2021 at 9:05
It worked:
-
Put only one entry in pg_hba.conf.
host all all ::1/128 trust -
Make sure that you run cmd from administrator if windows
pg_ctl reload -D «C:\Program Files\PostgreSQL\15\Data» -
start psql and it won’t ask for the password and connect.
-
Now reset the password.
postgres=# alter user postgres with password ‘postgres’;
ALTER ROLE -
Now go to Pgadmin and provide the password.
connected…Bingo!
answered Apr 19 at 7:24
For those intend to use it in a CI/CD pipeline, an alternative is to use Clint Bugs’ one line solution, and assign the password to a global variable:
sudo -u postgres psql -c "ALTER USER postgres PASSWORD '$PGPASSWORD';"
Considering, of course, reading the documentation of the CI/CD tool (I used Semaphore), for the definition of the value of this global variable.
answered Jul 6 at 6:23
How do I change the password for a PostgreSQL user?
asked Oct 4, 2012 at 5:45
3
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,01212 gold badges61 silver badges79 bronze badges
answered Oct 4, 2012 at 5:55
solaimuruganvsolaimuruganv
27.3k1 gold badge20 silver badges23 bronze badges
22
To change the PostgreSQL user’s password, follow these steps:
-
log in into the psql console:
sudo -u postgres psql
-
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
(the 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
answered Oct 4, 2012 at 5:50
Clint BugsClint Bugs
12.4k1 gold badge12 silver badges11 bronze badges
11
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
6,90414 gold badges53 silver badges55 bronze badges
answered Aug 30, 2017 at 16:55
Viktor NordlingViktor Nordling
8,7244 gold badges26 silver badges23 bronze badges
6
You can and should have the users’ password encrypted:
ALTER USER username WITH ENCRYPTED PASSWORD 'password';
answered Feb 21, 2015 at 8:58
yglodtyglodt
13.9k14 gold badges91 silver badges129 bronze badges
4
To change the password using the Linux command line, use:
sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"
answered May 25, 2015 at 23:14
Vajira LasanthaVajira Lasantha
2,4553 gold badges24 silver badges39 bronze badges
4
To the change password:
sudo -u postgres psql
Then
\password postgres
Now enter the new password and confirm.
Then \q
to exit.
answered Jun 29, 2019 at 19:09
Akitha_MJAkitha_MJ
3,91225 silver badges20 bronze badges
1
Go to your PostgreSQL configuration and edit file 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 the ‘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 the PostgreSQL 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.
answered Oct 9, 2014 at 14:03
3
Setting up a password for the postgres role
sudo -u postgres psql
You will get a prompt like the following:
postgres=#
Change password to PostgreSQL for user postgres
ALTER USER postgres WITH ENCRYPTED PASSWORD 'postgres';
You will get something as follows:
ALTER ROLE
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 file
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 PostgreSQL, so the changes take effect
sudo service postgresql restart
answered Oct 30, 2021 at 10:05
CHAVDA MEETCHAVDA MEET
7778 silver badges14 bronze badges
0
To request a new password for the postgres user (without showing it in the command):
sudo -u postgres psql -c "\password"
answered Mar 3, 2018 at 4:05
lcnicolaulcnicolau
3,2624 gold badges37 silver badges53 bronze badges
If you are on Windows.
Open pg_hba.conf
file and change from md5
to peer
.
Open cmd and type psql postgres postgres
.
Then type \password
to be prompted for a new password.
Refer to this Medium post for further information & granular steps.
answered Jun 13, 2020 at 19:27
Timothy MachariaTimothy Macharia
2,6611 gold badge20 silver badges27 bronze badges
3
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>;
answered Apr 21, 2016 at 20:53
Salvador DaliSalvador Dali
215k147 gold badges705 silver badges753 bronze badges
The configuration that I’ve got on my server was customized a lot, and I managed to change the 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.
answered Jan 11, 2014 at 20:39
ruruskyiruruskyi
2,0182 gold badges26 silver badges37 bronze badges
2
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';
answered Feb 12, 2018 at 11:52
Chris DareChris Dare
1711 silver badge9 bronze badges
For my case on Ubuntu 14.04 (Trusty Tahr), installed with PostgreSQL 10.3: I need to follow the following steps
-
su - postgres
to switch the user topostgres
-
psql
to enter the PostgreSQL shell -
\password
and then enter your password -
Q to quit the shell session
-
Then 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 PostgreSQL service by
service postgresql restart
-
Now switch to the
postgres
user and enter the PostgreSQL shell again. It will prompt you for a password.
answered Mar 25, 2018 at 19:47
haxporhaxpor
2,4613 gold badges27 silver badges46 bronze badges
1
TLDR:
On many systems, a user’s account often contains a period, or some sort of punctuation (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';
Rationale:
PostgreSQL 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.
answered Jun 1, 2020 at 18:28
FlyingVFlyingV
2,2371 gold badge19 silver badges18 bronze badges
1
This is similar to other answers in syntax, but it should be known that you can also pass the MD5 hash value 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, it’s 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 administrator 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 hash value of the password.
-
PostgreSQL, when hashing a password as MD5, salts the password with the user name and then prepends the text «md5» to the resulting hash.
-
Example: «md5″+md5(password + username)
-
In Bash:
echo -n "passwordStringUserName" | md5sum | awk '{print "md5"$1}'
Output:
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 likeALTER USER UserName WITH PASSWORD 'md5d6a35858d61d85e4a82ab1fb044aba9d';
-
Relevant links (note I will only link to the latest versions of the documentation. For older, it changes some, but MD5 is still supported 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
-
PostgreSQL password authentication documentation
-
Building PostgreSQL password MD5 hash value
answered Aug 20, 2019 at 19:52
jkdbajkdba
2,3983 gold badges23 silver badges33 bronze badges
And the fully automated way with Bash and expect (in this example we provision a new PostgreSQL administrator with the newly provisioned PostgreSQL password both on OS and PostgreSQL run-time level):
# 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 ;
"
answered Oct 20, 2019 at 8:35
Yordan GeorgievYordan Georgiev
5,1141 gold badge56 silver badges53 bronze badges
Change password to «postgres» for user «postgres»:
# ALTER USER postgres WITH ENCRYPTED PASSWORD '<NEW-PASSWORD>';
answered Oct 30, 2021 at 10:34
1
I was on Windows (Windows Server 2019; PostgreSQL 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:
- backup
pg_hba.conf
topg_hba.orig.conf
e.g. - create
pg_hba.conf
with only this:host all all 127.0.0.1/32 trust
- restart pg (service)
- execute
psql -U postgres -h 127.0.0.1
- enter (in pgctl console)
alter user postgres with password 'SomePass';
- restore
pg_hba.conf
from 1. above
answered Mar 5, 2021 at 13:46
Andreas CovidiotAndreas Covidiot
4,3365 gold badges51 silver badges97 bronze badges
One hacky way of changing your pgsql password is executing this command in the terminal as a superuser
ALTER USER username WITH PASSWORD 'your password'
You may have to restart your server for this to take effect.
I hope this helps!
answered Jul 10 at 12:04
1
In general, just use the pgAdmin UI for doing database-related activity.
If instead you are focusing more in automating database setup for your local development, CI, etc.
For example, you can use a simple combination 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 PostgreSQL database.
(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' "
PostgreSQL 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 PostgreSQL, and it is overall quite trivial to integrate this into your development setup scripts or into automated CI configuration.
answered Nov 1, 2019 at 17:41
99Sono99Sono
3,55428 silver badges39 bronze badges
Changing password of a PostgreSQL User is fairly simple task.
After starting Postgres, use the following command.
ALTER ROLE username
WITH PASSWORD 'password';
Instead of username write the user you want to alter and in » where password is written, write the new password, you want for the user.
For further understanding, visit following article: How To Change The Password of a PostgreSQL User
answered Jul 31 at 6:05
You can easily change the password by executing the following command line code:
sudo -u postgres psql -c "ALTER USER postgres PASSWORD '<new password>'
However, it should be noted that your unencrypted password will still be visible in plaintext in the command line history.
It would be best if you also used the ENCRYPTED
keyword explicitly if using PostgreSQL version 10 or less.
answered Aug 25 at 19:10
Check file 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: 19.1. The pg_hba.conf File
answered Oct 2, 2020 at 17:30
1
Using pgAdmin 4:
Menu Object → Change password…
answered Sep 8, 2022 at 12:59
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 or root user):
-
Edit the
pg_hba.conf
file 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, e.g.,postgresql@13-main
. Alternatively, my Bash shell provided auto-complete after enteringpostgresql@
, 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
.
- The folder of the data directory can be found by inspecting the systemd command line, easily obtained with
-
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.
answered Apr 13, 2021 at 9:05
It worked:
-
Put only one entry in pg_hba.conf.
host all all ::1/128 trust -
Make sure that you run cmd from administrator if windows
pg_ctl reload -D «C:\Program Files\PostgreSQL\15\Data» -
start psql and it won’t ask for the password and connect.
-
Now reset the password.
postgres=# alter user postgres with password ‘postgres’;
ALTER ROLE -
Now go to Pgadmin and provide the password.
connected…Bingo!
answered Apr 19 at 7:24
For those intend to use it in a CI/CD pipeline, an alternative is to use Clint Bugs’ one line solution, and assign the password to a global variable:
sudo -u postgres psql -c "ALTER USER postgres PASSWORD '$PGPASSWORD';"
Considering, of course, reading the documentation of the CI/CD tool (I used Semaphore), for the definition of the value of this global variable.
answered Jul 6 at 6:23
Забыли пароль учетной записи postgres в PostgreSQL? Выполнить сброс не сложно. Для этого необходимо выполнить пару манипуляций.
1. Правим файл pg_hba.conf
Находим файл в папке Data директории установки PostgreSQL. В Windows путь выглядит примерно так c:\Program Files\PostgreSQL\9.2.4-1.1C\data\
В этом файле нужно найти такие строчки
# IPv4 local connections: host all all 127.0.0.1/32 md5 host all all 0.0.0.0/0 md5 # IPv6 local connections: host all all ::1/128 md5
Меняем md5 на trust.
2. Удаляем файл pgpass.conf
В Windows этот файл находится в c:\Users\Administrator\AppData\Roaming\postgresql\
Здесь хранится старый пароль от PostgreSQL. Простое изменение хранимого здесь пароля мне не помогло. Поэтому я его просто удалил.
3. Меняем пароль в pgAdmin
Запускаем pgAdmin и нам предлагается ввести пароль. Если отметить галочку сохранить, то пароль будет сохранен в pgpass.conf и больше программой запрашиваться не будет.
Чтобы обеспечить безопасность использования паролей необходимо вернуть алгоритм шифрования md5. Для этого в файле pg_hba.conf параметр trust обратно меняем на md5.
Для подключения на локальном компьютере к PostgreSQL с помощью psql, pg_dump в локальных адресах IPv4 127.0.0.1/32 и IPv6 ::1/128 значение trust нужно оставить.
Спасибо софт-сетап
Join @AdmNtsRu on Telegram
Смотрите также:
Забыли пароль учетной записи postgres в PostgreSQL? Выполнить сброс не сложно. Для этого необходимо выполнить пару манипуляций.
1. Правим файл pg_hba.conf
Находим файл в папке Data директории установки PostgreSQL. В Windows путь выглядит примерно так c:\Program Files\PostgreSQL\9.2.4-1.1C\data\
В этом файле нужно найти такие строчки
# IPv4 local connections:
host all all 127.0.0.1/32 md5
host all all 0.0.0.0/0 md5
# IPv6 local connections:
host all all ::1/128 md5
Меняем md5 на trust.
2. Удаляем файл pgpass.conf
В Windows этот файл находится в c:\Users\Administrator\AppData\Roaming\postgresql\
Здесь хранится старый пароль от PostgreSQL. Простое изменение хранимого здесь пароля мне не помогло. Поэтому я его просто удалил.
3. Меняем пароль в pgAdmin
Запускаем pgAdmin и нам предлагается ввести пароль. Если отметить галочку сохранить, то пароль будет сохранен в pgpass.conf и больше программой запрашиваться не будет.
Чтобы обеспечить безопасность использования паролей необходимо вернуть алгоритм шифрования md5. Для этого в файле pg_hba.conf параметр trust обратно меняем на md5.
Для подключения на локальном компьютере к PostgreSQL с помощью psql, pg_dump в локальных адресах IPv4 127.0.0.1/32 и IPv6 ::1/128 значение trust нужно оставить.
In this article, we will look into the step-by-step process of resetting the Postgres user password in case the user forgets it.
PostgreSQL uses the pg_hba.conf configuration file stored in the database data directory (e.g., C:\Program Files\PostgreSQL\12\data on Windows) and is used to handle user authentication. The hba in pg_hba.conf means host-based authentication.
As resetting the password requires modification in the pg_hba.conf file, you will need to login to the Postgres role without any password.
Follow the below steps to reset a password for the postgres user:
- Step 1: Create a backup of the pg_hba.conf file by copying it to a different location or just rename it to pg_hba.conf.bk
- Step 2: Now change the pg_hba.conf file by making all local connections from md5 to trust. This will help you to log in to the PostgreSQL database server without using a password.
# TYPE DATABASE USER ADDRESS METHOD # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. host replication all 127.0.0.1/32 trust host replication all ::1/128 trust
- Step 3: Now restart the PostgreSQL server. On a Windows machine, you can restart the PostgreSQL from Services.
Or use the below command from the window terminal:
pg_ctl -D "C:\Program Files\PostgreSQL\12\data" restart
The “C:\Program Files\PostgreSQL\12\data” is the data directory.
- Step 4: Finally connect to the PostgreSQL database server using any tool such as psql or pgAdmin(In pgAdmin, press ok while it prompts you to enter the password without entering anything in the field.):
psql -U postgres
At this stage, you will not be asked for any authentication.
- Step 5: Use the below command to set a new password for the postgres user.
ALTER USER postgres WITH PASSWORD 'new_password';
This will change the user’s password as shown below:
- Step 6:Now restart the PostgreSQL database server. At this stage, you can connect to the PostgreSQL database server with the new password.
Follow the above steps to successfully reset the Postgres password and do not forget to restore the pg_hba.conf file after the reset to successfully store the credentials for future verification.
Last Updated :
22 Apr, 2022
Like Article
Save Article