Как сбросить пароль postgresql
Change/reset postgresql user password on windows 7
Several days ago I install postgesql 9.2 version on my local computer. (OS windows 7)
Now I forgot my password and I can not login in pgAdmin.
How to change postgresql password on windows 7?
6 Answers 6
You can find where the pg_hba.conf is located by typing in a psql command line:
Below steps helped me to reset the password-
Go to pg_hba.conf file at path e.g. C:\Program Files\PostgreSQL\10\data and add below line at the end,
Connect using PgAdmin or any software that you prefer and run query,
Remove the line that you added in step 1.
Edit pg_hba.conf to allow you to connect without a password. Then use ALTER USER to reset the password. Then change pg_hba.conf back again.
For the documentation on pg_hba.conf, see here:
Run your psql executable file and login into your database using your old password, use the following command to login:
In windows postgres stores password for automatic login at following path (only if you would have selected password save option while installation)
you can open this file in a text editor and see your password.
I am using postgres version 14.0 and Windows 10. To reset the password:
Type in your current password
3 Then type: \password postgres
It brings up the prompts to type the new password and confirm. Note for the psql command to work on the windows command prompt, you need to set the postgres bin folder on the path environment variable. You can just google how to do this.
PostgreSQL: Resetting password of PostgreSQL on Ubuntu [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
In Ubuntu, I installed PostgreSQL database and created a superuser for the server.
If I forgot the password of the postgresql superuser, how can I reset it (the password) for that user?
I tried uninstalling it and then installing it again but the previously created superuser is retained.
1 Answer 1
Assuming you’re the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:
(About the file location: 9.1 is the major postgres version and main the name of your «cluster». It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).
Then you should be able to log in with psql as the postgres superuser with this shell command:
Once inside psql, issue the SQL command:
Keep in mind that you need to type postgres with a single S at the end
It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.
Сброс пароля в 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 тоже в статье сказано.
Так что с голой жопой останутся только такие же невнимательные как ты.
Глохни, петух. Как я смогу изменить пароль, если не могу на сервер зайти без пароля, придурок!
Виндовозники привыкли мышкой водить. Нет чтоб в терминале просто и со вкусом ALTER USER user_name WITH PASSWORD ‘new_password’;
Я забыл пароль, который я ввел во время установки postgres
Я либо забыл, либо ошибся (во время установки) пароль для пользователя Postgres по умолчанию. Кажется, я не могу запустить его, и я получаю следующую ошибку:
есть ли способ сбросить пароль или как создать нового пользователя с привилегиями суперпользователя?
Я новичок в Postgres и только что установил его в первый раз. Я пытаюсь использовать его с Rails, и я запускаю Mac OS X Lion.
9 ответов
cp pg_hba.conf pg_hba.conf-backup
поместите следующую строку (как первую незафиксированную строку или как единственную):
local all all trust
перезапустите сервер PostgreSQL (например, в Linux:)
sudo /etc/init.d/postgresql restart
если служба (демон) не запускает отчеты в файле журнала:
локальные соединения не поддерживаются этой сборкой
вы должны изменить
local all all trust
host all all 127.0.0.1/32 trust
(обратите внимание, что с первой командой вы не всегда будете на связи с локальным узлом)
ALTER USER my_user_name with password ‘my_secure_password’;
восстановить старую pg_hba.conf Как это очень опасно сохранить вокруг
cp pg_hba.conf-backup pg_hba.conf
перезагрузить сервер, в приказываю бежать с сейфом pg_hba.conf
sudo /etc/init.d/postgresql restart
ниже показан сброс пароля, неудачный вход с одноранговой аутентификацией и успешный вход с использованием TCP-соединения.
The pg_hba.conf ( C:\Program Files\PostgreSQL.3\data ) файл изменился с тех пор, как были даны эти ответы. Что сработало для меня в Windows, это открыть файл и изменить METHOD С md5 до trust :
Если вы находитесь в Windows, вы можете просто запустить
и войдите в postgres с postgres/postgres как пользователь / пароль
для установки Windows создается пользователь Windows. И «psql» использует этого пользователя для подключения к порту. Если вы измените пароль пользователя PostgreSQL, он не изменит пароль Windows. Командная строка juste ниже работает, только если у вас есть доступ к командной строке.
редактировать файл /etc/postgresql/ /main/pg_hba.conf и найдите следующую строку:
изменить строку и изменить md5 в конце trust и сохраните файл
перезагрузка postgresql сервис
это загрузит файлы конфигурации. Теперь вы можете изменить postgres пользователь, войдя на psql раковины
обновить postgres пароль пользователя
перезагрузка postgresql сервис
убедитесь, что изменение пароля работает
что я сделал, чтобы решить ту же проблему:
открыть файл pg_hba.conf файл с редактором gedit из терминала:
он будет запрашивать пароль. Введите пароль администратора. Это откроет gedit с файлом. Вставьте следующую строку:
сохранить и закрыть его. Закройте терминал, откройте его снова и выполните следующую команду:
теперь вы войдете в консоль psql. Теперь изменить пароль, введя это:
наконец, удалите определенную строку, вставленную в pg_hba, и сохраните ее.
этот файл должен содержать следующие строки формат:
имя хоста: порт: база данных: имя пользователя: пароль
(вы можете добавить комментарий напоминания в файл, скопировав строку выше и предшествующую ей #.) Каждое из первых четырех полей может быть литеральным значением или*, которое соответствует чему угодно. Будет использоваться поле пароля из первой строки, соответствующее текущим параметрам соединения. (Поэтому при использовании подстановочных знаков сначала ставьте более конкретные записи.) Если запись должна содержать : или \, избежать этого символа с. Имя хоста localhost соответствует подключениям TCP (имя хоста localhost) и Unix domain socket (pghost empty или каталог сокетов по умолчанию), поступающим с локального компьютера. На резервном сервере имя базы данных репликации соответствует потоковым соединениям репликации, выполненным на главном сервере. Поле базы данных имеет ограниченную полезность, поскольку пользователи имеют одинаковый пароль для всех баз данных в одном кластере.
/.pgpass. Если разрешения менее строгие, файл будет проигнорирован. В Microsoft Windows предполагается, что файл хранится в защищенном каталоге, поэтому проверка специальных разрешений не производится.
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
cp pg_hba.conf pg_hba.conf-backup
place the following line (as either the first uncommented line, or as the only one):
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
local all all trust
host all all 127.0.0.1/32 trust
(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
The below shows a reset of the password, a failed login with PEER authentication and a successful login using a TCP connection.
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 :
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.
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
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
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: 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
Adding the answer for Windows User for the latest postgres version (>10),
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.
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:
Lastly, remove that certain line you pasted in pg_hba and save it.
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.
If you are in windows you can just run
and login in postgres with postgres/postgres as user/password
This file should contain lines of the following format:
/.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.














