Vitaly Karasik, при инсталяции он просит придумать пароль, я и пробовал вводить этот самый пароль при создании БД, но не принимает. Вы мне скинули ссылку, попробовал по инструкции, но выяснилось, что у меня урезанная версия виндоус и нет функции просмотра учетных записей других программ.
Кстати в pgadmin с этим паролем я могу зайти, там попробовал изменить пароль базы postgres, создать еще одного суперюзера, но теперь отчет об ошибке ведет себя по другому:
Раньше в сообщении об ошибке было написано, что не удалось подключиться к базе postgres, сейчас пишет, что не удалось подключиться к базе template1… и дальше все также (пользователь Albert не прошел проверку подлинности (по паролю).
Завтра поставлю себе убунту и буду работать уже на ней. Надеюсь там не будет возникать таких ошибок. Еще отчет об ошибке отправил на офф. сайт postgreSQL.
Table of Contents
- Introduction
- Solutions to Fix the Error
- 1. Verify the Password
- 2. Reset the ‘postgres’ User Password
- 3. Editing the pg_hba.conf File
- Conclusion
Introduction
Encountering an authentication error with PostgreSQL can be a stress-inducing event, but there are several methodologies to troubleshoot and solve this issue. The error “Password authentication failed for user ‘postgres’” specifically means that the password provided for the ‘postgres’ user is not matching the one stored in the database. This discrepancy might be due to various reasons, such as an incorrect password, misconfigured PostgreSQL files or insufficient user rights.
Solutions to Fix the Error
1. Verify the Password
This solution starts with the simplest step of verifying and ensuring that the correct password is being used while attempting to connect to the PostgreSQL database.
- Double-check the password provided for being accurate.
- Try logging in via the psql command-line interface to validate the password:
psql -U postgres -W
If the above-mentioned password works, the problem might lie with the application configuration using PostgreSQL.
Advantages: Simple and quick to check.
Limitations: If the password is lost, this method will not resolve the error directly.
2. Reset the ‘postgres’ User Password
If the password for the ‘postgres’ user has been forgotten or needs to be reset, this can be accomplished by accessing the PostgreSQL interactive terminal as a different, privileged user and setting a new password.
1. Sudo to the PostgreSQL user:
sudo su - postgres
2. Open the PostgreSQL interactive terminal:
psql
3. Run the command to set a new password for ‘postgres’ user:
ALTER USER postgres WITH PASSWORD 'newpassword';
Advantages: Direct method to reset a forgotten password.
Limitations: Requires provisional access to the PostgreSQL shell as a privileged user.
3. Editing the pg_hba.conf File
Improper configuration in PostgreSQL’s pg_hba.conf file can result in authentication issues. Modifying this file to use a different authentication method such as ‘trust’ can temporarily bypass the password for troubleshooting purposes.
- Access the PostgreSQL data directory, which typically contains the pg_hba.conf file. It is usually located in ‘/etc/postgresql/<version>/main/’ on Ubuntu or ‘/var/lib/pgsql/data/’ on Red Hat-based systems.
- Edit the pg_hba.conf file, changing the method to ‘trust’ for localhost or specific IP addresses.
- Reload the PostgreSQL server configuration:
sudo systemctl reload postgresql
Although changing the file and reloading the configuration is fast, using the ‘trust’ authentication method should be temporary, as it is not secure.
Advantages: Useful for diagnosing authentication issues.
Limitations: Must ensure the security of the system during troubleshooting, as ‘trust’ method allows connections without a password.
Conclusion
If none of the solutions work, there may be a deeper configuration issue or possible data corruption. To handle such scenarios, additional diagnostics may be required, possibly leading to recovery from backups or consulting with a database specialist. Nonetheless, the above solutions cover the majority of the scenarios encountered with the stated error in PostgreSQL.
установил PostgreSQL 9.4.
после запуска
root@DebianServer:/usr/lib/postgresql/9.4# su postgres
$ psql
psql: не удалось подключиться к серверу: Нет такого файла или каталога
Он действительно работает локально и принимает
соединения через доменный сокет «/var/run/postgresql/.s.PGSQL.5433»?
подскажите куда копать,пол интернета перечитал?
Cообщение объединено 20 Января 2017, 21:18:12
log
2017-01-20 16:14:26 EET [16162-2] СООБЩЕНИЕ: получен запрос на "вежливое" выключение
2017-01-20 16:14:26 EET [16167-2] СООБЩЕНИЕ: процесс запуска автоочистки завершается
2017-01-20 16:14:26 EET [16164-1] СООБЩЕНИЕ: выключение
2017-01-20 16:14:26 EET [16164-2] СООБЩЕНИЕ: система БД выключена
2017-01-20 16:15:35 EET [16255-1] СООБЩЕНИЕ: система БД была выключена: 2017-01-20 16:14:26 EET
2017-01-20 16:15:35 EET [16255-2] СООБЩЕНИЕ: Защита от наложения мультитранзакций сейчас включена
2017-01-20 16:15:35 EET [16254-1] СООБЩЕНИЕ: система БД готова принимать подключения
2017-01-20 16:15:35 EET [16259-1] СООБЩЕНИЕ: процесс запуска автоочистки создан
2017-01-20 16:15:36 EET [16261-1] [н/д]@[н/д] СООБЩЕНИЕ: неполный стартовый пакет
2017-01-20 16:15:36 EET [16264-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:36 EET [16264-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:37 EET [16267-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:37 EET [16267-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:37 EET [16270-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:37 EET [16270-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:38 EET [16273-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:38 EET [16273-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:38 EET [16276-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:38 EET [16276-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:39 EET [16279-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:39 EET [16279-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:39 EET [16282-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:39 EET [16282-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:40 EET [16285-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:40 EET [16285-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:40 EET [16288-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:40 EET [16288-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:41 EET [16291-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:41 EET [16291-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:41 EET [16294-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю)
2017-01-20 16:15:41 EET [16294-2] postgres@postgres ПОДРОБНОСТИ: Подключение соответствует строке 85 в pg_hba.conf: "local all postgres md5"
2017-01-20 16:15:41 EET [16254-2] СООБЩЕНИЕ: получен запрос на "вежливое" выключение
2017-01-20 16:15:41 EET [16259-2] СООБЩЕНИЕ: процесс запуска автоочистки завершается
2017-01-20 16:15:41 EET [16256-1] СООБЩЕНИЕ: выключение
2017-01-20 16:15:41 EET [16256-2] СООБЩЕНИЕ: система БД выключена
Palamar, используй теги для оформления сообщения.
Мало видеть нам начало — надо видеть и конец. Если видишь ты создание — значит где-то есть ТВОРЕЦ
Многие жалуются: геометрия в жизни не пригодилась. Ямб от хорея им приходится отличать ежедневно?
в половине интернета вы бы точно нашли, что для подключения к локалхосту нужно в pg_hda.conf нужно открыть доступ:
host all all 127.0.0.1/32 trust
Цитата: ogost от 23 января 2017, 04:17:12
в половине интернета вы бы точно нашли, что для подключения к локалхосту нужно в pg_hda.conf нужно открыть доступ:host all all 127.0.0.1/32 trust
добавил в pg_hba.conf
host all all 127.0.0.1/32 trust
без изменений.
root@DebianServer:/etc/postgresql/9.4/main# psql
psql: не удалось подключиться к серверу: Нет такого файла или каталога
Он действительно работает локально и принимает
соединения через доменный сокет «/var/run/postgresql/.s.PGSQL.5433»?
там не добавлять нужно, а изменить существующую строчку.
кроме того, нужно postgre перезапускать
Palamar, ругается же на строку 85 конфига.
У Вас там адрес/маска не указаны.
UPD: неверно
Цитата: qupl от 23 января 2017, 14:13:17
Palamar, ругается же на строку 85 конфига. У Вас там адрес/маска не указаны.
Посмотрите пожалуйста конфиги,возможно в них что то напорол.
Есть ли возможность создать новые конфиги без переустановки postgres?
В строке 85, замените md5 на peer.
создал пользователя при подключении ошибка
$ psql -d aircontrol -U air
psql: ВАЖНО: пользователь «air» не прошёл проверку подлинности (Peer)
$ psql -d aircontrol -U admin
psql: ВАЖНО: пользователь «admin» не прошёл проверку подлинности (Peer)
$
Palamar, а взять и почитать про установку? хотя бы нагуглить?
qaa-engineer.ru > Вопросы и ответы > ВАЖНО: пользователь «postgres» не прошёл проверку подлинности (по паролю) (pgjdbc: autodetected server-encoding to be windows-1251)
«ВАЖНО: пользователь ‘postgres’ не прошёл проверку подлинности (по паролю) (pgjdbc: autodetected server-encoding to be windows-1251)»
Первые шаги в программировании требуют от разработчика решения множества ошибок и проблем, с которыми он встречается. Однако некоторые ошибки могут быть особенно запутывающими и требовать дополнительных знаний. Одна из таких проблем, с которой многие пользователи PostgreSQL сталкиваются, — это ошибка «пользователь ‘postgres’ не прошёл проверку подлинности (по паролю) (pgjdbc: autodetected server-encoding to be windows-1251)».
Что означает эта ошибка? Почему она возникает? Как ее исправить? В этой статье мы рассмотрим этот вопрос, предоставив подробное объяснение причин и пути решения данной проблемы.
Ошибка «пользователь ‘postgres’ не прошёл проверку подлинности (по паролю) (pgjdbc: autodetected server-encoding to be windows-1251)» обычно возникает при попытке подключения к базе данных PostgreSQL с использованием пользователя ‘postgres’. Ошибка указывает на то, что сервер базы данных не принимает введенный пароль для данного пользователя и пытается установить кодировку windows-1251 для взаимодействия с драйвером JDBC.
Проблема возникает по нескольким причинам. Одна из них — неправильно настроенное соединение с базой данных. В этом случае может быть указан неправильный пароль или имя пользователя. Проверьте правильность указанных данных и убедитесь, что они соответствуют настройкам вашей базы данных.
Еще одна причина возникновения ошибки может быть связана с настройками кодировки. В этом случае проверьте настройки кодировки вашей базы данных и соответствующие настройки клиента. Если кодировки не совпадают, происходит ошибка при попытке установить соединение.
Также возможна ситуация, когда пользователь ‘postgres’ не имеет правильных разрешений для подключения к базе данных. Убедитесь, что у пользователя есть необходимые привилегии для доступа к базе данных и выполнения операций чтения и записи.
Теперь, когда мы понимаем возможные причины ошибки, давайте рассмотрим некоторые способы исправления этой проблемы.
1. Проверьте правильность введенных данных. Убедитесь, что пароль и имя пользователя указаны правильно. Если необходимо, измените значения и попробуйте снова подключиться.
2. Проверьте настройки кодировки. Убедитесь, что кодировка базы данных соответствует кодировке, указанной в настройках клиента. Если они не совпадают, измените одну из них так, чтобы они были совместимы.
3. Проверьте разрешения пользователя ‘postgres’. Убедитесь, что у пользователя есть правильные разрешения для подключения к базе данных. Если нет, измените разрешения, чтобы пользователь мог успешно подключиться.
4. Проверьте версию PostgreSQL и драйвер JDBC. В некоторых случаях проблема может быть связана с несовместимостью между версиями PostgreSQL и драйвера JDBC. Убедитесь, что у вас установлена последняя версия драйвера JDBC, совместимая с вашей версией PostgreSQL.
5. Измените настройки базы данных. В некоторых случаях проблема может быть связана с настройками базы данных. Попробуйте изменить некоторые настройки, такие как метод аутентификации, чтобы установить соединение.
6. Проверьте логи базы данных. Иногда проблема может быть связана с другими проблемами, такими как проблемы сетевого соединения или ошибки при установке базы данных. Просмотрите логи базы данных, чтобы узнать больше о возможных причинах ошибки.
Избавиться от ошибки «пользователь ‘postgres’ не прошёл проверку подлинности (по паролю) (pgjdbc: autodetected server-encoding to be windows-1251)» может быть сложной задачей. Важно проделать несколько проверок и испытать различные подходы к решению проблемы. Однако, следуя вышеуказанным рекомендациям, вы должны быть в состоянии успешно устранить данную ошибку и восстановить функциональность вашей базы данных PostgreSQL.
В заключение, помните, что в программировании ошибки и проблемы могут возникать в любой момент. Важно не паниковать и искать решения, основываясь на доступной информации и своих навыках. Представленная статья была призвана помочь вам понять и исправить ошибку «пользователь ‘postgres’ не прошёл проверку подлинности (по паролю) (pgjdbc: autodetected server-encoding to be windows-1251)», и мы надеемся, что она оказалась полезной для вас. Удачи в ваших программистских приключениях!
Перейти к контенту
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;
For those of you who got this error and NONE of these answers helped, I may not have StackOverflow fish for you, but I’ll teach you how to fish!
You likely don’t have the correct order of lines in the pg_hba.conf file. If you read this PostgreSQL documentation link below, it says this error can be thrown if «no matching entry is found». However, that is NOT always true! Documentation is written by humans and humans make mistakes.
https://www.postgresql.org/docs/current/client-authentication-problems.html
The truth is that a line further up might take precedence, is qualifying and is forcing you to use a password stored in PostgreSQL rather than delegated authentication or some other method. If you are not specifying a password stored in PostgreSQL, then you do not need the LOGIN role attribute. Put a line at the very top of this list with your specific user, authentication protocol, network details and other criteria. Also, many may think that most computers use IPv4. Try IPv6 and you’ll be surprised. Once you know the very specific criteria of your issue and place a line at the top, then you have established the ONLY RELIABLE WAY to troubleshoot these pg_hba.conf issues without source code debugging!
Another helpful trick is to create a crapload of Server entries in pg_admin (SQL IDE for PostgreSQL) with all of your users and authentication protocols for testing. When you test different scenarios, you’ll instantly know which ones fail.
Also, whenever you change this file, restart the PostgreSQL service, before testing the user.
You’re welcome my friend.
For those of you who got this error and NONE of these answers helped, I may not have StackOverflow fish for you, but I’ll teach you how to fish!
You likely don’t have the correct order of lines in the pg_hba.conf file. If you read this PostgreSQL documentation link below, it says this error can be thrown if «no matching entry is found». However, that is NOT always true! Documentation is written by humans and humans make mistakes.
https://www.postgresql.org/docs/current/client-authentication-problems.html
The truth is that a line further up might take precedence, is qualifying and is forcing you to use a password stored in PostgreSQL rather than delegated authentication or some other method. If you are not specifying a password stored in PostgreSQL, then you do not need the LOGIN role attribute. Put a line at the very top of this list with your specific user, authentication protocol, network details and other criteria. Also, many may think that most computers use IPv4. Try IPv6 and you’ll be surprised. Once you know the very specific criteria of your issue and place a line at the top, then you have established the ONLY RELIABLE WAY to troubleshoot these pg_hba.conf issues without source code debugging!
Another helpful trick is to create a crapload of Server entries in pg_admin (SQL IDE for PostgreSQL) with all of your users and authentication protocols for testing. When you test different scenarios, you’ll instantly know which ones fail.
Also, whenever you change this file, restart the PostgreSQL service, before testing the user.
You’re welcome my friend.
Authentication failures and related problems generally manifest themselves through error messages like the following:
FATAL: no pg_hba.conf entry for host "123.123.123.123", user "andym", database "testdb"
This is what you are most likely to get if you succeed in contacting the server, but it does not want to talk to you. As the message suggests, the server refused the connection request because it found no matching entry in its pg_hba.conf
configuration file.
FATAL: password authentication failed for user "andym"
Messages like this indicate that you contacted the server, and it is willing to talk to you, but not until you pass the authorization method specified in the pg_hba.conf
file. Check the password you are providing, or check your Kerberos or ident software if the complaint mentions one of those authentication types.
FATAL: user "andym" does not exist
The indicated database user name was not found.
FATAL: database "testdb" does not exist
The database you are trying to connect to does not exist. Note that if you do not specify a database name, it defaults to the database user name, which might or might not be the right thing.
Tip
The server log might contain more information about an authentication failure than is reported to the client. If you are confused about the reason for a failure, check the server log.
Помогите разобраться народ !!!
Установлен PostgreSQL 9.6
Это моя настройка в pg_hba.conf
# TYPE DATABASE USER ADDRESS METHOD LOCAL ALL postgres md5 # "local" is for Unix domain socket connections only LOCAL ALL ALL md5 # IPv4 local connections: host ALL ALL 127.0.0.1/32 md5
Задан пароль пользователю «postgres» в Ubuntu
sudo echo -e «PAROLnPAROLn» | passwd postgres;
Пароль пользователю «postgres» в базе был задан:
sudo -U postgres psql -c «ALTER USER postgres WITH ENCRYPTED PASSWORD ‘PAROL’;»
Перезапускаю service postgresql restart
В результате, в логах:
2017-03-09 14:55:43 MSK [11185-1] СООБЩЕНИЕ: система БД была выключена: 2017-03-09 14:55:42 MSK 2017-03-09 14:55:43 MSK [11185-2] СООБЩЕНИЕ: Защита от наложения мультитранзакций сейчас включена 2017-03-09 14:55:43 MSK [11184-1] СООБЩЕНИЕ: система БД готова принимать подключения 2017-03-09 14:55:43 MSK [11189-1] СООБЩЕНИЕ: процесс запуска автоочистки создан 2017-03-09 14:55:44 MSK [11191-1] [н/д]@[н/д] СООБЩЕНИЕ: неполный стартовый пакет 2017-03-09 14:55:44 MSK [11194-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:44 MSK [11194-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:45 MSK [11197-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:45 MSK [11197-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:45 MSK [11200-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:45 MSK [11200-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:46 MSK [11203-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:46 MSK [11203-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:46 MSK [11206-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:46 MSK [11206-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:47 MSK [11209-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:47 MSK [11209-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:47 MSK [11212-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:47 MSK [11212-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:48 MSK [11215-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:48 MSK [11215-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:48 MSK [11218-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:48 MSK [11218-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:49 MSK [11221-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:49 MSK [11221-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:49 MSK [11224-1] postgres@postgres ВАЖНО: пользователь "postgres" не прошёл проверку подлинности (по паролю) 2017-03-09 14:55:49 MSK [11224-2] postgres@postgres ПОДРОБНОСТИ: Пароль не подходит для пользователя "postgres". Подключение соответствует строке 86 в pg_hba.conf: "local all postgres md5" 2017-03-09 14:55:49 MSK [11184-2] СООБЩЕНИЕ: получен запрос на "вежливое" выключение 2017-03-09 14:55:49 MSK [11189-2] СООБЩЕНИЕ: процесс запуска автоочистки завершается 2017-03-09 14:55:49 MSK [11186-1] СООБЩЕНИЕ: выключение 2017-03-09 14:55:49 MSK [11184-3] СООБЩЕНИЕ: система БД выключена
Solution of psql: FATAL: Peer authentication failed for user “postgres” (or any user)
The connection failed because by default psql
connects over UNIX sockets using peer
authentication, that requires the current UNIX user to have the same user name as psql
. So you will have to create the UNIX user postgres
and then login as postgres
or use sudo -u postgres psql database-name
for accessing the database (and psql
should not ask for a password).
If you cannot or do not want to create the UNIX user, like if you just want to connect to your database for ad hoc queries, forcing a socket connection using psql --host=localhost --dbname=database-name --username=postgres
(as pointed out by @meyerson answer) will solve your immediate problem.
But if you intend to force password authentication over Unix sockets instead of the peer method, try changing the following pg_hba.conf
* line:
from
# TYPE DATABASE USER ADDRESS METHOD
local all all peer
to
# TYPE DATABASE USER ADDRESS METHOD
local all all md5
-
peer
means it will trust the identity (authenticity) of UNIX user. So not asking for a password. -
md5
means it will always ask for a password, and validate it after hashing withMD5
. -
trust
means it will never ask for a password, and always trust any connection.
You can, of course, also create more specific rules for a specific database or user, with some users having peer
and others requiring passwords.
After changing
pg_hba.conf
you’ll need to restart PostgreSQL if it’s running. E.g.sudo service postgresql restart
Steps to change/create default postgres
user’s password:
trust
connection by adding inpg_hba.conf
file
local all postgres trust
- Restart postgresql service
sudo service postgresql restart
-
psql -U postgres
-
At the
postgres=#
prompt, change the user namepostgres
password:
ALTER USER postgres with password ‘new-password’;
- Revert the changes in
pg_hba.conf
file fromtrust
tomd5
and restartpostgresql
.
pg_hba.conf file location
The file pg_hba.conf
will most likely be at /etc/postgresql/9.x/main/pg_hba.conf
To check location of pg_hba.conf connect to postgres db using psql then type SHOW hba_file;
command.
After change pg_hba.conf file, you can execute SELECT pg_reload_conf();
or pg_ctl reload with superuser instead of restart postgresql service.
* Source
Вот еще несколько интересных статей: