Как изменить пароль суперпользователя postgres

How do I change the password for a PostgreSQL user?

How do I change the password for a PostgreSQL user?

Peter Mortensen's user avatar

asked Oct 4, 2012 at 5:45

Saad's user avatar

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's user avatar

rmtheis

5,80712 gold badges60 silver badges77 bronze badges

answered Oct 4, 2012 at 5:55

solaimuruganv's user avatar

solaimuruganvsolaimuruganv

25.8k1 gold badge18 silver badges23 bronze badges

22

To change the PostgreSQL user’s password, follow these steps:

  1. log in into the psql console:

    sudo -u postgres psql
    
  2. 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

Peter Mortensen's user avatar

answered Oct 4, 2012 at 5:50

Clint Bugs's user avatar

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';

Peter Mortensen's user avatar

answered Feb 21, 2015 at 8:58

yglodt's user avatar

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's user avatar

xlm

6,40414 gold badges54 silver badges54 bronze badges

answered Aug 30, 2017 at 16:55

Viktor Nordling's user avatar

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>';"

Peter Mortensen's user avatar

answered May 25, 2015 at 23:14

Vajira Lasantha's user avatar

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.

Peter Mortensen's user avatar

answered Jun 29, 2019 at 19:09

Akitha_MJ's user avatar

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.

Peter Mortensen's user avatar

answered Oct 9, 2014 at 14:03

Murtaza Kanchwala's user avatar

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

Peter Mortensen's user avatar

answered Oct 30, 2021 at 10:05

CHAVDA MEET's user avatar

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

lcnicolau's user avatar

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 Dali's user avatar

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.

Peter Mortensen's user avatar

answered Jun 13, 2020 at 19:27

Timothy Macharia's user avatar

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.

Peter Mortensen's user avatar

answered Jan 11, 2014 at 20:39

ruruskyi's user avatar

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 to postgres

  • 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 your pg_hba.conf (mine is at /etc/postgresql/10/main/pg_hba.conf) by making sure you have the following line

    local all postgres md5

  • Restart your 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.

Peter Mortensen's user avatar

answered Mar 25, 2018 at 19:47

haxpor's user avatar

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';

Peter Mortensen's user avatar

answered Feb 12, 2018 at 11:52

Chris Dare's user avatar

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.

Peter Mortensen's user avatar

answered Jun 1, 2020 at 18:28

FlyingV's user avatar

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.

  1. If you do not have SSL and are modifying remotely you are transmitting the plain text password across the network.
  2. If you have your logging configuration set to log DDL statements log_statement = ddl or higher, then your plain text password will show up in your error logs.
  3. If you are not protecting these logs, it’s a problem.
  4. If you collect these logs/ETL them and display them where others have access, they could end up seeing this password, etc.
  5. 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 like

    ALTER 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

Peter Mortensen's user avatar

answered Aug 20, 2019 at 19:52

jkdba's user avatar

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 ;
 "

Peter Mortensen's user avatar

answered Oct 20, 2019 at 8:35

Yordan Georgiev's user avatar

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>';

Peter Mortensen's user avatar

answered Oct 30, 2021 at 10:34

rams zipppp's user avatar

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:

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

answered Mar 5, 2021 at 13:46

Andreas Covidiot's user avatar

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

Peter Mortensen's user avatar

answered Oct 2, 2020 at 17:30

Sufyan Elahi's user avatar

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.

Peter Mortensen's user avatar

answered Nov 1, 2019 at 17:41

99Sono's user avatar

99Sono99Sono

3,50427 silver badges38 bronze badges

Using pgAdmin 4:

Menu ObjectChange password…

Peter Mortensen's user avatar

answered Sep 8, 2022 at 12:59

