- Сброс пароля в PostgreSQL
- 5 thoughts on “ Сброс пароля в PostgreSQL ”
- Windows pgAdmin и пароли PostgreSQL
- Решение
- Linux и Windows: помощь админам и пользователям
- Администрируем и настраиваем Windows, Linux.
- 15 команд для управления PostgreSQL
- 1. Как изменить root пароль в PostgreSQL?
- 2. Как установить PostgreSQL в автозапуск?
- 3. Проверяем состояние сервера
- 4. Как запустить, остановить, перезапустить PostgreSQL?
- 5. Как посмотреть какая версия PostgreSQL запущена?
- 5. Как создать пользователя в PostgreSQL?
- 7. Получаем список всех баз в Postgresql?
- 8. Как удалить базу в PostgreSQL?
- 9. Пользуемя встроенным хелпом к командам
- 10. Как получить список всех таблиц в базе данный в Postgresql?
- 11. Как узнать время выполнения запроса?
- 12. Как бэкапить и восстанавливать базы и таблицы в PostgreSQL?
- 14. Как отредактировать запрос к PostgreSQL в редакторе?
- 15. Где я могу найти файл истории postgreSQL?
- Комментариев: 10
- I forgot the password I entered during postgres installation
- 15 Answers 15
- PostgreSQL: How to change PostgreSQL user password?
- 20 Answers 20
Сброс пароля в 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’;
Windows pgAdmin и пароли PostgreSQL
Добрый день, подскажите плиииз! Запутался окончательно!
Скачал с оф-сайта и установил Postgres9 на Windows. При установке меня заставили ввести целых 2 пароля. придумал сложные и ввел!
Что я сделал не так.
. планирую работать с Ps на линуксе, но разобраться с доступами хочу на винде и «графических» редакторах SQL-скриптов
Проблема с pgAdmin при установке PostgreSQL 11
Здравствуйте. Устанавливаю PostgreSQL 11. Сначала всё идёт как положено, установка внешне.
Запрос на вывод из базы PostgreSQL, PgAdmin III)
Здравствуйте, пытаюсь подключиться к базе и получить все данные по запросу, но ничего не.
Пароли в Windows 7
Всем привет. скажу сразу хакер с меня ни какой. Моя проблема- сменил пароль в майле и вскоре.
Разные пароли на wi-fi в Windows 7 и 8
У меня есть роутер (маршрутизатор) Zyxel Keenetic 4G. У него на этикетке крышке написан пин-код для.
Решение
В 1С (бухгалтерская прога) можно базу подключить к постгресу (ожидается дикий прирост скорости по сравнению с не кешированным файловым хранилищем). Обычно все работают в win-терминалах на ЭТОМ-же компе (один приличный сервер на фирму в 10-20 компов). Далеко не каждый 1Сник умеет (и имеет желание) кроме 1С еще и заниматься линуксом.
А я пытался разобраться с принципами «ролей», чтобы понять как на линукс-сервере организовать «разграничение доступов». Хотел потренироваться сначала на локальной базе с «графическим» редактором/вювером pgAdmin и неожиданно «доступ не урезается». к серверной не получилось подключить pgAmdin
пробую разобраться с /etc/postgresql/9.1/main/pg_hba.conf
но пока безуспешно.
скопипастить через терминал не получается. буду набирать:
все остальное заремарено.
где-то на форуме предложили добавить:
после каждой модификации пробовал перегрузить через
То есть вы в операционной системе работаете в каком-то своем окружении под пользователем myuser, даете команду оболочке от имени пользователя postgres запустить команду коннект к базе данных через доменный сокет, который расположен в директории /var/lib/postgresql. Пользователь базы данных будет по умолчанию postgres, база данных, к которой подключаетесь, будет по умолчанию тоже postgres.
2 строчка)
local = понятно
all = понятно
all = разрешает доступ всем пользователям (которые созданы в СУБД командой CREATE ROLE/USER или утилитой createuser)
md5 = разрешает доступ, только если пользователь прошел проверку своего пароля, указанного при соединении с базой данных (то есть обычная проверка по паролю)
Все вместе означает, что эта строчка авторизует коннекты к базе, которые делаются примерно такой командой
В итоге получаем, что Ваш текущий pg_hba.conf разрешает соединения ТОЛЬКО внутри данного сервера всякими разными способами (через unix-сокеты, через tcp/ip v4 и v6).
Чтобы добавить коннект извне (из Интернета) надо добавить примерно следующую строчку
5) строчка
host = понятно
all = понятно
all = понятно
1.2.3.4/24 = IP-адрес и префикс (или плюс маска) того адреса, С КОТОРОГО вы будете соединяться с базой данных (это адрес вашего провайдера). Можно указать 0.0.0.0/0, тогда будет с любого адрес (что может быть НЕБЕЗОПАСНЫМ. ).
Вместе с добавлением этой строчки нужно убедиться, что в файле postgresql.conf
параметры listen_addresses и port выставлены верно
хотя бы так
listen_addresses=’*’
port = 5432
Если я где-то ошибся, верную информацию всегда можно найти в оф. документации
Все эти компоненты окружения операционной системы должны быть учтены при поиске проблем подключения к базе данных. Естественно, когда речь идет о сервере на реальном адресе, простое выключение файрволов и прочих служб безопасности чревато разными проблемами в будущем.
Linux и Windows: помощь админам и пользователям
Администрируем и настраиваем Windows, Linux.
15 команд для управления PostgreSQL
В этой статье я покажу 15 наиболее полезных команд для управления postgreSQL.
1. Как изменить root пароль в PostgreSQL?
Изменение пароля для обычного пользователя происходит таким же образом. Пользователь root может поменять пароль любому пользователю.
2. Как установить PostgreSQL в автозапуск?
3. Проверяем состояние сервера
4. Как запустить, остановить, перезапустить PostgreSQL?
5. Как посмотреть какая версия PostgreSQL запущена?
5. Как создать пользователя в PostgreSQL?
Для этого существуют два метода..
Метод 1: Создаем пользователя в через PSQL шелл, командой CREATE USER.
Метод 2: Создаем пользователя в через шелл команду createuser.
Для этого существует 2 метода.
Метод 1: Создаем базу черезе PSQL шелл, с помощью команды CREATE DATABASE.
Метод 2: Используем команду createdb.
7. Получаем список всех баз в Postgresql?
8. Как удалить базу в PostgreSQL?
9. Пользуемя встроенным хелпом к командам
Команда \? отобразит строку помощи для команда PSQL. \h CREATE покажет хелп для всех команд который начинаются с CREATE.
10. Как получить список всех таблиц в базе данный в Postgresql?
Для пустой базы вы получите сообщение “No relations found.”
11. Как узнать время выполнения запроса?
# \timing — после выполения данной команды каждый последующий запрос будет показывать время выполнения.
12. Как бэкапить и восстанавливать базы и таблицы в PostgreSQL?
Этот вопрос довольно велик и я опубликую его позднее отдельной статьей.
Для того чтобы получить список доступных функций, скажите \df+
14. Как отредактировать запрос к PostgreSQL в редакторе?
\e откроет редактор, в котором вы можете отредактировать запрос и сохранить его.
15. Где я могу найти файл истории postgreSQL?
/.bash_history, postgreSQL хранит все sql команды в файле
Разное
Лучшие выставочные стенды в Москве. Отличное качество выполнения, невысокие цены.
Курьерская служба, доставка по Москве и Московской области, срочная доставка, рассылки писем, счетов, журналов
Комментариев: 10
Очень хорошая статья, люблю живые примеры
С удовольствием прочитаю статью про бэкапы в postgresql
Спасибо, подборка очень выручила когда пришлось аврально разбираться, как с postgesql работать.
И да, примерах с кодом у меня повылазили тэги , лучше бы их убрать, читать мешает.
Не получается :((( команда postgresql status говорит что он остановлен.
Странно. Я пользуюсь Ruby On Rails и у меня иногда удаляется база данных. Причём, непонятно почему.
Как посмотреть какая версия PostgreSQL запущена?
Полная ахинея. Нужно быть придурком чтобы таким образом определять версию постгреса,
Автор просто скопипастил текст «статьи» откуда-то даже не удосужившись удалить html-тэги.
Также хочется отметить, что способов запуска/остановки процессов в разных системах минимум 2, тут выделен самый неудачный в плане длинного пути и отсутствия стандартизации запуска процессов.
Есть команда показывающая место расположения базы данных:
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
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.
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
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:
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
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.
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
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.
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
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.
With that said here is how we can alter a user’s password by building an md5 of the password.
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:
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):