pgAdmin:Password authentication failed [duplicate] - postgresql

I have installed PostgreSQL 8.4, Postgres client and Pgadmin 3. Authentication failed for user "postgres" for both console client and Pgadmin. I have typed user as "postgres" and password "postgres", because it worked before. But now authentication is failed. I did it before a couple of times without this problem. What should I do? And what happens?
psql -U postgres -h localhost -W
Password for user postgres:
psql: FATAL: password authentication failed for user "postgres"
FATAL: password authentication failed for user "postgres"

If I remember correctly the user postgres has no DB password set on Ubuntu by default. That means, that you can login to that account only by using the postgres OS user account.
Assuming, that you have root access on the box you can do:
sudo -u postgres psql
If that fails with a database "postgres" does not exists error, then you are most likely not on a Ubuntu or Debian server :-) In this case simply add template1 to the command:
sudo -u postgres psql template1
If any of those commands fail with an error psql: FATAL: password authentication failed for user "postgres" then check the file /etc/postgresql/8.4/main/pg_hba.conf: There must be a line like this as the first non-comment line:
local all postgres ident
For newer versions of PostgreSQL ident actually might be peer. That's OK also.
Inside the psql shell you can give the DB user postgres a password:
ALTER USER postgres PASSWORD 'newPassword';
You can leave the psql shell by typing CtrlD or with the command \q.
Now you should be able to give pgAdmin a valid password for the DB superuser and it will be happy too. :-)

The response of staff is correct, but if you want to further automate can do:
$ sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'postgres';"
Done! You saved User = postgres and password = postgres.
If you do not have a password for the User postgres ubuntu do:
$ sudo passwd postgres

This was frustrating, most of the above answers are correct but they fail to mention you have to restart the database service before the changes in the pg_hba.conf file will take affect.
so if you make the changes as mentioned above:
local all postgres ident
then restart as root ( on centos its something like service service postgresql-9.2 restart )
now you should be able to access the db as the user postgres
$psql
psql (9.2.4)
Type "help" for help.
postgres=#
Hope this adds info for new postgres users

Edit the pg_hba.conf file, for Debian on /etc/postgresql/9.3/main/pg_hba.conf and for Red Hat/IBM derivates at /var/lib/pgsql/9.4/data/pg_hba.conf
Change all authentication methods to trust.
Change Linux Password for postgres user.
Restart Server.
Login with psql -h localhost -U postgres and use the just set Unix password.
If it works you should re-set the pg_hba.conf file to values with md5 or ident methods and restart.

For those who are using it first time and have no information regarding what the password is they can follow the below steps(assuming you are on ubuntu):
Open the file pg_hba.conf in /etc/postgresql/9.x/main
sudo vi pg_hba.conf
2.edit the below line
local all postgres peer
to
local all postgres trust
Restart the server
sudo service postgresql restart
Finally you can login without need of a password as shown in the figure
Ref here for more info

When you install postgresql no password is set for user postgres, you have to explicitly set it on Unix by using the command:
sudo passwd postgres
It will ask your sudo password and then promt you for new postgres user password.
Source

Try to not use the -W parameter and leave the password in blank. Sometimes the user is created with no-password.
If that doesn't work reset the password. There are several ways to do it, but this works on many systems:
$ su root
$ su postgres
$ psql -h localhost
> ALTER USER postgres with password 'YourNewPassword';

As a rule of thumb: YOU SHOULD NEVER EVER SET A PASSWORD FOR THE POSTGRES USER.
If you need a superuser access from pgAdmin, make another superuser. That way, if the credentials for that superuser is compromised, you can always ssh into the actual database host and manually delete the superuser using
sudo -u postgres -c "DROP ROLE superuser;"

Once you are in your postgres shell, Enter this command
postgres=# \password postgres
After entering this command you will be prompted to set your password , just set the password and then try.

If you are trying to login postgres shell as postgres user, then you can use following commands.
switch to postgres user
# su - postgres
login to psql
# psql
Hope that helps

