Как узнать пароль от postgresql

от admin

Сброс пароля в 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 нужно оставить.

7 thoughts on “ Сброс пароля в PostgreSQL ”

Ты не сменил и не сбросил пароль. Ты отключил все механизмы защиты, поэтому он теперь пускает не с новым паролем, а вообще с ЛЮБЫМ. Строка trust как раз и отключает проверку пароля. А файл pgpass.conf нужен для того что бы утилитка pgAdmin могла туда сохранить пароль и не спрашивать его больше. Именно поэтому он храниться в твоем профиле, что бы никто другой не мог туда зяглянуть.
Пароль пользователя меняется командой ALTER USER user_name WITH PASSWORD ‘new_password’;

Удали статью, а то кучи начинающих «АДМИНОВ» понаоткрывают голую жопу по твоим советам.

  1. admin Автор записи 07.07.2019 в 16:05

Прежде чем писать такой комментарий

Строка trust как раз и отключает проверку пароля.

..внимательней читайте статью, там написано

параметр trust обратно меняем на md5

Про файл pgpass.conf тоже в статье сказано.
Так что с голой жопой останутся только такие же невнимательные как ты.

Глохни, петух. Как я смогу изменить пароль, если не могу на сервер зайти без пароля, придурок!

Тебе выше написали, что параметры доступа в pg_hba.conf изменены так, чтобы пустить потом тебя БЕЗ пароля с localhost. Да, когда меняете этот файл, перещапускать БД не забывайте.
Потом влетай в консоль psql -Upostgres -W -hlocalhost c пустым паролем, и меняй себе его наздоровье.
Затем возверни настройки обратно в md5 и перезапусти БД.

Виндовозники привыкли мышкой водить. Нет чтоб в терминале просто и со вкусом ALTER USER user_name WITH PASSWORD ‘new_password’;

На локальном компьютере это оказалось оптимальным решением. Конечно, в сочетании с обычной сменой пароля, когда смог попасть в админку. Если Вы и петух, то очень полезный для сообщества) Спасибо Вам!

Сброс пароля в PostgreSQL на Windows платформах

Забыли пароль учетной записи postgres в PostgreSQL? Выполнить сброс не сложно. Для этого необходимо выполнить пару манипуляций.

1. Правим файл pg_hba.conf

Находим файл в папке Data директории установки PostgreSQL. В Windows путь выглядит примерно так c:\Program Files\PostgreSQL\9.2.4-1.1C\data\

В этом файле нужно найти такие строчки

Меняем 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 нужно оставить.

Как посмотреть пароль PostgreSQL?

При запуске выдаёт ошибку:
The error ‘FATAL: password authentication failed for user «postgres»
‘ occurred
Нагуглил, что при установке Postgres выдаётся пароль, но я Postgres не устанавливал, он уже на компе был, может с виндой установился, не знаю. Как этот пароль посмотреть или новый создать? Операционка Windows 10.

И ещё ошибка с from psycopg2 import OperationalError, он просто не находит OperationalError.

  • Вопрос задан более года назад
  • 13022 просмотра
  • Facebook
  • Вконтакте
  • Twitter

версия psycopg2 какая?

Проверяйте свой pg_hba.conf. Там нужна запись для 127.0.0.1 или localhost

Инсталлятор может задавать какой-то пароль по умолчанию, а может и вообще не задавать (тогда юзер postgres не сможет входить по паролю). Вам нужно либо настроить в pg_hba.conf вход без пароля (метод trust), либо зайти через консоль/pgadmin и задать пароль:
ALTER ROLE postgres WITH PASSWORD ‘123’; или в psql \password

Зайти через консоль/pgadmin без пароля получится только, если в pg_hba.conf это настроено (обычно инсталлятор это делает, если нет — меняйте файл вручную и не забудьте рестартнуть постгрес).

  • Facebook
  • Вконтакте
  • Twitter

galaxy,
Хотя в __init__.py они импортированы 61685c1727a83404260255.png

Soul1, не понял, что не работает.
Сервис запущен? Подключение через pgAdmin происходит?
И у вас вообще кластер инициализирован? В папке с pg_hba.conf есть куча папок: base, global, pg_*?

IDE может тупить. Запустите в питоне простейший скрипт

Если работает — все ок с импортом.

61689aa417612530199885.png

В службах есть строка posrgresql-8.4 — PostgreSQL Server 8.4 Когда я в первый раз зашёл его перезапустить, там были пункты «остановить», «перезапустить» и ещё какой-то. Я его несколько раз перезапускал и в итоге сейчас он выключен и включаться не хочет, есть только пункт «запустить», но он выполняется несколько минут и выдаёт ошибку.
Ещё я не знал, что posgres вообще установлен и скачал 12 версию, а на компе оказалась 8.4 Они не будут конфликтовать или ещё что?

I forgot the password I entered during PostgreSQL installation

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:

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

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

Читать:
Cpu clock drive что это

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 the password (‘replace my_user_name with postgres since you are resetting the postgres user)

ALTER USER my_user_name with password ‘my_secure_password’;

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

cp pg_hba.conf-backup pg_hba.conf

Restart the server, in order to run with the safe pg_hba.conf file

sudo /etc/init.d/postgresql restart

Further reading about that pg_hba file: 19.1. The pg_hba.conf File (official documentation)

Peter Mortensen's user avatar

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.

Working with -h localhost :

Peter Mortensen's user avatar

SaeX's user avatar

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, was to open the file and change the METHOD from md5 to 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

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.

Nathan Wailes's user avatar

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 the pg_hba.conf file (not the backup, but the original)

Find the multiple lines that start with host near the bottom of the file:

Replace md5 with trust:

Close this file

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

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 ‘<your new password>’; Make sure that you include ; at the end “ALTER ROLE” should be displayed as an indication that the previous line was executed successfully

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

Restart the server with Services app as before

Peter Mortensen's user avatar

Vito Farina's user avatar

Edit the file /etc/postgresql/<version>/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/<version>/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

Peter Mortensen's user avatar

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

Daniel's user avatar

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 ..\postgres\data\pg_hba.conf .

Open that file with Notepad, and find this line:

Now go to your SQL shell (PSQL) and leave everything blank,

It will not ask for a password this time, and you will be logged in,

Now run this line:

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

Bidhan Majhi's user avatar

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:\Windows\system32\lusrmgr.exe". This application manages users created by Windows. So you can now modify the password.

Peter Mortensen's user avatar

I did this to resolve the same problem:

Open the pg_hba.conf file with the gedit editor from the terminal:

It will ask for a password. Enter your admin login password. This will open gedit with the file. Paste the following line:

Save and close it.

Close the terminal, open it again and run this command:

You will now enter the psql console.

Now change the password by entering this:

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

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)

Похожие статьи