Postgresql postgres user password windows

Сброс пароля в 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’;

Читайте также:  Обновление безопасности windows 10 kb4541338

Пароль пользователя postgres — как задать и изменить пароль

Команды по администрированию базами и пользователями выполняются от имени системного пользователя postgres

root может стать им выполнив su — postgres

Затем можно без пароля попасть в интерфейс БД psql

Или то же самое одной командой

Пользователь может создать базу

Затем добавить пользователя и задать для него пароль

=# create user appadmin with encrypted password ‘jdfh8jhtghnjkfrvhyu’;

После этого пользователю нужно дать права для работы с базой данных

=# grant all privileges on db1 mydb to appadmin;

Изменить пароль пользователя Postgres

Пользователя можно создавать и задавать ему пароль двумя раздельными командами

sudo -u postgres createuser anotheruser

Вторая служит для изменения паролей уже существующих пользователей, выполняется из консоли psql

=# alter user anotheruser with encrypted password ‘NEW_STRONG_PASSWORD’;

Непосредственно для системного пользователя postgres пароль не нужен, им может стать root выполнив su как показано ранее. Если нужна авторизация root может установить для postgres новый пароль

Затем пароль нужно ввести дважды, отображаться он не будет.

Пользователь appadmin — не системный, он существует только в postgresql.

Подключаться к базе из консоли от имени этого пользователя нужно указывая имя базы и ключ -W

psql -h myhost -d db1 -U appadmin -W

Последний ключ не обязателен, но без него в интерактивном режиме в некоторых версиях СУБД не будет запрашиваться пароль, пароль должен запрашиваться.

Про создание дампов баз данных Postgres и их загрузку.

What is the default password for Postgres

I have just install Postgres 9.3 on Windows 7. The installation completed successfully. It has never asked me to provide the password for postgres user.

The service postgresql-x64-9.3 is up and running. However, I cannot connect: I do not not know the password. I’ve found the following answer, but it did not help:

3 Answers 3

WARNING: trust means exactly that. Anyone who can connect to the PostgreSQL server can control it. If you set trust mode that allows superusers like user postgres (or all users) to connect, they get total control of your PostgreSQL and can probably run shell commands too. You should usually only use it to change the password then restore the configuration back to the auth mode you were using before.

If you used an unattended installer script, the password will be in the script or associated config file.

Otherwise, treat it the same as if you lost/forgot the password rather than never knowing it:

  • Edit pg_hba.conf , setting the auth mode to trust instead of the default md5
  • In the Services control panel restart the PostgreSQL service
  • Connect with psql or PgAdmin or whatever
  • ALTER USER postgres PASSWORD ‘mynewpassword’;
  • Edit pg_hba.conf again and set the auth mode back to md5
  • Restart PostgreSQL again

pg_hba.conf is in your data directory. By default it’ll be %PROGRAMFILES%\PostgreSQL\9.3\data .

Читайте также:  Ssd ���������� mac os

To edit it you’ll have to use the security tab to give yourself read/write permissions (via a UAC prompt). This might require you to set yourself as the owner of the file.

On unix systems it’s more secure to prepend a

Forgotten PostgreSQL Windows password

This morning I’ve been trying to connect the PostgreSQL database on my Windows 7 Professional desktop.

The default value is ‘postgres’, but sure enough I forgot what password I used when I originally installed it.

I have googled and found a post related to resetting your password. I followed the steps, but the end result is a bit different then mentioned in the post. I used—

to reset the password for my database but instead of a success message I am getting:

«System error 5 has occurred. Access is denied.»

system error. How do I avoid this error and reset the password?

3 Answers 3

(Note: Not much of this is relevant to readers using PostgreSQL 9.2 or above from the EDB installers, which now have a greatly simplified default install using the NETWORK SERVICE , though you can still configure other accounts).

I have used net user postgres postgres to reset the password for my database but instead of a success message I am getting «System error 5 has occurred. Access is denied.»

You’ve reset (or tried to reset) the service account password. PostgreSQL won’t run as Administrator for security reasons and the installer generally sets it up with a «postgres» user account in PostgreSQL 9.1 and older 1 . On Windows you can’t start a service as a user without saving the password of the user in the registry, so that’s what the installer does.

If you change the password for the Windows user account postgres , the PostgreSQL service can no longer start. So don’t do that, you’ll have to fix the service configuration to store the updated password.

Thankfully I think another mistake prevented you from doing that. It looks like you’re probably running your command prompt without using «Run as Administrator» on an unprivileged Windows user account or a machine with UAC, so it isn’t running with the access permissions required to change the password for the postgres user.

Before you try to change that password, make sure it’s really what you want to do. What’s the problem you’re trying to solve here? Are you attempting to install a database update or something else that’s asking for the password for the postgres Windows user?

Most likely you’re just trying to log in to the database. For that, you use the (unfortunately completely unrelated) password stored in the database its self. Since you’ve lost/forgotten it you’ll have to reset it:

  • Find your pg_hba.conf , usually in C:\Program Files\PostgreSQL\9.1\data\pg_hba.conf
  • If necessary, set the permissions on it so that you can modify it; your user account might not be able to do so until you use the security tab in the properties dialog to give yourself that right by using an admin override. Alternately, find notepad / notepad++ in your start menu, right click, choose «Run as administrator», then use File->Open to open pg_hba.conf that way.

Edit it to set the «host» line for user «postgres» on host «127.0.0.1/32» to «trust». You can add the line if it isn’t there; just insert:

before any other lines. (You can ignore comments, lines beginning with # ).

Restart the PostgreSQL service from the Services control panel (start->run-> services.msc )

  • connect using psql or PgAdmin-III or whatever you prefer
  • ALTER USER postgres PASSWORD ‘postgres’
  • remove the line you added to pg_hba.conf or change it back
  • restart PostgreSQL again.
  • Читайте также:  Где найти сочетания клавиш windows

    1. 9.2 now uses the NETWORKSERVICE account, which doesn’t require a password, so this problem goes away.

    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

    Оцените статью