Postgres linux user password

Пароль пользователя 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 и их загрузку.

Источник

How to Set the Default User Password in PostgreSQL

Firstly, it is important to understand that for most Unix distributions, the default Postgres user neither requires nor uses a password for authentication. Instead, depending how Postgres was originally installed and what version you are using, the default authentication method will either be ident or peer .

ident authentication uses the operating system’s identification server running at TCP port 113 to verify the user’s credentials.

peer authentication on the other hand, is used for local connections and verifies that the logged in username of the operating system matches the username for the Postgres database.

Login and Connect as Default User

For most systems, the default Postgres user is postgres and a password is not required for authentication. Thus, to add a password, we must first login and connect as the postgres user.

Читайте также:  Delphi add linux platform

If you successfully connected and are viewing the psql prompt, jump down to the Changing the Password section.

If you received an error stating that the database “postgres” doesn’t exist, try connecting to the template1 database instead and if successful, continue to Changing the Password.

Authentication Error

If you receive an authentication error when attempting to connect to the psql client, you may need to alter the Postgres authentication config file (pg_hfa.conf).

Open the config file, typically located at /etc/postgresql/#.#/main/pg_hba.conf , where #.# is the Postgres version you are using:

The auth config file is a list of authentication rules. Scroll down the file until you locate the first line displaying the postgres user in the third column (if such a line exists). Uncomment the line if necessary (remove the semicolon), or otherwise if the line is missing entirely, add the following line to the top of the file and save your changes:

This authentication rule simply tells Postgres that for local connections established to all databases for the user postgres , authenticate using the peer protocol.

Note: Some older versions of Postgres prefer the default authentication method of ident, but most modern installations will utilize peer as specified above instead. You may need to test both if your results differ.

Now with your configuration file updated, repeat the steps in the Login and Connect as Default User section to try to connect to as the default postgres user. Once successful, proceed with changing the password.

Changing the Password

With a connection now established to Postgres at the psql prompt, issue the ALTER USER command to change the password for the postgres user:

If successful, Postgres will output a confirmation of ALTER ROLE as seen above.

Finally, exit the psql client by using the \q command.

You’re all done. The default postgres user now has a password associated with the account for use in your other applications.

Источник

PostgreSQL: Resetting password of PostgreSQL on Ubuntu [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed 8 years ago .

In Ubuntu, I installed PostgreSQL database and created a superuser for the server.

If I forgot the password of the postgresql superuser, how can I reset it (the password) for that user?

I tried uninstalling it and then installing it again but the previously created superuser is retained.

1 Answer 1

Assuming you’re the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

Читайте также:  Usb камера эндоскоп драйвер для windows

(About the file location: 9.1 is the major postgres version and main the name of your «cluster». It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload .

Then you should be able to log in with psql as the postgres superuser with this shell command:

Once inside psql, issue the SQL command:

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh , the command would be:

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER . PASSWORD :

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Источник

What is the Default Password for PostgreSQL?

When connecting to PostgreSQL on Linux for the first time many admins have questions, especially if those admins are from the MySQL world. By default, when PostgreSQL is installed, a postgres user is also added.

If you run the command:

… you’ll see the postgres user.

The first question many ask is, “What is the default password for the user postgres?” The answer is easy… there isn’t a default password. The default authentication mode for PostgreSQL is set to ident.

… you’ll see the authentication mode is ident.

# IPv4 local connections:
host all all 127.0.0.1/32 ident
# IPv6 local connections:
host all all ::1/128 ident

What is the ident authentication method? Well, it works by taking the OS username you’re operating as and comparing it with the allowed database username(s). There is optional username mapping.

This means that in order to connect to PostgreSQL you must be logged in as the correct OS user. In this case, we are logged into the server as root. When we try to connect to PostgreSQL:

… we get the following error:

psql: FATAL: role «root» does not exist

However, if we become the default PostgreSQL user, postgres:

… then attempt a connection to PostgreSQL:

… I get the correct, valid response!

Читайте также:  Samba анонимный доступ windows

psql (9.3.9)
Type «help» for help.

Is your Cloud VPS slowing down your PostgreSQL instance? Liquid Web’s Dedicated Servers is the solution. Liquid Web’s server outmatches the competition on performance and support. Check out how our VPS server or Dedicated Servers can skyrocket your site’s performance.

Источник

Как изменить пароль пользователя PostgreSQL?

Как изменить пароль для пользователя PostgreSQL?

11 ответов

для пароля меньше логина:

чтобы сбросить пароль, если вы забыли:

затем бросить psql :

если это не помогает, настройте проверку подлинности.

редактировать /etc/postgresql/9.1/main/pg_hba.conf (путь будет отличаться) и меняться:

вы можете и должны зашифровать пароль пользователя:

Я считаю, что лучший способ изменить пароль, просто использовать:

в консоли Postgres.

при указании незашифрованного пароля с помощью эта команда. Пароль будет передан на сервер в открытый текст, и он также может быть зарегистрирован в истории команд клиента или журнал сервера. psql содержит команду \password, которую можно использовать изменение пароля роли без выставляя пароль.

изменить пароль с помощью командной строки в Ubuntu, используйте:

перейдите в конфигурацию Postgresql и отредактируйте pg_hba.conf

sudo vim /etc/postgresql/9.3/main/pg_hba.conf

затем измените эту строку :

затем перезапустите службу PostgreSQL с помощью команды SUDO, затем

теперь вы будете введены и увидите терминал Postgresql

и введите новый пароль Пользователь Postgres по умолчанию, после успешной смены пароля снова перейдите в pg_hba.conf и вернуть изменение в «md5»

теперь вы войдете в систему как

С новым паролем.

Дайте мне знать, если вы обнаружите какие-либо проблемы в нем.

Это был первый результат в Google, когда я искал как переименовать пользователя, так:

несколько других команд, полезных для управления пользователями:

переместить пользователя в другую группу

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

Не забудьте изменить это обратно на пароль или md5

запросить новый пароль postgres пользователь (не показывая его в команде):

для моего случая на Ubuntu 14.04 установлен с postgres 10.3. Мне нужно выполнить следующие шаги

  • su — postgres к postgres
  • psql для входа в оболочку postgres
  • \password введите пароль
  • \q чтобы выйти из сеанса оболочки

затем вы переключаетесь обратно в root, выполнив exit и настроить свой pg_hba.conf (мое-в /etc/postgresql/10/main/pg_hba.conf ), убедившись, что у вас есть следующие линия

local all postgres md5

  • перезапустите службу postgres с помощью service postgresql restart
  • теперь переключаемся на postgres user и снова введите оболочку postgres. Он предложит вам пароль.
  • введите новый пароль для этого пользователя, а затем подтвердите его. Если вы не помните пароль, и вы хотите его изменить, вы можете войти в систему как postgres, а затем использовать это:

    Источник

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