Jhonnatan Panoch's user avatar

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 entering postgresql@, so you could try that or look for the PostgreSQL services in the list of all services (systemctl -a). Once you have the status output, look for the second command line after CGroup, which should be rather long, and start with /usr/lib/postgresql/13/bin/postgres or similar (depending on version, distro, and installation method). You are looking for the directory after -D, for example /var/lib/postgresql/13/main.
  • Add the following line: host all all 127.0.0.1/32 trust. This allows for all users on all databases to connect to the database via IPv4 on the local machine unconditionally, without asking for a password.

    This is a temporary fix and don’t forget to remove this line again later on. Just to be sure, I commented out the host all all 127.0.0.1/32 md5 (md5 may be replaced by scram-sha-256), which is valid for the same login data, just requiring a password.

  • Restart the database service: systemctl restart postgresql@... Again, use the exact service you found earlier.

  • Check that the service started properly with systemctl status postgresql@....

  • Connect with psql, and very importantly, force psql to not ask for a password. In my experience, it will ask you for a password even though the server doesn’t care, and will still reject your login if your password was wrong. This can be accomplished with the -w flag.

    The full command line looks something like this: sudo -u postgres psql -w -h 127.0.0.1 -p 5432. Here, postgres is your user and you may have changed that. 5432 is the port of the cluster-specific server and may be higher if you are running more than one cluster (I have 5434 for example).

  • Change the password with the password special command.

  • Remember to remove the password ignore workaround and restart the server to apply the configuration.

Peter Mortensen's user avatar

answered Apr 13, 2021 at 9:05

kleines Filmröllchen's user avatar

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).

Peter Mortensen's user avatar

asked Jun 1, 2012 at 7:14

hilarl's user avatar

1

  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/

  2. Back it up

    cp pg_hba.conf pg_hba.conf-backup

  3. 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

  4. 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

  5. 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)

  6. 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';

  7. Restore the old pg_hba.conf file as it is very dangerous to keep around

    cp pg_hba.conf-backup pg_hba.conf

  8. 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)

Peter Mortensen's user avatar

answered Jun 1, 2012 at 7:42

Arsen7's user avatar

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=#

Peter Mortensen's user avatar

answered Feb 2, 2014 at 10:21

SaeX's user avatar

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 FileChange Password.

Peter Mortensen's user avatar

answered Sep 19, 2014 at 22:26

SaiyanGirl's user avatar

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 Wailes's user avatar

Nathan WailesNathan Wailes

8,9806 gold badges52 silver badges90 bronze badges

0

  1. Edit the file /etc/postgresql/<version>/main/pg_hba.conf and find the following line:

    local  all  postgres  md5
    
  2. Edit the line and change md5 at the end to trust and save the file

  3. Reload the postgresql service

    sudo service postgresql reload
    
  4. This will load the configuration files. Now you can modify the postgres user by logging into the psql shell

    psql -U postgres
    
  5. Update the postgres user’s password

    alter user postgres with password 'secure-passwd-here';
    
  6. Edit the file /etc/postgresql/<version>/main/pg_hba.conf and change trust back to md5 and save the file

  7. Reload the postgresql service

    sudo service postgresql reload
    
  8. Verify that the password change is working

    psql -U postgres -W
    

Peter Mortensen's user avatar

answered Aug 17, 2017 at 2:55

Ray Hunter's user avatar

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?

  1. 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.

  2. 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)

  3. Open the pg_hba.conf file (not the backup, but the original)

  4. 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
    
  5. 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
    
  6. Close this file

  7. Go to your search bar on windows and open Services app. Find postgres and restart it.

    Picture of services app

  8. Write cd.. in cmd and then cd bin. Your path should be C:Program FilesPostgreSQL12bin

  9. Enter: psql -U postgres -h localhost

  10. 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

  11. Open original pg_hba.conf file and change back from trust to md5

  12. Restart the server with Services app as before

Peter Mortensen's user avatar

answered Nov 15, 2020 at 22:14

Vito Farina's user avatar

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.

Peter Mortensen's user avatar

answered Mar 12, 2018 at 12:58

Daniel's user avatar

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.

Peter Mortensen's user avatar

answered Feb 3, 2019 at 13:40

Bidhan Majhi's user avatar

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.

Peter Mortensen's user avatar

answered Mar 21, 2017 at 15:31

cpunky's user avatar

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.

Peter Mortensen's user avatar

answered Nov 14, 2017 at 12:08

Taufiq Rahman's user avatar

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

Sostene MUNEZERO BAGIRA's user avatar

answered Mar 16, 2020 at 15:22

David's user avatar

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.

Peter Mortensen's user avatar

answered Jun 7, 2016 at 16:36