Ancient thread, but I wasted half a day dealing with this in 2020, so this might help someone: Double-check your postgres port (on Ubuntu, it's in /etc/postgresql/9.5/main/postgresql.conf). The psql client defaults to using port 5432, BUT in my case, the server was running on port 5433. The solution was to specify the -p option in psql (e.g. psql --host=localhost --username=user -p 5433 mydatabase).
If you leave off the --host parameter, psql will connect via a socket, which worked in my case, but my Golang app (which uses TCP/IP) did not. Unfortunately, the error message was password authentication failed for user "user", which was misleading. The fix was to use a url connection string with the port (e.g. postgres://user:password#localhost:5433/mydatabase).
My setup was Ubuntu 18.04 on Digital Ocean, with postgres 9.5 installed via apt-get, so not sure why this happened. Hope this saves you some time.

I faced the same error on Windows 10. In my case, when I setup the Postgres, my username was postgres by default.
But when I ran the command psql, it as showing my the username as jitender which is my machine name, and I don't know why this username had been setup.
Anyway to solved it, I did the following steps:
Run the command psql --help
In the output, look for the Connection Option, here you will see your default user, in my case it as jitender.
You will also get the command to set the anoter username, which should be psql --username postgres. You set the username whatever you require, and that's all, problem got solved.

If you see error
FATAL: password authentication failed for user "postgres"
and you are sure that your password is correct, check that the password has any special characters, especially "%" or slashes.
In my case, it was "%" in the password string. After removing this symbol, everything works fine.

Here are some combinations which I tried to login:
# login via user foo
psql -Ufoo -h localhost
sudo -u postgres psql postgres
# user foo login to postgres db
psql -Ufoo -h localhost -d postgres

Time flies!
On version 12, I have to use "password" instead of "ident" here:
local all postgres password
Connect without using the -h option.

First of All password crate
ALTER USER postgres with encrypted password 'postgres';
then service restart:
sudo systemctl restart postgresql.service
End.

Follow these steps :
sudo -u postgres -i
psql
\password postgres
After that, enter your password twice.
Then use that password in the pgAdmin4.

I was also faced this issue while login the postgres. I was followed the below steps and able to login with postgres and pgadmin.
Step1: Open Postgres using terminal.
sudo su postgres
Step2: Open psql.
psql
Step3: Reset the password of user
ALTER USER user_name WITH PASSWORD 'new_password';
Step4: Give the permission on database to user.
GRANT ALL PRIVILEGES ON DATABASE my_database TO db_user;

I just wanted to add that you should also check if your password is expired.
See Postgres password authentication fails for details.

In my case, Ubuntu 20.04 Postgresql 12 was using the wrong port.
I've checked /etc/postgresql/12/main/postgresql.conf and realized it was 5433 instead of 5432.

The answer is #diego
I want to add some explanations of how I fixed error and I hope it will help other folks:
ERROR: password authentication failed for user "postgres"
On Window
Make sure you download Postgres software, install it, create and confirm password
and make sure its not complicated with some symbols and characters.
Open window, click SQL Shell (PSQL) and access it and create database
Create connection string like
postgres://postgres:your_password#localhost:port/your_database
On WSL
Follow Microsoft documentation
After successful installation
// Open postgres
su postgres
// Type psql and hit enter
psql
// Create a user postgres if not exist or any other user you want
CREATE USER your_user_db WITH PASSWORD 'match_password_with_db_password';
// Give user password same as the one you set up for postgres db
ALTER USER your_user_db WITH PASSWORD 'match_password_with_db_password';
// Restart the server
sudo service postgresql restart

i had a similar problem.
Ubuntu was left me log in in console with any password for superuser.
Except when i connected with -h localhost in psql line command.
I Observed too that "localhost:8080/MyJSPSiteLogIn" - showed: Fatal: autentication error with user "user".
pg_hba.conf was ok.
I noted had two versions of postgres running in the same service.
Solved - uninstalling inutil version.

I had faced similar issue.
While accessing any database I was getting below prompt after updating password
"password authentication failed for user “postgres”" in PGAdmin
Solution:
Shut down postgres server
Re-run pgadmin
pgadmin will ask for password.
Please enter current password of mentioned user
Hope it will resolve your issue

This happens due to caching.
When you run, php artisan config:cache, it will cache the configuration files. Whenever things get change, you need to keep running it to update the cache files. But, it won't cache if you never run that command.
This is OK for production, since config don't change that often. But during staging or dev, you can just disable caching by clearing the cache and don't run the cache command
So, just run php artisan config:clear, and don't run the command previously to avoid caching.
Check original post
Password authentication failed error on running laravel migration

In my case, its Password was longer than 100 characters. Setting it to a smaller character password worked.
Actually I am wondering is there a reference somewhere to that.

Please remember if you have two versions of Postgres installed you need to Uninstall one of them, in my case on MacOS I had one version installed via .dmg and one via brew.
What worked for me was to uninstall the one installed via .dmg using the following steps
Go to /Library/PostgreSQL/13.
Open uninstall-postgres.app.
then try
psql postgres
it should work.

Answer given is almost correct just missing some pointers which i'll be taking care of in my solution
First make sure your user have a sudo access if not you can use the below command to add your user as sudo user :-
sudo adduser <username> sudo
The change will take effect the next time the user logs in.
i) Now go to sudo vim /etc/postgresql/<your_postgres_version>/main/pg_hba.conf file and look for line that says :
local all postgres md5 #peer
and comment that. Just below that line there must be a commented line that says:
local all postgres peer
or for older versions it'll be :-
local all postgres ident
Uncomment that line.
ii) Now restart the postgres by using any of these commands :-
sudo /etc/init.d/postgresql restart
OR
sudo service postgresql restart
iii) Now you can simply log into postgres using the following command :
sudo -u postgres psql
iv) once you're in you can create any operation you want to in my case i wanted to create a new database you can do the same using below command :
CREATE DATABASE airflow_replica;

