Восстановить пароль postgres windows

Забыли пароль PostgreSQL для Windows

Сегодня утром я пытаюсь подключить базу данных PostgreSQL на рабочем столе Windows 7 Professional.

Значение по умолчанию — «postgres», но, конечно же, я забыл, какой пароль я использовал, когда я его первоначально установил.

У меня есть googled и найдено сообщение , связанное с сбросом ваш пароль. Я последовал за этими шагами, но конечный результат немного отличается от упомянутого в сообщении. Я использовал «

, чтобы сбросить пароль для моей базы данных, но вместо успешного сообщения, которое я получаю:

«Произошла системная ошибка 5. Доступ запрещен.»

системная ошибка. Как избежать этой ошибки и сбросить пароль?

3 ответа

(Примечание. Это не очень важно для читателей, использующих PostgreSQL 9.2 или выше, из установщиков EDB, которые теперь имеют значительно упрощенную установку по умолчанию , используя NETWORK SERVICE , хотя вы можете настроить другие учетные записи) .

Я использовал net user postgres postgres для сброса пароля для моей базы данных, но вместо успешного сообщения я получаю «System error 5 has occurred. Access is denied.»

Сброс (или попытка сброса) пароля учетной записи службы. PostgreSQL не запускается в качестве администратора по соображениям безопасности, и установщик обычно устанавливает его с учетной записью пользователя postgres в PostgreSQL 9.1 и старше 1 . В Windows вы не можете запустить службу как пользователь, не сохраняя пароль пользователя в реестре, так что это делает установщик.

Если вы измените пароль для учетной записи пользователя Windows postgres , служба PostgreSQL больше не сможет запускаться. Так что не делайте этого, вам нужно будет исправить конфигурацию службы, чтобы сохранить обновленный пароль.

К счастью, я думаю, что другая ошибка помешала вам сделать это. Похоже, что вы, вероятно, запускаете свою командную строку, не используя «Запуск от имени администратора» в непривилегированной учетной записи пользователя Windows или машине с UAC, поэтому она не работает с правами доступа, необходимыми для изменения пароля для postgres .

Прежде чем пытаться изменить этот пароль, убедитесь, что это действительно то, что вы хотите сделать. В чем проблема, которую вы пытаетесь решить здесь? Вы пытаетесь установить обновление базы данных или что-то еще, запрашивающее пароль для пользователя postgres Windows?

Скорее всего, вы просто пытаетесь войти в базу данных. Для этого вы используете (к сожалению, полностью несвязанный) пароль, хранящийся в базе данных сам. Поскольку вы потеряли /забыли, вам придется его сбросить:

  • Найдите pg_hba.conf , обычно в C:\Program Files\PostgreSQL\9.1\data\pg_hba.conf
  • При необходимости установите для него разрешения, чтобы вы могли его изменить; ваша учетная запись пользователя может оказаться неспособной сделать это, пока вы не включите вкладку безопасности в диалоговом окне свойств, чтобы получить это право, используя переопределение администратора. В качестве альтернативы найдите в меню «Пуск» блокнот /блокнот ++, выберите «Запуск от имени администратора», затем нажмите «Файл» и «Открыть», чтобы открыть pg_hba.conf ).

Отредактируйте его, чтобы установить строку «хозяина» для пользователя «postgres» на хосте «127.0.0.1/32» для «доверия». Вы можете добавить строку, если ее нет; просто вставьте:

перед любые другие строки. (Вы можете игнорировать комментарии, строки, начинающиеся с # ).

Перезапустите службу PostgreSQL с панели управления Services (start-> run-> services.msc )

  • подключиться с помощью psql или PgAdmin-III или любого другого, что вы предпочитаете
  • ALTER USER postgres PASSWORD ‘postgres’
  • удалите строку, добавленную в pg_hba.conf , или измените ее.
  • снова перезапустите PostgreSQL.
  • 1. 9.2 теперь использует учетную запись NETWORKSERVICE , которая не требует пароля, поэтому эта проблема уходит .

    Вам нужно различать пользователя вашей системы (Windows), называемого «postgres», и пользователя базы данных с тем же именем.

    Читайте также:  Octave установить пакет windows

    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

    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

    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) , exepct replication section if you don’t have any it has to be changed as follow ,no MD5 or Peer autehication should be present.

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

    Читайте также:  Windows 10 неполадки с клавиатурой

    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

    When connecting to postgres from command line, don’t forget to add -h localhost as command line parameter. If not, postgres 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 :

    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 :

    Then, using pgAdmin III, I logged in using no password and changed user postgres’ password by going to File -> Change Password

    Just a note, on Linux You can simply run sudo su — postgres to become the postgres user and from there change what required using psql.

    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.

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

    Go to your postgres installation location, and search for pg_hba.conf , you will find it in ..\postgres\data\pg_hba.conf

    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

    Читайте также:  Как устанавливать windows live usb

    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

    Close this file

    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: psql -U postgres -h localhost

    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:

    If it says user does not exist then instead of ALTER use CREATE .

    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

    The file .pgpass in a user’s home directory or the file referenced by PGPASSFILE can contain passwords to be used if the connection requires a password (and no password has been specified otherwise). On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user’s profile).

    This file should contain lines of the following format:

    (You can add a reminder comment to the file by copying the line above and preceding it with #.) Each of the first four fields can be a literal value, or *, which matches anything. The password field from the first line that matches the current connection parameters will be used. (Therefore, put more-specific entries first when you are using wildcards.) If an entry needs to contain : or \, escape this character with . A host name of localhost matches both TCP (host name localhost) and Unix domain socket (pghost empty or the default socket directory) connections coming from the local machine. In a standby server, a database name of replication matches streaming replication connections made to the master server. The database field is of limited usefulness because users have the same password for all databases in the same cluster.

    On Unix systems, the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600

    /.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.

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