ivofernandes's user avatar

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.

Peter Mortensen's user avatar

answered Jun 27, 2022 at 11:12

Francis C.j Francis's user avatar

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.

Peter Mortensen's user avatar

answered Nov 23, 2022 at 15:31

Barabas's user avatar

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.

Peter Mortensen's user avatar

answered Feb 26, 2021 at 10:47

Suresh S Y's user avatar

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).

Peter Mortensen's user avatar

asked Jun 1, 2012 at 7:14

hilarl's user avatar

1

  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/

  2. Back it up

    cp pg_hba.conf pg_hba.conf-backup

  3. 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

  4. 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

  5. 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)

  6. 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';

  7. Restore the old pg_hba.conf file as it is very dangerous to keep around

    cp pg_hba.conf-backup pg_hba.conf

  8. 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)

Peter Mortensen's user avatar

answered Jun 1, 2012 at 7:42

Arsen7's user avatar

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=#

Peter Mortensen's user avatar

answered Feb 2, 2014 at 10:21

SaeX's user avatar

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 FileChange Password.

Peter Mortensen's user avatar

answered Sep 19, 2014 at 22:26

SaiyanGirl's user avatar

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 Wailes's user avatar

Nathan WailesNathan Wailes

8,9806 gold badges52 silver badges90 bronze badges

0

  1. Edit the file /etc/postgresql/<version>/main/pg_hba.conf and find the following line:

    local  all  postgres  md5
    
  2. Edit the line and change md5 at the end to trust and save the file

  3. Reload the postgresql service

    sudo service postgresql reload
    
  4. This will load the configuration files. Now you can modify the postgres user by logging into the psql shell

    psql -U postgres
    
  5. Update the postgres user’s password

    alter user postgres with password 'secure-passwd-here';
    
  6. Edit the file /etc/postgresql/<version>/main/pg_hba.conf and change trust back to md5 and save the file

  7. Reload the postgresql service

    sudo service postgresql reload
    
  8. Verify that the password change is working

    psql -U postgres -W
    

Peter Mortensen's user avatar

answered Aug 17, 2017 at 2:55

Ray Hunter's user avatar

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?

  1. 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.

  2. 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)

  3. Open the pg_hba.conf file (not the backup, but the original)

  4. 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
    
  5. 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
    
  6. Close this file

  7. Go to your search bar on windows and open Services app. Find postgres and restart it.

    Picture of services app

  8. Write cd.. in cmd and then cd bin. Your path should be C:Program FilesPostgreSQL12bin

  9. Enter: psql -U postgres -h localhost

  10. 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

  11. Open original pg_hba.conf file and change back from trust to md5

  12. Restart the server with Services app as before

Peter Mortensen's user avatar

answered Nov 15, 2020 at 22:14

Vito Farina's user avatar

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.

Peter Mortensen's user avatar

answered Mar 12, 2018 at 12:58

Daniel's user avatar

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.

Peter Mortensen's user avatar

answered Feb 3, 2019 at 13:40

Bidhan Majhi's user avatar

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.

Peter Mortensen's user avatar

answered Mar 21, 2017 at 15:31

cpunky's user avatar

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.

Peter Mortensen's user avatar

answered Nov 14, 2017 at 12:08

Taufiq Rahman's user avatar

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

Sostene MUNEZERO BAGIRA's user avatar

answered Mar 16, 2020 at 15:22

David's user avatar

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.

Peter Mortensen's user avatar

answered Jun 7, 2016 at 16:36

ivofernandes's user avatar

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.

Peter Mortensen's user avatar

answered Jun 27, 2022 at 11:12

Francis C.j Francis's user avatar

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.

Peter Mortensen's user avatar

answered Nov 23, 2022 at 15:31

Barabas's user avatar

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.

Peter Mortensen's user avatar

answered Feb 26, 2021 at 10:47

Suresh S Y's user avatar

На чтение 5 мин Просмотров 10.6к. Опубликовано 17.12.2021

Это необходимо для защиты ваших данных и информации от любых вторжений, которые могут быть выполнены с помощью паролей для ваших пользователей. Пароли используются для защиты ваших данных от любых неудач в будущем, чтобы ни один другой пользователь, кроме вас, не мог войти в систему. Они необходимы, когда вы вошли в систему или вошли в определенную систему для целей аутентификации.