In my case it was so simple! I was taken error in application JAVA Spring because I needed remember the Database Superuser, it is showed during the install process PostgreSQL, in my case the datasource would be postgres. So, I added correctly the name and it works!

Open pg_hba.conf in any text editor (you can find this file in your postgres instalation folder);
Change all the methods fields to trust (meaning you don't need a password for postgre);
Run in your console this comand:
"alter user postgres with password '[my password]';" | psql -U postgres
(meaning to alter some user password for [my password] for the user as parameter -U postgres)
Et voilà (don't forget to change back the method from trust for the one that should be best for you)
I hope this help someone someday.

I hope this will help you short of time.
You can change the password of postgres sql by using bellow command.
Command
sudo -u postgres psql
And next you can update the password
Command
Alter user postgres password 'YOUR_NEW_PASSWORD';

Related

FATAL: role "user" does not exist [duplicate]

I'm setting up my PostgreSQL 9.1. I can't do anything with PostgreSQL: can't createdb, can't createuser; all operations return the error message
Fatal: role h9uest does not exist
h9uest is my account name, and I sudo apt-get install PostgreSQL 9.1 under this account.
Similar error persists for the root account.
Use the operating system user postgres to create your database - as long as you haven't set up a database role with the necessary privileges that corresponds to your operating system user of the same name (h9uest in your case):
sudo -u postgres -i
As recommended here or here.
Then try again. Type exit when done with operating as system user postgres.
Or execute the single command createuser as postgres with sudo, like demonstrated by drees in another answer.
The point is to use the operating system user matching the database role of the same name to be granted access via ident authentication. postgres is the default operating system user to have initialized the database cluster. The manual:
In order to bootstrap the database system, a freshly initialized
system always contains one predefined role. This role is always a
“superuser”, and by default (unless altered when running initdb) it
will have the same name as the operating system user that initialized
the database cluster. Customarily, this role will be named postgres.
In order to create more roles you first have to connect as this
initial role.
I have heard of odd setups with non-standard user names or where the operating system user does not exist. You'd need to adapt your strategy there.
Read about database roles and client authentication in the manual.
After trying many other people's solutions, and without success, this answer finally helped me.
https://stackoverflow.com/a/16974197/2433309
In short, running
sudo -u postgres createuser owning_user
creates a role with name owning_user (in this case, h9uest). After that you can run rake db:create from the terminal under whatever account name you set up without having to enter into the Postgres environment.
sudo su - postgres
psql template1
creating role on pgsql with privilege as "superuser"
CREATE ROLE username superuser;
eg. CREATE ROLE demo superuser;
Then create user
CREATE USER username;
eg. CREATE USER demo;
Assign privilege to user
GRANT ROOT TO username;
And then enable login that user, so you can run e.g.: psql template1, from normal $ terminal:
ALTER ROLE username WITH LOGIN;
This works for me:
psql -h localhost -U postgres
Installing postgres using apt-get does not create a user role or a database.
To create a superuser role and a database for your personal user account:
sudo -u postgres createuser -s $(whoami); createdb $(whoami)
psql postgres
postgres=# CREATE ROLE username superuser;
postgres=# ALTER ROLE username WITH LOGIN;
For version Postgres 9.5 use following comand:
psql -h localhost -U postgres
Hope this will help.
Working method,
vi /etc/postgresql/9.3/main/pg_hba.conf
local all postgres peer
here change peer to trust
restart, sudo service postgresql restart
now try, psql -U postgres
For Windows users : psql -U postgres
You should see then the command-line interface to PostgreSQL: postgres=#
I did a healthcheck with docker-compose.
healthcheck:
test: ['CMD-SHELL', 'pg_isready']
interval: 5s
timeout: 5s
retries: 5
If you also have that change the user:
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U postgres'] # <<<---
interval: 5s
timeout: 5s
retries: 5
In local user prompt, not root user prompt, type
sudo -u postgres createuser <local username>
Then enter password for local user.
Then enter the previous command that generated "role 'username' does not exist."
Above steps solved the problem for me.
If not, please send terminal messages for above steps.
I installed it on macOS and had to:
cd /Applications/Postgres.app/Contents/Versions/9.5/bin
createuser -U postgres -s YOURUSERNAME
createdb YOURUSERNAME
Here's the source: https://github.com/PostgresApp/PostgresApp/issues/313#issuecomment-192461641
Manually creating a DB cluster solved it in my case.
For some reason, when I installed postgres, the "initial DB" wasn't created. Executing initdb did the trick for me.
This solution is provided in the PostgreSQL Wiki - First steps:
initdb
Typically installing postgres to your OS creates an "initial DB" and starts the postgres server daemon running. If not then you'll need to run initdb
dump and restore with --no-owner --no-privileges flags
e.g.
dump - pg_dump --no-owner --no-privileges --format=c --dbname=postgres://userpass:username#postgres:5432/schemaname > /tmp/full.dump
restore - pg_restore --no-owner --no-privileges --format=c --dbname=postgres://userpass:username#postgres:5432/schemaname /tmp/full.dump
sudo -u postgres createuser --superuser $USER
sudo -u postgres createdb $USER
This should definitely work for you.
for those who using docker and correctly followed the instructions from official doc, if you still met this problem, RESTART windows and try again.
Follow These Steps and it Will Work For You :
run msfconsole
type db_console
some information will be shown to you chose the information who tell you to make: db_connect user:pass#host:port.../database sorry I don't remember it but it's like this one then replace the user and the password and the host and the database with the information included in the database.yml in the emplacement: /usr/share/metasploit-framework/config
you will see. rebuilding the model cache in the background.
Type apt-get update && apt-get upgrade after the update restart the terminal and lunch msfconsole and it works you can check that by typing in msfconsole: msf>db_status you will see that it's connected.
Follow these steps to get postgres working.
In your terminal, locate the Application Support folder with the following command.
/Users/[name of the user]/library/application support
Delete the application, Postgres.
Reinstall the app and it should work just fine.
Something as simple as changing port from 5432 to 5433 worked for me.

Unable to execute postgres command

I'm having difficulty changing the password associated with the postgres user after installing postgres on my windows 10 machine. My apologies in advance as I'm quite unfamiliar with postgres as well as the commands required to work with it.
I've referenced the approved answer in the below article:
FATAL: password authentication failed for user "postgres" (postgresql 11 with pgAdmin 4)
I'm stuck on the step that requires me to
Connect using psql or pgAdmin4 or whatever you prefer
Run ALTER USER postgres PASSWORD 'fooBarEatsBarFoodBareFoot'
I don't quite understand this step. I've taken the following steps
Open cmd
run psql
The system then asks me for password for username jason. Regardless of what I enter, i get the following message:
psql: error: could not connect to server: FATAL: password authentication failed for user "jason"
At no point do I have an opportunity to enter the following command:
ALTER USER postgres PASSWORD 'fooBarEatsBarFoodBareFoot'
How can I run this command without being asked to enter a password for postgres?
Thanks!
The steps below require that you remember what you did when you installed PostgreSQL.
Locate the data directory where the installation process created the database cluster. By default, that would be a subdirectory of where you installed the software (which is a bad place)
Edit the pg_hba.conf file therein and add this line on top:
host postgres postgres 127.0.0.1/32 trust
Reload or restart PostgreSQL.
Start cmd.exe and enter
psql -h 127.0.0.1 -p 5432 -d postgres -U postgres
If psql is not on your PATH, use the absolute path C:\...\psql.
Use \password to change the password.

Change authentication method for postgres superuser

I am using psql to connect to a PostgreSQL database on Debian 10. I am trying to connect as the postgres user, to the default postgres database. By default, this is using the 'peer' authentication method, which does not require a password.
If I log in using the 'peer' authentication and set a password using the following command:
ALTER USER postgres WITH PASSWORD 'myPassword';
The query executes successfully, however when I edit pg_hba.conf to change the authentication method from:
local all postgres peer
to:
local all postgres scram-sha-256
and restart the server, I get the following error:
~$ sudo -u postgres psql postgres
Password for user postgres:
psql: FATAL: password authentication failed for user "postgres"
~$
Does anyone know how to do this?
To change the authentication method in PostgreSQL:
Open a terminal window
Change into the postgres bin directory
Example: cd /usr/local/pgsql/bin
Note: Depending on your install environment the path to the bin directory may vary.
Type su – postgres and press Enter. This will change the logged in to the postgres user.
From the bin directory type ./psql
Type:
ALTER USER your_username password 'new_password'; and press Enter. ALTER ROLE should be displayed.
Type \q and press Enter
Open /path_to_data_directory/pg_hba.conf
Example: /etc/postgresql/11/main/pg_hba.conf
Modify the line at the bottom of the config file to resemble one of these examples.
Note: You will probably only have to change the word trust to md5. The line or lines should already exist.
host all postgres peer
host all your_username your.ip your.subnet md5
Save the changes
Restart PostgreSQL service with systemctl restart postgresql.service
Before you assign the password, you probably need to set the password_encryption to "scram-sha-256". Otherwise, you stored the password in the md5 format, and such a password cannot be used to login when pg_hba.conf calls for "scram-sha-256".
The default setting of password_encryption is still md5. It will change to be "scram-sha-256" in v14.
The error message sent to the unauthenticated user is intentionally vague. The error message in the server log file will probably say DETAIL: User "postgres" does not have a valid SCRAM secret. (If it does not, then ignore this answer, and edit your question to tell us what it does say)
You need to 1st in the shell change to be the "postgres" user which you're not doing correctly above:
sudo su - postgres
Then you can do the following as peer auth:
psql -d postgres -U postgres
Also recommend you set a pw for postgres sql user:
\password postgres
& change the authentication method to "md5", not "peer".

How to connect Postgres to localhost server using pgAdmin on Ubuntu?

I installed Postgres with this command
sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
Using psql --version on terminal I get psql (PostgreSQL) 9.3.4
then I installed pgadmin with
sudo apt-get install pgadmin3
Later I opened the UI and create the server with this information
but this error appear
how can I fix it?
Modify password for role postgres:
sudo -u postgres psql postgres
alter user postgres with password 'postgres';
Now connect to pgadmin using username postgres and password postgres
Now you can create roles & databases using pgAdmin
How to change PostgreSQL user password?
You haven't created a user db. If its just a fresh install, the default user is postgres and the password should be blank. After you access it, you can create the users you need.
It helps me:
1. Open the file pg_hba.conf
sudo nano /etc/postgresql/9.x/main/pg_hba.conf
and 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 trust
Restart the server
sudo service postgresql restart
Login into psql and set password
psql -U postgres
ALTER USER postgres with password 'new password';
Again open the file pg_hba.conf and change this line:
Database administrative login by Unix domain socket
local all postgres trust
to
Database administrative login by Unix domain socket
local all postgres md5
Restart the server
sudo service postgresql restart
It works.
Helpful links
1: PostgreSQL (from ubuntu.com)
Create a user first. You must do this as user postgres. Because the postgres system account has no password assigned, you can either set a password first, or you go like this:
sudo /bin/bash
# you should be root now
su postgres
# you are postgres now
createuser --interactive
and the programm will prompt you.
First you should change the password using terminal.
(username is postgres)
postgres=# \password postgres
Then you will be prompted to enter the password and confirm it.
Now you will be able to connect using pgadmin with the new password.
if you open the psql console in a terminal window, by typing
$ psql
you're super user username will be shown before the =#, for example:
elisechant=#$
That will be the user name you should use for localhost.

How can I change a PostgreSQL user password?

How do I change the password for a PostgreSQL user?
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';
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
You can and should have the users' password encrypted:
ALTER USER username WITH ENCRYPTED PASSWORD 'password';
I believe the best way to change the password is simply to use:
\password
in the Postgres console.
Per ALTER USER documentation:
Caution must be exercised when specifying an unencrypted password with
this command. The password will be transmitted to the server in
cleartext, and it might also be logged in the client's command history
or the server log. psql contains a command \password that can be used
to change a role's password without exposing the cleartext password.
Note: ALTER USER is an alias for ALTER ROLE
To change the password using the Linux command line, use:
sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"
To the change password:
sudo -u postgres psql
Then
\password postgres
Now enter the new password and confirm.
Then \q to exit.
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.
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
To request a new password for the postgres user (without showing it in the command):
sudo -u postgres psql -c "\password"
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>;
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.
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.
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.
Use this:
\password
Enter the new password you want for that user and then confirm it.
If you don't remember the password and you want to change it, you can log in as "postgres" and then use this:
ALTER USER 'the username' WITH PASSWORD 'the new password';
TLDR:
On many systems, a user's account often contains a period, or some sort of 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.
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 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
And the fully automated way with Bash and expect (in this example we provision a new PostgreSQL administrator with the newly provisioned PostgreSQL password both on OS and PostgreSQL run-time level):
# The $postgres_usr_pw and the other Bash variables MUST be defined
# for reference the manual way of doing things automated with expect bellow
#echo "copy-paste: $postgres_usr_pw"
#sudo -u postgres psql -c "\password"
# The OS password could / should be different
sudo -u root echo "postgres:$postgres_usr_pw" | sudo chpasswd
expect <<- EOF_EXPECT
set timeout -1
spawn sudo -u postgres psql -c "\\\password"
expect "Enter new password: "
send -- "$postgres_usr_pw\r"
expect "Enter it again: "
send -- "$postgres_usr_pw\r"
expect eof
EOF_EXPECT
cd /tmp/
# At this point the 'postgres' executable uses the new password
sudo -u postgres PGPASSWORD=$postgres_usr_pw psql \
--port $postgres_db_port --host $postgres_db_host -c "
DO \$\$DECLARE r record;
BEGIN
IF NOT EXISTS (
SELECT
FROM pg_catalog.pg_roles
WHERE rolname = '"$postgres_db_useradmin"') THEN
CREATE ROLE "$postgres_db_useradmin" WITH SUPERUSER CREATEROLE
CREATEDB REPLICATION BYPASSRLS
PASSWORD '"$postgres_db_useradmin_pw"' LOGIN ;
END IF;
END\$\$;
ALTER ROLE "$postgres_db_useradmin" WITH SUPERUSER CREATEROLE
CREATEDB REPLICATION BYPASSRLS
PASSWORD '"$postgres_db_useradmin_pw"' LOGIN ;
"
Change password to "postgres" for user "postgres":
# ALTER USER postgres WITH ENCRYPTED PASSWORD '<NEW-PASSWORD>';
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 to pg_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
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
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.
Using pgAdmin 4:
Menu Object → Change password...
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.