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
5,80712 gold badges60 silver badges77 bronze badges
answered Oct 4, 2012 at 5:55
solaimuruganvsolaimuruganv
25.8k1 gold badge18 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
11.2k1 gold badge11 silver badges11 bronze badges
10
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.3k14 gold badges86 silver badges125 bronze badges
4
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,40414 gold badges54 silver badges54 bronze badges
answered Aug 30, 2017 at 16:55
Viktor NordlingViktor Nordling
8,4344 gold badges26 silver badges23 bronze badges
6
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,4053 gold badges22 silver badges39 bronze badges
3
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,64422 silver badges18 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
6798 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,1524 gold badges38 silver badges52 bronze badges
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
209k145 gold badges690 silver badges749 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,4611 gold badge19 silver badges26 bronze badges
3
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
1,9902 gold badges26 silver badges37 bronze badges
2
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,3173 gold badges26 silver badges45 bronze badges
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';
answered Feb 12, 2018 at 11:52
Chris DareChris Dare
1511 silver badge8 bronze badges
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
1,91718 silver badges15 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,2483 gold badges22 silver badges32 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_pwr"
expect "Enter it again: "
send -- "$postgres_usr_pwr"
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
4,8681 gold badge52 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,1385 gold badges49 silver badges95 bronze badges
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
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,50427 silver badges38 bronze badges
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
I either forgot or mistyped (during the installation) the password to the default user of PostgreSQL. I can’t seem to be able to run it, and I get the following error:
psql: FATAL: password authentication failed for user "hisham"
hisham-agil: hisham$ psql
Is there a way to reset the password or how do I create a new user with superuser privileges?
I am new to PostgreSQL and just installed it for the first time. I am trying to use it with Ruby on Rails and I am running Mac OS X v10.7 (Lion).
asked Jun 1, 2012 at 7:14
1
-
Find the file pg_hba.conf. It may be located, for example, in /etc/postgresql-9.1/pg_hba.conf.
cd /etc/postgresql-9.1/
-
Back it up
cp pg_hba.conf pg_hba.conf-backup
-
Place the following line (as either the first uncommented line, or as the only one):
For all occurrence of below (local and host) , except replication
section if you don’t have any it has to be changed as follow ,no MD5
or Peer authentication should be present.local all all trust
-
Restart your PostgreSQL server (e.g., on Linux:)
sudo /etc/init.d/postgresql restart
If the service (daemon) doesn’t start reporting in log file:
local connections are not supported by this build
you should change
local all all trust
to
host all all 127.0.0.1/32 trust
-
You can now connect as any user. Connect as the superuser postgres (note, the superuser name may be different in your installation. In some systems it is called pgsql, for example.)
psql -U postgres
or
psql -h 127.0.0.1 -U postgres
(note that with the first command you will not always be connected with local host)
-
Reset the password (‘replace my_user_name with postgres since you are resetting the postgres user)
ALTER USER my_user_name with password 'my_secure_password';
-
Restore the old pg_hba.conf file as it is very dangerous to keep around
cp pg_hba.conf-backup pg_hba.conf
-
Restart the server, in order to run with the safe pg_hba.conf file
sudo /etc/init.d/postgresql restart
Further reading about that pg_hba file: 19.1. The pg_hba.conf File (official documentation)
answered Jun 1, 2012 at 7:42
Arsen7Arsen7
12.4k2 gold badges43 silver badges60 bronze badges
19
When connecting to PostgreSQL from the command line, don’t forget to add -h localhost
as a command line parameter. If not, PostgreSQL will try to connect using PEER authentication mode.
The below shows a reset of the password, a failed login with PEER authentication and a successful login using a TCP connection.
# sudo -u postgres psql
could not change directory to "/root"
psql (9.1.11)
Type "help" for help.
postgres=# password
Enter new password:
Enter it again:
postgres=# q
Failing:
# psql -U postgres -W
Password for user postgres:
psql: FATAL: Peer authentication failed for user "postgres"
Working with -h localhost
:
# psql -U postgres -W -h localhost
Password for user postgres:
psql (9.1.11)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
Type "help" for help.
postgres=#
answered Feb 2, 2014 at 10:21
SaeXSaeX
16.6k15 gold badges74 silver badges95 bronze badges
1
The pg_hba.conf
(C:Program FilesPostgreSQL9.3data
) file has changed since these answers were given. What worked for me, in Windows, was to open the file and change the METHOD
from md5
to trust
:
# 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
Then, using pgAdmin III, I logged in without using a password and changed user postgres
‘s password by going to menu File → Change Password.
answered Sep 19, 2014 at 22:26
SaiyanGirlSaiyanGirl
16k11 gold badges40 silver badges56 bronze badges
6
I was just having this problem on Windows 10 and the issue in my case was that I was just running psql
and it was defaulting to trying to log in with my Windows username («Nathan»), but there was no PostgreSQL user with that name, and it wasn’t telling me that.
So the solution was to run psql -U postgres
rather than just psql
, and then the password I entered at installation worked.
answered Jun 26, 2019 at 21:29
Nathan WailesNathan Wailes
8,9806 gold badges52 silver badges90 bronze badges
0
-
Edit the file
/etc/postgresql/<version>/main/pg_hba.conf
and find the following line:local all postgres md5
-
Edit the line and change
md5
at the end totrust
and save the file -
Reload the postgresql service
sudo service postgresql reload
-
This will load the configuration files. Now you can modify the
postgres
user by logging into thepsql
shellpsql -U postgres
-
Update the
postgres
user’s passwordalter user postgres with password 'secure-passwd-here';
-
Edit the file
/etc/postgresql/<version>/main/pg_hba.conf
and changetrust
back tomd5
and save the file -
Reload the postgresql service
sudo service postgresql reload
-
Verify that the password change is working
psql -U postgres -W
answered Aug 17, 2017 at 2:55
Ray HunterRay Hunter
14.9k5 gold badges52 silver badges51 bronze badges
2
For Windows (what has helped me):
This is the document I am referring to: How can I reset a PostgreSQL password?
-
Open your cmd and go to
C:Program FilesPostgreSQL12data
.
This is usually the right path. You might have it stored somewhere else. Note that, if you have a different PostgreSQL version, there will be a different number. That doesn’t matter. -
Find a pg_hba.conf file and copy it to somewhere else (that way you will have an unmodified version of this file, so you will be able to look at it after we make some changes)
-
Open the pg_hba.conf file (not the backup, but the original)
-
Find the multiple lines that start with host near the bottom of the file:
host all all 127.0.0.1/32 md5 host all all ::1/128 md5 host replication all 127.0.0.1/32 md5 host replication all ::1/128 md5
-
Replace md5 with trust:
host all all 127.0.0.1/32 trust host all all ::1/128 trust host replication all 127.0.0.1/32 trust host replication all ::1/128 trust
-
Close this file
-
Go to your search bar on windows and open Services app. Find postgres and restart it.
Picture of services app
-
Write cd.. in cmd and then cd bin. Your path should be
C:Program FilesPostgreSQL12bin
-
Enter:
psql -U postgres -h localhost
-
Enter:
ALTER USER postgres with password '<your new password>';
Make sure that you include ; at the end
“ALTER ROLE” should be displayed as an indication that the previous line was executed successfully -
Open original pg_hba.conf file and change back from trust to md5
-
Restart the server with Services app as before
answered Nov 15, 2020 at 22:14
Vito FarinaVito Farina
2012 silver badges2 bronze badges
1
Just a note: On Linux, you can simply run sudo su - postgres
to become the postgres user and from there change what is required using psql.
answered Mar 12, 2018 at 12:58
DanielDaniel
1891 silver badge4 bronze badges
2
For a Windows user for the latest PostgreSQL version (greater than 10):
Go to your PostgreSQL installation location, and search for pg_hba.conf
, you will find it in ..postgresdatapg_hba.conf
.
Open that file with Notepad, and find this line:
# TYPE DATABASE USER ADDRESS METHOD
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
#..
Change the method from *md5* to *trust*:
# 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
# ...
Now go to your SQL shell (PSQL) and leave everything blank,
Server [localhost]:
Database [postgres]:
Port [8000]:
Username [postgres]:
It will not ask for a password this time, and you will be logged in,
Now run this line:
`ALTER USER yourusername WITH SUPERUSER`
Now you can leave the shell with q.
Again, go to the file pg_hba.conf and change METHOD from trust to md5 again, and save it.
Now log in with your new user and password, and you can check du for its attributes.
answered Feb 3, 2019 at 13:40
Bidhan MajhiBidhan Majhi
1,2901 gold badge12 silver badges25 bronze badges
For a Windows installation, a Windows user is created. And «psql» uses this user for connection to the port. If you change the PostgreSQL user’s password, it won’t change the Windows one.
The command line just below works only if you have access to the command line.
Instead, you could use the Windows GUI application «c:Windowssystem32lusrmgr.exe». This application manages users created by Windows. So you can now modify the password.
answered Mar 21, 2017 at 15:31
2
I did this to resolve the same problem:
Open the pg_hba.conf file with the gedit editor from the terminal:
sudo gedit /etc/postgresql/9.5/main/pg_hba.conf
It will ask for a password. Enter your admin login password.
This will open gedit with the file. Paste the following line:
host all all 127.0.0.1/32 trust
just below -
# Database administrative login by Unix domain socket
Save and close it.
Close the terminal, open it again and run this command:
psql -U postgres
You will now enter the psql console.
Now change the password by entering this:
ALTER USER [your preferred user name] with password '[desired password]';
If it says the user does not exist then instead of ALTER
, use CREATE
.
Lastly, remove that certain line you pasted in pg_hba and save it.
answered Nov 14, 2017 at 12:08
Taufiq RahmanTaufiq Rahman
5,4952 gold badges36 silver badges43 bronze badges
If you are running PostgreSQL on macOS, try these:
1. Edit the pg_hba.conf file
sudo vi /Library/PostgreSQL/9.2/data/pg_hba.conf
and Change the «md5» method for all users to «trust» near the bottom of the file
2. Find the name of the postgres service
ls /Library/LaunchDaemons
Look for postgresql
3. Restart the postgresql service
sudo launchctl stop com.edb.launchd.postgresql-9.2
sudo launchctl start com.edb.launchd.postgresql-9.2
(com.edb.launchd.postgresql-9.2 should be name postgresql service from step 3)
4. Start a psql session as postgres
psql -U postgres
(shouldn’t ask for password because of ‘trust’ setting)
5. Reset password in the psql session by typing:
ALTER USER postgres with password 'secure-new-password';
6. Edit the pg_hba.conf file
Switch it back to ‘md5’
8. Restart services again
answered Mar 16, 2020 at 15:22
DavidDavid
3,74330 silver badges36 bronze badges
If you are on Windows you can just run
net user postgres postgres
And log in in PostgreSQL with postgres/postgres as the user/password.
answered Jun 7, 2016 at 16:36
0
Follow step 1 on the best answer.
Here is my addition if you use the Windows operating system. Follow only step 1, and then open pgAdmin or postgres on web and click on file on the top nav. Click on reset layout, and finally reload the application. Whatever password you put should work. I used 1234.
answered Jun 27, 2022 at 11:12
I didn’t manage to find the file pg_hba.conf
in the folder C:Program FilesPostgreSQL14data
, because there is not a folder data
at all.
I solved the problem by creating a new user using pgAdmin and gave it super system administrator rights.
answered Nov 23, 2022 at 15:31
BarabasBarabas
8528 silver badges17 bronze badges
Add the below line to your pg_hba.conf file. Which will be present in the installation directory of PostgreSQL
hostnossl all all 0.0.0.0/0 trust
It will start working.
answered Feb 26, 2021 at 10:47
I either forgot or mistyped (during the installation) the password to the default user of PostgreSQL. I can’t seem to be able to run it, and I get the following error:
psql: FATAL: password authentication failed for user "hisham"
hisham-agil: hisham$ psql
Is there a way to reset the password or how do I create a new user with superuser privileges?
I am new to PostgreSQL and just installed it for the first time. I am trying to use it with Ruby on Rails and I am running Mac OS X v10.7 (Lion).
asked Jun 1, 2012 at 7:14
1
-
Find the file pg_hba.conf. It may be located, for example, in /etc/postgresql-9.1/pg_hba.conf.
cd /etc/postgresql-9.1/
-
Back it up
cp pg_hba.conf pg_hba.conf-backup
-
Place the following line (as either the first uncommented line, or as the only one):
For all occurrence of below (local and host) , except replication
section if you don’t have any it has to be changed as follow ,no MD5
or Peer authentication should be present.local all all trust
-
Restart your PostgreSQL server (e.g., on Linux:)
sudo /etc/init.d/postgresql restart
If the service (daemon) doesn’t start reporting in log file:
local connections are not supported by this build
you should change
local all all trust
to
host all all 127.0.0.1/32 trust
-
You can now connect as any user. Connect as the superuser postgres (note, the superuser name may be different in your installation. In some systems it is called pgsql, for example.)
psql -U postgres
or
psql -h 127.0.0.1 -U postgres
(note that with the first command you will not always be connected with local host)
-
Reset the password (‘replace my_user_name with postgres since you are resetting the postgres user)
ALTER USER my_user_name with password 'my_secure_password';
-
Restore the old pg_hba.conf file as it is very dangerous to keep around
cp pg_hba.conf-backup pg_hba.conf
-
Restart the server, in order to run with the safe pg_hba.conf file
sudo /etc/init.d/postgresql restart
Further reading about that pg_hba file: 19.1. The pg_hba.conf File (official documentation)
answered Jun 1, 2012 at 7:42
Arsen7Arsen7
12.4k2 gold badges43 silver badges60 bronze badges
19
When connecting to PostgreSQL from the command line, don’t forget to add -h localhost
as a command line parameter. If not, PostgreSQL will try to connect using PEER authentication mode.
The below shows a reset of the password, a failed login with PEER authentication and a successful login using a TCP connection.
# sudo -u postgres psql
could not change directory to "/root"
psql (9.1.11)
Type "help" for help.
postgres=# password
Enter new password:
Enter it again:
postgres=# q
Failing:
# psql -U postgres -W
Password for user postgres:
psql: FATAL: Peer authentication failed for user "postgres"
Working with -h localhost
:
# psql -U postgres -W -h localhost
Password for user postgres:
psql (9.1.11)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
Type "help" for help.
postgres=#
answered Feb 2, 2014 at 10:21
SaeXSaeX
16.6k15 gold badges74 silver badges95 bronze badges
1
The pg_hba.conf
(C:Program FilesPostgreSQL9.3data
) file has changed since these answers were given. What worked for me, in Windows, was to open the file and change the METHOD
from md5
to trust
:
# 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
Then, using pgAdmin III, I logged in without using a password and changed user postgres
‘s password by going to menu File → Change Password.
answered Sep 19, 2014 at 22:26
SaiyanGirlSaiyanGirl
16k11 gold badges40 silver badges56 bronze badges
6
I was just having this problem on Windows 10 and the issue in my case was that I was just running psql
and it was defaulting to trying to log in with my Windows username («Nathan»), but there was no PostgreSQL user with that name, and it wasn’t telling me that.
So the solution was to run psql -U postgres
rather than just psql
, and then the password I entered at installation worked.
answered Jun 26, 2019 at 21:29
Nathan WailesNathan Wailes
8,9806 gold badges52 silver badges90 bronze badges
0
-
Edit the file
/etc/postgresql/<version>/main/pg_hba.conf
and find the following line:local all postgres md5
-
Edit the line and change
md5
at the end totrust
and save the file -
Reload the postgresql service
sudo service postgresql reload
-
This will load the configuration files. Now you can modify the
postgres
user by logging into thepsql
shellpsql -U postgres
-
Update the
postgres
user’s passwordalter user postgres with password 'secure-passwd-here';
-
Edit the file
/etc/postgresql/<version>/main/pg_hba.conf
and changetrust
back tomd5
and save the file -
Reload the postgresql service
sudo service postgresql reload
-
Verify that the password change is working
psql -U postgres -W
answered Aug 17, 2017 at 2:55
Ray HunterRay Hunter
14.9k5 gold badges52 silver badges51 bronze badges
2
For Windows (what has helped me):
This is the document I am referring to: How can I reset a PostgreSQL password?
-
Open your cmd and go to
C:Program FilesPostgreSQL12data
.
This is usually the right path. You might have it stored somewhere else. Note that, if you have a different PostgreSQL version, there will be a different number. That doesn’t matter. -
Find a pg_hba.conf file and copy it to somewhere else (that way you will have an unmodified version of this file, so you will be able to look at it after we make some changes)
-
Open the pg_hba.conf file (not the backup, but the original)
-
Find the multiple lines that start with host near the bottom of the file:
host all all 127.0.0.1/32 md5 host all all ::1/128 md5 host replication all 127.0.0.1/32 md5 host replication all ::1/128 md5
-
Replace md5 with trust:
host all all 127.0.0.1/32 trust host all all ::1/128 trust host replication all 127.0.0.1/32 trust host replication all ::1/128 trust
-
Close this file
-
Go to your search bar on windows and open Services app. Find postgres and restart it.
Picture of services app
-
Write cd.. in cmd and then cd bin. Your path should be
C:Program FilesPostgreSQL12bin
-
Enter:
psql -U postgres -h localhost
-
Enter:
ALTER USER postgres with password '<your new password>';
Make sure that you include ; at the end
“ALTER ROLE” should be displayed as an indication that the previous line was executed successfully -
Open original pg_hba.conf file and change back from trust to md5
-
Restart the server with Services app as before
answered Nov 15, 2020 at 22:14
Vito FarinaVito Farina
2012 silver badges2 bronze badges
1
Just a note: On Linux, you can simply run sudo su - postgres
to become the postgres user and from there change what is required using psql.
answered Mar 12, 2018 at 12:58
DanielDaniel
1891 silver badge4 bronze badges
2
For a Windows user for the latest PostgreSQL version (greater than 10):
Go to your PostgreSQL installation location, and search for pg_hba.conf
, you will find it in ..postgresdatapg_hba.conf
.
Open that file with Notepad, and find this line:
# TYPE DATABASE USER ADDRESS METHOD
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
#..
Change the method from *md5* to *trust*:
# 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
# ...
Now go to your SQL shell (PSQL) and leave everything blank,
Server [localhost]:
Database [postgres]:
Port [8000]:
Username [postgres]:
It will not ask for a password this time, and you will be logged in,
Now run this line:
`ALTER USER yourusername WITH SUPERUSER`
Now you can leave the shell with q.
Again, go to the file pg_hba.conf and change METHOD from trust to md5 again, and save it.
Now log in with your new user and password, and you can check du for its attributes.
answered Feb 3, 2019 at 13:40
Bidhan MajhiBidhan Majhi
1,2901 gold badge12 silver badges25 bronze badges
For a Windows installation, a Windows user is created. And «psql» uses this user for connection to the port. If you change the PostgreSQL user’s password, it won’t change the Windows one.
The command line just below works only if you have access to the command line.
Instead, you could use the Windows GUI application «c:Windowssystem32lusrmgr.exe». This application manages users created by Windows. So you can now modify the password.
answered Mar 21, 2017 at 15:31
2
I did this to resolve the same problem:
Open the pg_hba.conf file with the gedit editor from the terminal:
sudo gedit /etc/postgresql/9.5/main/pg_hba.conf
It will ask for a password. Enter your admin login password.
This will open gedit with the file. Paste the following line:
host all all 127.0.0.1/32 trust
just below -
# Database administrative login by Unix domain socket
Save and close it.
Close the terminal, open it again and run this command:
psql -U postgres
You will now enter the psql console.
Now change the password by entering this:
ALTER USER [your preferred user name] with password '[desired password]';
If it says the user does not exist then instead of ALTER
, use CREATE
.
Lastly, remove that certain line you pasted in pg_hba and save it.
answered Nov 14, 2017 at 12:08
Taufiq RahmanTaufiq Rahman
5,4952 gold badges36 silver badges43 bronze badges
If you are running PostgreSQL on macOS, try these:
1. Edit the pg_hba.conf file
sudo vi /Library/PostgreSQL/9.2/data/pg_hba.conf
and Change the «md5» method for all users to «trust» near the bottom of the file
2. Find the name of the postgres service
ls /Library/LaunchDaemons
Look for postgresql
3. Restart the postgresql service
sudo launchctl stop com.edb.launchd.postgresql-9.2
sudo launchctl start com.edb.launchd.postgresql-9.2
(com.edb.launchd.postgresql-9.2 should be name postgresql service from step 3)
4. Start a psql session as postgres
psql -U postgres
(shouldn’t ask for password because of ‘trust’ setting)
5. Reset password in the psql session by typing:
ALTER USER postgres with password 'secure-new-password';
6. Edit the pg_hba.conf file
Switch it back to ‘md5’
8. Restart services again
answered Mar 16, 2020 at 15:22
DavidDavid
3,74330 silver badges36 bronze badges
If you are on Windows you can just run
net user postgres postgres
And log in in PostgreSQL with postgres/postgres as the user/password.
answered Jun 7, 2016 at 16:36
0
Follow step 1 on the best answer.
Here is my addition if you use the Windows operating system. Follow only step 1, and then open pgAdmin or postgres on web and click on file on the top nav. Click on reset layout, and finally reload the application. Whatever password you put should work. I used 1234.
answered Jun 27, 2022 at 11:12
I didn’t manage to find the file pg_hba.conf
in the folder C:Program FilesPostgreSQL14data
, because there is not a folder data
at all.
I solved the problem by creating a new user using pgAdmin and gave it super system administrator rights.
answered Nov 23, 2022 at 15:31
BarabasBarabas
8528 silver badges17 bronze badges
Add the below line to your pg_hba.conf file. Which will be present in the installation directory of PostgreSQL
hostnossl all all 0.0.0.0/0 trust
It will start working.
answered Feb 26, 2021 at 10:47
На чтение 5 мин Просмотров 10.6к. Опубликовано 17.12.2021
Это необходимо для защиты ваших данных и информации от любых вторжений, которые могут быть выполнены с помощью паролей для ваших пользователей. Пароли используются для защиты ваших данных от любых неудач в будущем, чтобы ни один другой пользователь, кроме вас, не мог войти в систему. Они необходимы, когда вы вошли в систему или вошли в определенную систему для целей аутентификации.
В PostgreSQL, когда вы однажды установили программу установки, она попросит вас установить пароль для базы данных по умолчанию, то есть «postgres». Вы также можете позже создать собственного пользователя в PostgreSQL и установить для него пароль. Но что, если возникает необходимость изменить пароль для управления базой данных или административных функций, и в вашей голове возникает вопрос, как и откуда вы можете изменить пароль? Не о чем беспокоиться, потому что эта статья будет специально посвящена ответу на ваш вопрос с помощью простых и различных способов изменения паролей пользователей в PostgreSQL. Это руководство поможет вам изменить пароли пользователей и четко определить каждый шаг для вашего лучшего понимания.
Различные режимы изменения пароля пользователя:
Вы можете изменить пароли пользователей двумя разными способами в PostgreSQL. В обоих методах вы можете создать и установить пароль, а также изменить его. Вот эти два метода:
- Используя pgAdmin.
- Используя psql.
Содержание
- Шаги по изменению пароля с помощью pgAdmin
- Изменить пароль через psql
- Измените пароль с помощью операторов ALTER ROLE
- Измените пароль с помощью мета-команды
- Вывод
Шаги по изменению пароля с помощью pgAdmin
Когда вы открываете PostgreSQL, перед вами отображается примерно следующее:
С левой стороны можно увидеть меню навигации, в котором определены «Логин / Групповые роли». При нажатии на нее появляется выпадающий список.
В этом списке хранятся все имена пользователей, которые существуют в базе данных, вместе с их определенными и привилегированными ролями.
Давайте сначала создадим имя пользователя и установим пароль для этого имени пользователя, а затем мы изменим пароль. Чтобы создать имя пользователя, нажмите «Логин / Роли группы» и нажмите «Создать» логин или групповую роль. Здесь мы создадим роль входа в базу данных с желаемыми ролями.
После нажатия на «Логин / Групповые роли» появится следующее:
В поле имени вы можете указать любое имя, какое захотите. Затем нажмите «Определения» и введите пароль для своего имени пользователя.
В «Привилегиях» определите свои роли пользователей и в конце сохраните данные для входа в систему.
Теперь вы создали пользователя и можете просто изменить пароль, щелкнув свое имя пользователя, а затем «Свойства» на боковой панели навигации следующим образом:
В окне «Свойства» откроется тот же экран, на котором вы создали имя пользователя для входа в систему. Здесь в «Паролях» вы можете ввести свой новый пароль и сохранить его в конце.
В поле «Пароли» повторно введите новый пароль, и ваш пароль будет изменен на имя пользователя «saeed_raza».
Изменить пароль через psql
В оболочке SQL (psql) вы также можете изменить пароль двумя способами:
- Использование операторов ALTER ROLE.
- Использование мета-команд.
Измените пароль с помощью операторов ALTER ROLE
Операторы ALTER ROLE используются для изменения паролей пользователя в PostgreSQL. Вот основной синтаксис для использования операторов ALTER Role в вашей базе данных:
В приведенном выше заявлении укажите имя пользователя вместо «имени пользователя», пароль которого вы хотите изменить. Затем введите новый пароль вместо new_password, чтобы изменить пароль. Предложение VALID UNTIL не является обязательным; он используется для ввода периода времени, в течение которого вы хотите, чтобы пароль действовал после указанной даты или времени, когда истечет срок действия пароля.
Ниже приведена иллюстрация изменения пароля пользователя «saeed_raza» на новый пароль «data».
ALTER ROLE saeed_raza WITH PASSWORD ‘data’;
Команда ALTER ROLE после оператора SQL обеспечивает изменение пароля в базе данных.
Давайте посмотрим еще один пример изменения пароля, который будет действовать в течение определенного периода, который мы назначим:
ALTER ROLE saeed_raza WITH PASSWORD ‘defined’
VALID UNTIL ‘March 30, 2022’ ;
Я изменил пароль с «данные» на «определенный» для имени пользователя «saeed_raza» и упомянул дату, когда пароль для этого имени пользователя станет действительным, а именно «30 марта 2022 года». Срок действия пароля истечет до этой даты, но если вы не добавите в оператор предложение VALID UNTIL, пароль будет действителен в течение всего времени жизни.
Чтобы убедиться, что пароль действителен до этой даты, выполните следующую команду для проверки:
Эта команда отобразит все списки ролей, которые присутствуют в базах данных, с их атрибутами и именем пользователя. Приведенная выше команда покажет следующие результаты:
В приведенных выше выходных данных вы можете ясно видеть, что в имени роли «saeed_raza» пароль действителен до 30 марта 2022 года.
Измените пароль с помощью мета-команды
В приведенном выше методе для изменения пароля с помощью операторов ALTER ROLE мы увидели, что пароль виден системе, и она также передаст этот пароль на сервер, который также может быть сохранен в истории операторов psql. Вы можете изменить пароль, сохранив его в надежном и безопасном месте в журнале сервера и его истории с помощью этого метода.
Во-первых, при запуске psql вы должны ввести имя пользователя, пароль которого вы хотите изменить:
Я ввел имя пользователя saeed_raza, потому что хочу изменить пароль этого пользователя в PostgreSQL. Теперь следуйте этому простому синтаксису, который также изменит пароль пользователя или пароль по умолчанию PostgreSQL, просто используя метакоманду:
postgres=# password
Enter new password:
Enter it again:
Теперь пароль для пользователя saeed_raza изменен с помощью этой простой метакоманды.
Вывод
В этом руководстве мы узнали, как можно изменить пароль пользователя с помощью pgAdmin и psql, а также с различными способами psql. Все методы, которые мы использовали в этой статье, были эффективными и простыми, которые вы можете реализовать в своей системе, чтобы окончательно ответить на ваши вопросы о том, как изменить пароли пользователей в PostgreSQL.
Обновлено: 17.09.2021
Опубликовано: 20.07.2016
Что такое PostgreSQL простыми словами.
Создание пользователя
Использование групп
Редактирование пользователя
Удаление пользователя или группы
Особые права
Для резервного копирования
Графический интерфейс
Часть нижеописанных операций нужно выполнять в командной оболочке PostgreSQL. Она может быть запущена от пользователя postgres — чтобы войти в систему от данного пользователя, вводим:
su — postgres
* если система выдаст ошибку, связанную с нехваткой прав, сначала повышаем привилегии командой sudo su или su.
Теперь запускаем командную оболочку PostgreSQL:
$ psql -Upostgres template1
* в данном примере, вход выполняется от учетной записи postgres к шаблонной базе template1.
Для просмотра всех пользователей СУБД:
=# select * from pg_user;
Создание нового пользователя
Для того, чтобы была возможность подключения к СУБД PostgreSQL от нового пользователя, необходимо создать данного пользователя, назначить ему права, выполнить настройку файла pg_hba.conf.
1. Создание пользователя
а) Добавление новой роли (пользователя) из оболочки SQL:
=# CREATE USER dmosk WITH PASSWORD ‘myPassword’;
* в примере создана роль dmosk с паролем myPassword.
б) Добавление новой роли (пользователя) из командной строки Linux:
createuser -P dmosk
2. Назначение прав на использование базы данных
Даем права на базу командой:
=# GRANT ALL PRIVILEGES ON DATABASE «database1» to dmosk;
Теперь подключаемся к базе, к которой хотим дать доступ:
=# c database1
* в примере подсоединимся к базе с названием database1.
а) Так мы добавим все права на использование всех таблиц в базе database1 учетной записи dmosk:
database1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO «dmosk»;
* в большинстве случаев, используется схема по умолчанию public. Но администратор может создать новую схему. Это нужно учитывать при назначении прав.
б) Также можно дать доступ к базе для определенных таблиц:
database1=# GRANT ALL PRIVILEGES ON TABLE table1 IN SCHEMA public TO «dmosk»;
* в данном примере мы даем права на таблицу table1.
Выходим из SQL-оболочки:
database1=# q
3. Настройка файла pg_hba.conf
Для возможности подключиться к СУБД от созданного пользователя, необходимо проверить настройки прав в конфигурационном файле pg_hba.conf.
Для начала смотрим путь расположения данных для PostgreSQL:
=# SHOW config_file;
В ответ мы получим, что-то на подобие:
——————————————
/var/lib/pgsql/9.6/data/postgresql.conf
(1 row)
* в данном примере /var/lib/pgsql/9.6/data/ — путь расположения конфигурационных файлов.
Открываем pg_hba.conf:
vi /var/lib/pgsql/9.6/data/pg_hba.conf
Добавляем права на подключение нашему созданному пользователю:
…
# IPv4 local connections:
host all dmosk 127.0.0.1/32 md5
…
* в данном примере мы разрешили подключаться пользователю dmosk ко всем базам на сервере (all) от узла 127.0.0.1 (localhost) с требованием пароля (md5).
* необходимо, чтобы данная строка была выше строки, которая прописана по умолчанию
host all all 127.0.0.1/32 ident.
После перезапускаем службу:
systemctl restart postgresql-9.6
* в данном примере установлен postgresql версии 9.6, для разных версий на разных операционных системах команды для перезапуска сервиса могут быть разные.
4. Проверка
Для теста пробуем подключиться к Postgre с помощью созданного пользователя:
psql -Udmosk template1 -h127.0.0.1
Настройка прав доступа к базе с помощью групп
Сначала создадим групповую роль:
=# CREATE ROLE «myRole» NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION;
* данной командой создана группа myRole с минимальными правами.
Теперь добавим ранее созданного пользователя dmosk в эту группу:
=# GRANT «myRole» TO dmosk;
Подключимся к базе данных, для которой хотим настроить права
=# c database1
и предоставим все права для группы myRole всем таблицам базы database1
database1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO GROUP «myRole»;
Редактирование пользователя
1. Смена пароля
Рассмотрим несколько примеров смены пароля пользователя.
Одной командой:
=# ALTER USER postgres PASSWORD ‘password’
* в данном примере мы зададим пароль password для пользователя postgres.
С запросов ввода пароля:
=# password postgres
* после ввода данной команды система потребует дважды ввести пароль для пользователя (в нашем примере, postgres).
Из командной строки Linux:
sudo -u postgres psql -U postgres -d postgres -c «ALTER USER postgres PASSWORD ‘password'»
* по сути, мы выполняем также запрос в оболочке sql.
Удаление пользователей и групп
Удаление пользователя выполняется следующей командой:
=# DROP USER dmosk;
Забрать права:
database1=# REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM «dmosk»;
* обратите внимание, данный запрос отличается от предоставления прав двумя моментами: 1) вместо GRANT пишем REVOKE; 2) вместо TO «dmosk» пишем FROM «dmosk»;
Назначение особых прав пользователям PostgreSQL
Помимо ALL PRIVILEGES можно выдавать права на особые операции, например:
=# GRANT SELECT, UPDATE, INSERT ON ALL TABLES IN SCHEMA public TO «dmosk»;
* команда позволит выдать права на получение данных, их обновление и добавление. Другие операции, например, удаление будут запрещены для пользователя dmosk.
Назначение прав для определенной таблицы:
database1=# GRANT ALL PRIVILEGES ON table_users TO «dmosk»;
* в данном примере мы предоставим все права на таблицу table_users в базе данных database1;
Учетная запись для резервного копирования
Для выполнения резервного копирования лучше всего подключаться к базе с минимальными привилегиями.
Сначала создаем роль, которую будем использовать для выполнения резервного копирования:
=# CREATE USER bkpuser WITH PASSWORD ‘bkppasswd’;
* мы создадим учетную запись bkpuser с паролем bkppasswd.
Предоставляем права на подключения к базе
=# GRANT CONNECT ON DATABASE database TO bkpuser;
* в данном примере к базе database.
Подключаемся к базе (в нашем примере database):
=# c database
Даем права на все последовательности в схеме:
=# GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO bkpuser;
* мы дали права для схемы public. Это схема является схемой по умолчанию, но в вашем случае она может быть другой. В таком случае, подставляем свое значение.
Графический интерфейс
Иногда проще воспользоваться программой для выставления прав и работы с PostgreSQL. Могу посоветовать приложение pgAdmin. Оно позволит в оконном режиме не только создать и удалить пользователей, но и полноценно работать с СУБД.
In this Postgresql tutorial, we are going to learn about “Postgresql set user password”, which means changing the password of an existing user in the Postgres database on different environments like Windows, Ubuntu, etc.
We are going to cover the following topics.
- How to set user password in PostgreSQL in windows OS
- Set user password in PostgreSQL in ubuntu
- Change user password using pgadmin in PostgreSQL
In Postgresql, We can change the password of the user using the below syntax.
Syntax:
ALTER USER user_name WITH PASSWORD 'new_password';
Here ALTER USER is a command that changes the attributes of a PostgreSQL user account, user_name is the name of the user whose password is to be altered and new_password is the password that you want to set for the user.
We can change password of a Postgresql user account using the command line in windows.
The following are the instructions to change the password of the user.
Open CMD on your computer using CTRL+R and type cmd in the box, then hit Enter from your keyboard.
Enter into psql command prompt as postgres user using below command.
If it asks for a password, then enter the password of the user and remember the password.
psql -U postgres
Now change the password of the current user postgres.
ALTER USER postgres WITH PASSWORD '23456';
Now remember this new password and forget the password that we have remembered before for a user named postgres.
Exit from the psql prompt.
q -- To exit from psql prompt in Postgresql databast
We have successfully change the password of a user named Postgres.
Now log in again with the new password of user Postgres.
psql -U postgres
if it asks for a password, enter the new password that we have set recently.
Read: How to create a table in PostgreSQL
Postgresql set user password ubuntu
In Ubuntu, we can change the password of the Postgresql user account using the terminal.
Open the terminal using CTRL+ALT+T from your keyboard and log into the Postgres prompt using the below command.
sudo su - postgres
Enter into psql prompt.
psql
Now change the password of the user named postgres.
ALTER USER postgres WITH PASSWORD '23456';
Exit from psql prompt and logout from Postgres prompt.
exit -- To exit from psql and postgres prompt
From the above output, we see the output “ALTER ROLE”, which means the password changed successfully.
Now again log in with the new password and if it asks for a password, then enter the new password.
sudo -i -u postgres
You will successfully be logged in.
Read: PostgreSQL installation on Linux
Postgresql change user password pgadmin
In Postgresql, we can also change the user password from the pgAdmin application.
The following are the instructions to change passwords in the Postgresql database.
Open pdAdmin, go to Browser section and expand icon > in front of Server then expand the icon > in front of Login/Group Roles.
Now select postgres user from Login/Group Roles, right-click on that and click on option Properties.
After clicking on Properties, a Login Role-postgres dialog appears, click on the Definition tab and enter the password then click on the Save button at the bottom right corner.
After clicking on Save, we have successfully changed the password of a user named postgres. Now, close the pgAdmin application, and log in again with the new password.
You may also like some of our latest articles on PostgreSQL.
- PostgreSQL WHERE IN
- Postgres date range
- Postgresql if else
- PostgreSQL CASE
- Postgresql create user with password
- PostgreSQL DATE Format
- PostgreSQL ADD COLUMN
- PostgreSQL vs SQL Server
- Postgres RegEx
- Postgresql date between two dates
- Postgresql create database
So in this tutorial, we have learned about “Postgresql set user password” and changed the password of existing users. We have covered the following topics.
- How to set user password windows in PostgreSQL
- Set user password ubuntu in PostgreSQL
- How to change user password pgadmin in PostgreSQL
I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.
Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.