В PostgreSQL, когда вы однажды установили программу установки, она попросит вас установить пароль для базы данных по умолчанию, то есть «postgres». Вы также можете позже создать собственного пользователя в PostgreSQL и установить для него пароль. Но что, если возникает необходимость изменить пароль для управления базой данных или административных функций, и в вашей голове возникает вопрос, как и откуда вы можете изменить пароль? Не о чем беспокоиться, потому что эта статья будет специально посвящена ответу на ваш вопрос с помощью простых и различных способов изменения паролей пользователей в PostgreSQL. Это руководство поможет вам изменить пароли пользователей и четко определить каждый шаг для вашего лучшего понимания.

Различные режимы изменения пароля пользователя:

Вы можете изменить пароли пользователей двумя разными способами в PostgreSQL. В обоих методах вы можете создать и установить пароль, а также изменить его. Вот эти два метода:

  • Используя pgAdmin.
  • Используя psql.

Содержание

  1. Шаги по изменению пароля с помощью pgAdmin
  2. Изменить пароль через psql
  3. Измените пароль с помощью операторов ALTER ROLE
  4. Измените пароль с помощью мета-команды
  5. Вывод

Шаги по изменению пароля с помощью pgAdmin

Когда вы открываете PostgreSQL, перед вами отображается примерно следующее:

вы открываете PostgreSQL, перед вами отображается

С левой стороны можно увидеть меню навигации, в котором определены «Логин / Групповые роли». При нажатии на нее появляется выпадающий список.

левой стороны можно увидеть меню навигации, в котором определены

В этом списке хранятся все имена пользователей, которые существуют в базе данных, вместе с их определенными и привилегированными ролями.

Давайте сначала создадим имя пользователя и установим пароль для этого имени пользователя, а затем мы изменим пароль. Чтобы создать имя пользователя, нажмите «Логин / Роли группы» и нажмите «Создать» логин или групповую роль. Здесь мы создадим роль входа в базу данных с желаемыми ролями.

Давайте сначала создадим имя пользователя и установим пароль

После нажатия на «Логин / Групповые роли» появится следующее:

После нажатия на «Логин 

В поле имени вы можете указать любое имя, какое захотите. Затем нажмите «Определения» и введите пароль для своего имени пользователя.

В поле имени вы можете указать любое имя, какое захотите

В «Привилегиях» определите свои роли пользователей и в конце сохраните данные для входа в систему.

«Привилегиях» определите свои роли пользователей и

Теперь вы создали пользователя и можете просто изменить пароль, щелкнув свое имя пользователя, а затем «Свойства» на боковой панели навигации следующим образом:

Теперь вы создали пользователя и можете просто изменить пароль

В окне «Свойства» откроется тот же экран, на котором вы создали имя пользователя для входа в систему. Здесь в «Паролях» вы можете ввести свой новый пароль и сохранить его в конце.

В окне «Свойства» откроется тот же экран, на котором вы

В поле «Пароли» повторно введите новый пароль, и ваш пароль будет изменен на имя пользователя «saeed_raza».

Изменить пароль через psql

В оболочке SQL (psql) вы также можете изменить пароль двумя способами:

  • Использование операторов ALTER ROLE.
  • Использование мета-команд.

Измените пароль с помощью операторов ALTER ROLE

Операторы ALTER ROLE используются для изменения паролей пользователя в PostgreSQL. Вот основной синтаксис для использования операторов ALTER Role в вашей базе данных:

Операторы 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 вы должны ввести имя пользователя, пароль которого вы хотите изменить:

Во-первых, при запуске psql вы должны ввести имя пользователя, пароль

Я ввел имя пользователя saeed_raza, потому что хочу изменить пароль этого пользователя в PostgreSQL. Теперь следуйте этому простому синтаксису, который также изменит пароль пользователя или пароль по умолчанию PostgreSQL, просто используя метакоманду:

postgres=# password

Enter new password:

Enter it again:

Теперь пароль для пользователя saeed

Теперь пароль для пользователя saeed_raza изменен с помощью этой простой метакоманды.

