Сброс пароля в PostgreSQL
Забыли пароль учетной записи postgres в PostgreSQL? Выполнить сброс не сложно. Для этого необходимо выполнить пару манипуляций.
1. Правим файл pg_hba.conf
Находим файл в папке Data директории установки PostgreSQL. В Windows путь выглядит примерно так c:\Program Files\PostgreSQL\9.2.4-1.1C\data\
В этом файле нужно найти такие строчки
# IPv4 local connections:
host all all 127.0.0.1/32 md5
host all all 0.0.0.0/0 md5
# IPv6 local connections:
host all all ::1/128 md5
Меняем md5 на trust.
2. Удаляем файл pgpass.conf
В Windows этот файл находится в c:\Users\Administrator\AppData\Roaming\postgresql\
Здесь хранится старый пароль от PostgreSQL. Простое изменение хранимого здесь пароля мне не помогло. Поэтому я его просто удалил.
3. Меняем пароль в pgAdmin
Запускаем pgAdmin и нам предлагается ввести пароль. Если отметить галочку сохранить, то пароль будет сохранен в pgpass.conf и больше программой запрашиваться не будет.
Чтобы обеспечить безопасность использования паролей необходимо вернуть алгоритм шифрования md5. Для этого в файле pg_hba.conf параметр trust обратно меняем на md5.
Для подключения на локальном компьютере к PostgreSQL с помощью psql, pg_dump в локальных адресах IPv4 127.0.0.1/32 и IPv6 ::1/128 значение trust нужно оставить.
5 thoughts on “ Сброс пароля в PostgreSQL ”
Ты не сменил и не сбросил пароль. Ты отключил все механизмы защиты, поэтому он теперь пускает не с новым паролем, а вообще с ЛЮБЫМ. Строка trust как раз и отключает проверку пароля. А файл pgpass.conf нужен для того что бы утилитка pgAdmin могла туда сохранить пароль и не спрашивать его больше. Именно поэтому он храниться в твоем профиле, что бы никто другой не мог туда зяглянуть.
Пароль пользователя меняется командой ALTER USER user_name WITH PASSWORD ‘new_password’;
Удали статью, а то кучи начинающих «АДМИНОВ» понаоткрывают голую жопу по твоим советам.
Прежде чем писать такой комментарий
Строка trust как раз и отключает проверку пароля.
..внимательней читайте статью, там написано
параметр trust обратно меняем на md5
Про файл pgpass.conf тоже в статье сказано.
Так что с голой жопой останутся только такие же невнимательные как ты.
Глохни, петух. Как я смогу изменить пароль, если не могу на сервер зайти без пароля, придурок!
Тебе выше написали, что параметры доступа в pg_hba.conf изменены так, чтобы пустить потом тебя БЕЗ пароля с localhost. Да, когда меняете этот файл, перещапускать БД не забывайте.
Потом влетай в консоль psql -Upostgres -W -hlocalhost c пустым паролем, и меняй себе его наздоровье.
Затем возверни настройки обратно в md5 и перезапусти БД.
Виндовозники привыкли мышкой водить. Нет чтоб в терминале просто и со вкусом ALTER USER user_name WITH PASSWORD ‘new_password’;
Forgot Admin Password on Postgres (Windows Installation), can’t reset
I have a Windows PostgreSQL installation.
According to some posts, there is no default password set for the ‘postgres’ user yet I can’t connect using an empty password string.
I’m receiving this exception when I try to connect:
I tried that and restarted PGAdmin but it still asks me for the password when I try to connect:
The task manager in Windows shows some PostgreSQL processes are running. I can’t switch them off.
I have tried this and it failed:
How can I reset the default password for user ‘postgres’?
3 Answers 3
Based on AK47’s answer and some additional info I fixed it by doing the following,
1) Stop Postgres if currently running, command line below. Need to give it the ‘data’ dir. In my case C:\PostgreSQL\data
2) Edit the file pg_hba.conf (it’s also in the \data dir) as follows:
As AK40 wrote, change all MD5 references to trust , e.g.
4) In the PG Command Prompt that appears type,
5) Save this by typing wq enter to exit the PG Prompt
6) Now start Postgres
7) Might want to revert the MD5 -> Trust change later in the pg_hba.conf .
Update your pg_hba.conf file to allow for trusted local connections
then restart your PostgreSQL server
at this point you can connect to your server as postgres user using a local connection without the need to enter a password (omitting the -h parameter when calling the psql command will use a local connection — if you pass -h then this will match the line host all all 0.0.0.0/0 in your pg_hba.conf file)
You can then alter the postgres user role and set the password to whatever you like using the following command in the psql terminal
Once this is done you can restart your PostgreSQL server again
and at this point your password should be changed to the new password
I forgot the password I entered during postgres installation
I either forgot or mistyped (during the installation) the password to the default user of Postgres. I can’t seem to be able to run it and I get the following error:
Is there anyway to reset the password or how do I create a new user with superuser privileges?
I am new to Postgres and just installed it for the first time. I am trying to use it with Rails and I am running Mac OS X Lion.
15 Answers 15
find the file pg_hba.conf — it may be located, for example in /etc/postgresql-9.1/pg_hba.conf .
cp pg_hba.conf pg_hba.conf-backup
place the following line (as either the first uncommented line, or as the only one):
For all occurrence of below (local and host) , exepct replication section if you don’t have any it has to be changed as follow ,no MD5 or Peer autehication should be present.
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
host all all 127.0.0.1/32 trust
you can now connect as any user. Connect as the superuser postgres (note, the superuser name may be different in your installation. In some systems it is called pgsql , for example.)
psql -U postgres
psql -h 127.0.0.1 -U postgres
(note that with the first command you will not always be connected with local host)
Reset password (‘replace my_user_name with postgres since you are resetting postgres user)
ALTER USER my_user_name with password ‘my_secure_password’;
Restore the old pg_hba.conf as it is very dangerous to keep around
cp pg_hba.conf-backup pg_hba.conf
restart the server, in order to run with the safe pg_hba.conf
sudo /etc/init.d/postgresql restart
When connecting to postgres from command line, don’t forget to add -h localhost as command line parameter. If not, postgres 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.
Working with -h localhost :
The pg_hba.conf ( C:\Program Files\PostgreSQL\9.3\data ) file has changed since these answers were given. What worked for me, in Windows, is to open the file and change the METHOD from md5 to trust :
Then, using pgAdmin III, I logged in using no password and changed user postgres’ password by going to File -> Change Password
Just a note, on Linux You can simply run sudo su — postgres to become the postgres user and from there change what required using psql.
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.
Edit the file /etc/postgresql/ /main/pg_hba.conf and find the following line:
Edit the line and change md5 at the end to trust and save the file
Reload the postgresql service
This will load the configuration files. Now you can modify the postgres user by logging into the psql shell
Update the postgres user’s password
Edit the file /etc/postgresql/ /main/pg_hba.conf and change trust back to md5 and save the file
Reload the postgresql service
Verify that the password change is working
Adding the answer for Windows User for the latest postgres version (>10),
Go to your postgres installation location, and search for pg_hba.conf , you will find it in ..\postgres\data\pg_hba.conf
Open that file with notepad, find this line,
Change the method from md5 to trust,
Now go to your SQL Shell(PSQL) and leave everything blank,
It will not ask for 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 login with your new user and password and you can check \du for its attributes.
FOR WINDOWS: (what has helped me)
Open your cmd and go to C:\Program Files\PostgreSQL\12\data This is usually the right path. You might have it stored somewhere else. Note that, if you have a different postgresql version, there will be a different number. That doesn’t matter.
Find a pg_hba.conf file and copy it to somewhere else (That way you will have an unmodified version of this file, so you will be able to look at it after we make some changes)
Open pg_hba.conf file (not the backup, but the original)
Find the multiple lines that start with host near the bottom of the file:
host all all 127.0.0.1/32 md5
host all all ::1/128 md5
host replication all 127.0.0.1/32 md5
host replication all ::1/128 md5
Replace md5 with trust:
host all all 127.0.0.1/32 trust
host all all ::1/128 trust
host replication all 127.0.0.1/32 trust
host replication all ::1/128 trust
Close this file
Go to your search bar on windows and open Services app. Find postgres and restart it. picture of services app
Write cd.. in cmd and then cd bin. Your path should be C:\Program Files\PostgreSQL\12\bin
Enter: psql -U postgres -h localhost
Enter: ALTER USER postgres with password ‘ ‘; Make sure that you include ; at the end “ALTER ROLE” should be displayed as an indication that the previous line was executed successfully
Open original pg_hba.conf file and change back from trust to md5
Restart the server with Services app as before
For Windows installation, a Windows user is created. And «psql» use this user for connection to the port. If you change the PostgreSQL user’s password, it won’t change the Windows one. The commandline juste below works only if you have access to commandline.
Instead you could use Windows GUI application «c:\Windows\system32\lusrmgr.exe». This app manage users created by Windows. So you can now modify the password.
What I did to resolve the same problem was:
Open pg_hba.conf file with gedit editor from the terminal:
It will ask for password. Enter your admin login password. This will open gedit with the file. Paste the following line:
Save and close it. Close the terminal and open it again and run this command:
You will now enter the psql console. Now change the password by entering this:
If it says user does not exist then instead of ALTER use CREATE .
Lastly, remove that certain line you pasted in pg_hba and save it.
If you are in windows you can just run
and login in postgres with postgres/postgres as user/password
The file .pgpass in a user’s home directory or the file referenced by PGPASSFILE can contain passwords to be used if the connection requires a password (and no password has been specified otherwise). On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user’s profile).
This file should contain lines of the following format:
(You can add a reminder comment to the file by copying the line above and preceding it with #.) Each of the first four fields can be a literal value, or *, which matches anything. The password field from the first line that matches the current connection parameters will be used. (Therefore, put more-specific entries first when you are using wildcards.) If an entry needs to contain : or \, escape this character with . A host name of localhost matches both TCP (host name localhost) and Unix domain socket (pghost empty or the default socket directory) connections coming from the local machine. In a standby server, a database name of replication matches streaming replication connections made to the master server. The database field is of limited usefulness because users have the same password for all databases in the same cluster.
On Unix systems, the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600
/.pgpass. If the permissions are less strict than this, the file will be ignored. On Microsoft Windows, it is assumed that the file is stored in a directory that is secure, so no special permissions check is made.
PostgreSQL: How to change PostgreSQL user password?
How do I change the password for PostgreSQL user?
20 Answers 20
To login without a password:
To reset the password if you have forgotten:
/.psql_history – RickyA Oct 30 ’13 at 13:03
Then to quit psql :
If that does not work, reconfigure authentication.
Edit /etc/postgresql/9.1/main/pg_hba.conf (path will differ) and change:
Then restart the server:
You can and should have the users’s password encrypted:
I believe the best way to change the password is simply to use:
in the Postgres console.
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 password using Linux command line, use:
To Change Password
now enter New Password and Confirm
Go to your Postgresql Config and Edit pg_hba.conf
sudo vim /etc/postgresql/9.3/main/pg_hba.conf
Then Change this Line :
then Restart the PostgreSQL service via SUDO command then
You will be now entered and will See the Postgresql terminal
and enter the NEW Password for Postgres default user, After Successfully changing the Password again go to the pg_hba.conf and revert the change to «md5»
now you will be logged in as
with your new Password.
Let me know if you all find any issue in it.
$ psql -U postgres psql: FATAL: Peer authentication failed for user «postgres» – G M Jul 4 ’15 at 22:12
To request a new password for the postgres user (without showing it in the command):
This was the first result on google, when I was looking how to rename a user, so:
A couple of other commands helpful for user management:
Move user to another group
Configuration that I’ve got on my server was customized a lot and I managed to change password only after I set trust authentication in the pg_hba.conf file:
Don’t forget to change this back to password or md5
If you are on windows.
Open pg_hba.conf file and change from md5 to peer
Open cmd, type psql postgres postgres
Then type \password to be prompted for a new password.
Refer to this medium post for further information & granular steps.
For my case on Ubuntu 14.04 installed with postgres 10.3. I need to follow the following steps
- su — postgres to switch user to postgres
- psql to enter postgres shell
- \password then enter your password
- \q to quit the shell session
Then you switch back to root by executing exit and configure your pg_hba.conf (mine is at /etc/postgresql/10/main/pg_hba.conf ) by making sure you have the following line
local all postgres md5
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:
TLDR:
On many systems, a user’s account often contains a period, or some sort of punction (user: john.smith, horise.johnson). IN these cases a modification will have to be made to the accepted answer above. The change requires the username to be double-quoted.
Rational:
Postgres is quite picky on when to use a ‘double quote’ and when to use a ‘single quote’. Typically when providing a string you would use a single quote.
Similar to other answers in syntax but it should be known that you can also pass a md5 of the password so you are not transmitting a plain text password.
Here are a few scenarios of unintended consequences of altering a users password in plain text.
- 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 its 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 admin or low level employee tasked with reviewing logs.
With that said here is how we can alter a user’s password by building an md5 of the password.
- Postgres when hash a password as md5, salts the password with the user name then prepends the text «md5» to the resulting hash.
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.
and the fully automated way with bash and expect ( in this example we provision a new postgres admin with the newly provisioned postgres pw both on OS and postgres run-time level )
In general, just use pg admin UI for doing db related activity.
If instead you are focusin more in automating database setup for your local development, or CI etc.
For example, you can use a simple combo like this.
(a) Create a dummy super user via jenkins with a command similar to this:
this will create a super user called experiment001 in you postgres db.
(b) Give this user some password by running a NON-Interactive SQL command.
Postgres is probably the best database out there for command line (non-interactive) tooling. Creating users, running SQL, making backup of database etc. In general it is all quite basic with postgres and it is overall quite trivial to integrate this into your development setup scripts or into automated CI configuration.
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.
I was on Windows (Server 2019; PG 10) so local type connections ( pg_hba.conf : local all all peer ) are not supported. The following should work on Windows and Unix systems alike:
- 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
Most of the answers were mostly correct, but you need to look out for minor things. The problem I had was that I didn’t ever set the password of postgres, so I couldn’t log into an SQL command line that allowed me to change passwords. These are the steps that I used successfully (note that most or all commands need sudo/root user):