Вывод

В этом руководстве мы узнали, как можно изменить пароль пользователя с помощью pgAdmin и psql, а также с различными способами psql. Все методы, которые мы использовали в этой статье, были эффективными и простыми, которые вы можете реализовать в своей системе, чтобы окончательно ответить на ваши вопросы о том, как изменить пароли пользователей в PostgreSQL.

Postgres Change Password

Introduction to Postgres Change Password

In this article, we will learn how we can change the Postgres Change Password of the user if present and if not how we can assign a password to the user for further authenticated usage by him in the PostgreSQL database server. There are two methods to do so. The first method involves using the ALTER query statement to change the password and the second method is to use the meta-command password in PostgreSQL’s psql utility.

To proceed with changing the password process, we first need to understand how password mechanism works in PostgreSQL and what password policy is set to the default superuser which is most often user named Postgres.

In any Unix distribution system of PostgreSQL, there are two types of authentication methods namely ident and peer. The default authentication method depends on which version of PostgreSQL does it use and how is PostgreSQL installed on your machine.

Ident Authentication method: In this method, TCP port with 113 as port number authenticates the user’s credentials where the identification server of the operating system is running.

Peer Authentication Method: In the peer authentication method, the current user’s password of PostgreSQL is matched with the password of the operating system user’s password.

Syntax

Format 1:

ALTER USER name [ [ WITH ] option [ ... ] ] where option can be:
CREATEDB | NOCREATEDB
| CREATEUSER | NOCREATEUSER
| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'newPassword'
| VALID UNTIL 'expirytime'

Explanation: Using the above alter command the password of the user can be changed and along with that other options can also be reassigned.

Name: It is the name of the user or role whose properties or password you want to change.

Option: We can change multiple parameters and privileges associated with the user using this format.

CREATEDB: This can be specified if you want to give the privilege to the user to create a new database

NOCREATEDB: This can be mentioned if you want to restrict the user from creating any new database.

CREATEUSER: This property can be specified to allow the user to create new users.

NOCREATEUSER: When this property is mentioned in the query in the above format the user won’t be able to create new users.

ENCRYPTED: This property determines whether the password stored in the pg_catalog’s pg_shadow table is stored in the form of an MD5 encrypted format.

UNENCRYPTED: The password is not stored in encrypted format in pg_catalog. If neither ENCRYPTED or UNENCRYPTED property is specified and neither this is done while user creation then the default password storing mechanism is decided based on password_encryption configuration variable.

PASSWORD: The new password is the string that you want to set as the password for the user. If this field is not specified and the user doesn’t have any previously set password to it then no authentication will be done for the user and the user can log in to the system without mentioning the password. But in case if you switch to a password authentication system then the user won’t be able to log in.

VALID UNTIL expiry time: This field can be used if you want to allow the set password up to some specific period. This field if the timestamp up to which you want to permit the assigned password to work.

Examples to Implement Postgres Change Password

Below are examples mentioned:

Example #1

We will firstly login to the system by Postgres default user. Here we have assigned a password to the Postgres role already. So, we will enter the password.

Code:

sudo su - postgres

Output:

Postgres Change Password1

Example #2

Further, let us check all the users which are present in the database server by firing the command using psql promo:

Code:

select username from pg_catalog.pg_user;

Output:

Postgres Change Password2

Example #3

Let us try to login using a user:

Code:

sudo su – a;

Output:

Postgres Change Password3

Example #4

As we have forgotten the password associated to that user assigned to it while its creation, we will reset it to pay by using the format 1 ALTER USER query in the following way:

Code:

ALTER USER a WITH ENCRYPTED PASSWORD 'payal';

Output:

Postgres Change Password4

As the output is ALTER ROLE. The password has been reset successfully.

Format 2:

ALTER USER name RENAME TO alteredName

This format is only used to alter the name of the user to some other name “alteredName”.

Example #5

Code:

ALTER USER a RENAME TO payal;

Output:

Postgres Change Password5

Example #6

Let us verify the available users in our database server now.

Code:

SELECT usename FROM pg_catalog.pg_user;

Output:

verify the available users

Example #7

Code:

ALTER USER name SET parameter { TO | = } { targetValue | DEFAULT }

the parameter can be any configuration property of PostgreSQL. You can see all the configuration properties by firing the command

SHOW ALL;

Output:

configuration property of PostgreSQL

Example #8

ALTER USER name RESET parameter

This command is used to reset the value of any field related to the user. Example –

Now, in case if we want to reset the password of the payal user. we can do so by using the query statement :

Code:

ALTER USER payal RESET password;

Output:

reset the password

That gives the output “ALTER ROLE” which means that password for payal user has been reset successfully.

Example #9

MetaCommand to change password: In PostgreSQL, we have this amazing functionality called meta-commands that can be used with the help of psql utility. MetaCommands are short commands which are provided to make the working

of database administrator easy and efficient. These metacommands internally fire the SQL commands which are basic like ALTER, CREATE, SELECT, etc. One such meta-command for changing the password of the user is available and named password. It asks to enter the password and then reenter the password for confirmation and then sets the entered password for that user.

password

Let us check the working of metacommand with the help of an example. Suppose we want to change the password of Postgres user after login to the Postgres database. Then we will query for the same in the following steps:

Code:

psql -d postgres -U postgres
password

Output:

working of metacommand

Conclusion

We can change the password of the user either by using the ALTER command or metacommand password in PostgreSQL.

Recommended Articles

This is a guide to Postgres Change Password. Here we discuss an introduction to Postgres Change Password, syntax, examples with code and output. You can also go through our other related articles to learn more –

  1. PostgreSQL Database
  2. PostgreSQL Trunc()
  3. PostgreSQL cluster
  4. PostgreSQL Functions

Are you trying to change the password of PostgreSQL? We can help you with it.

Here at Bobcares, we have seen several such PostgreSQL related queries as part of our Server Management Services for web hosts and online service providers.

Today we’ll take a look at the process of changing the PostgreSQL password.

A few facts about PostgreSQL

PostgreSQL is one of the most popular free and open-source relational database management systems.

It is mainly used as the primary data store or data warehouse for many webs, mobile, geospatial, and analytics applications.

Moreover, it supports many leading programming languages that include Python, Java, Perl, .Net, C/C++, and so on.

How we change the password of PostgreSQL

Here are the steps our Support Engineers provide to our customers to change the password.

Note: Make sure that you have root access to the server.

1. First, switch to PostgreSQL user – postgres

In case, if you are working using a default PostgreSQL installation, then PostgreSQL will be configured with the default user postgres.

Since we logged in as a root user, we assume that the root doesn’t have a user for PostgreSQL. So we switch to PostgreSQL user by running the below command.

$ su – postgres

Then we connect to the PostgreSQL by running the below command.

$ psql

You will be asked for a password now. Enter it.

2. Add/Change the PostgreSQL password

Here is the command we use to change the password of the current user.

password

Now enter the new password and hit enter again to confirm it as shown below.

Enter new password:
Enter it again:

After changing the password, you can quit it by entering

q

You can also do all the steps in a single command as below.

$ su -c “psql” – postgres

Also, the password of the PostgreSQL can be changed using the ALTER ROLE statement as below.

ALTER ROLE username
WITH PASSWORD ‘password’;

In the above statement, first, specify the username of which you want to change the password. Next, provide the new password within a single quote. For example, the following statement changes the password of the superuser to secret12345.

ALTER ROLE super WITH PASSWORD ‘secret12345’;

In some cases, you would wish to keep the password valid until a certain date and time. In such cases, you can use VALID UNTIL clause:

ALTER ROLE username
WITH PASSWORD ‘new_password’
VALID UNTIL timestamp;

Note: If you omit the VALID UNTIL clause, then the password will be valid forever.

The following statement sets the expiration date for the password of the superuser to December 31, 2020:

ALTER ROLE super
VALID UNTIL ‘December 31, 2020’;

[Need any further assistance with PostgreSQL queries? – We are here to help you.]

Conclusion

Today, we saw how our Support Engineers change the password of PostgreSQL using different methods.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить пароль суперпользователя debian
  • Как изменить пароль стим через телефон
  • Как изменить пароль стим не имея доступа к почте
  • Как изменить пароль стеам
  • Как изменить пароль скайпа на компьютере

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии