как поменять пароль в postgresql linux
Пароль пользователя postgres — как задать и изменить пароль
Команды по администрированию базами и пользователями выполняются от имени системного пользователя postgres
root может стать им выполнив su — postgres
Затем можно без пароля попасть в интерфейс БД psql
Или то же самое одной командой
Пользователь может создать базу
Затем добавить пользователя и задать для него пароль
=# create user appadmin with encrypted password ‘jdfh8jhtghnjkfrvhyu’;
После этого пользователю нужно дать права для работы с базой данных
=# grant all privileges on db1 mydb to appadmin;
Изменить пароль пользователя Postgres
Пользователя можно создавать и задавать ему пароль двумя раздельными командами
Вторая служит для изменения паролей уже существующих пользователей, выполняется из консоли psql
=# alter user anotheruser with encrypted password ‘NEW_STRONG_PASSWORD’;
Непосредственно для системного пользователя postgres пароль не нужен, им может стать root выполнив su как показано ранее. Если нужна авторизация root может установить для postgres новый пароль
Затем пароль нужно ввести дважды, отображаться он не будет.
Пользователь appadmin — не системный, он существует только в postgresql.
Подключаться к базе из консоли от имени этого пользователя нужно указывая имя базы и ключ -W
Последний ключ не обязателен, но без него в интерактивном режиме в некоторых версиях СУБД не будет запрашиваться пароль, пароль должен запрашиваться.
Про создание дампов баз данных Postgres и их загрузку.
Как изменить пароль пользователя 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. Мне нужно выполнить следующие шаги
затем вы переключаетесь обратно в root, выполнив exit и настроить свой pg_hba.conf (мое-в /etc/postgresql/10/main/pg_hba.conf ), убедившись, что у вас есть следующие линия
local all postgres md5
введите новый пароль для этого пользователя, а затем подтвердите его. Если вы не помните пароль, и вы хотите его изменить, вы можете войти в систему как postgres, а затем использовать это:
Как работать с пользователями в PostgreSQL
Часть нижеописанных операций нужно выполнять в командной оболочке PostgreSQL. Она может быть запущена от пользователя postgres — чтобы войти в систему от данного пользователя, вводим:
* если система выдаст ошибку, связанную с нехваткой прав, сначала повышаем привилегии командой sudo su или su.
Теперь запускаем командную оболочку PostgreSQL:
* в данном примере, вход выполняется от учетной записи postgres к шаблонной базе template1.
Для просмотра всех пользователей СУБД:
=# select * from pg_user;
Создание нового пользователя
Для того, чтобы была возможность подключения к СУБД PostgreSQL от нового пользователя, необходимо создать данного пользователя, назначить ему права, выполнить настройку файла pg_hba.conf.
1. Создание пользователя
а) Добавление новой роли (пользователя) из оболочки SQL:
=# CREATE USER dmosk WITH PASSWORD ‘myPassword’;
* в примере создана роль dmosk с паролем myPassword.
б) Добавление новой роли (пользователя) из командной строки Linux:
2. Назначение прав на использование базы данных
Даем права на базу командой:
=# GRANT ALL PRIVILEGES ON DATABASE «database1» to dmosk;
Теперь подключаемся к базе, к которой хотим дать доступ:
* в примере подсоединимся к базе с названием database1.
а) Так мы добавим все права на использование всех таблиц в базе database1 учетной записи dmosk:
database1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO «dmosk»;
* в большинстве случаев, используется схема по умолчанию public. Но администратор может создать новую схему. Это нужно учитывать при назначении прав.
б) Также можно дать доступ к базе для определенных таблиц:
database1=# GRANT ALL PRIVILEGES ON TABLE table1 IN SCHEMA public TO «dmosk»;
* в данном примере мы даем права на таблицу table1.
Выходим из SQL-оболочки:
3. Настройка файла pg_hba.conf
Для возможности подключиться к СУБД от созданного пользователя, необходимо проверить настройки прав в конфигурационном файле pg_hba.conf.
Для начала смотрим путь расположения данных для PostgreSQL:
В ответ мы получим, что-то на подобие:
* в данном примере /var/lib/pgsql/9.6/data/ — путь расположения конфигурационных файлов.
Добавляем права на подключение нашему созданному пользователю:
.
# IPv4 local connections:
host all dmosk 127.0.0.1/32 md5
.
* в данном примере мы разрешили подключаться пользователю dmosk ко всем базам на сервере (all) от узла 127.0.0.1 (localhost) с требованием пароля (md5).
* необходимо, чтобы данная строка была выше строки, которая прописана по умолчанию
host all all 127.0.0.1/32 ident.
После перезапускаем службу:
systemctl restart postgresql-9.6
* в данном примере установлен postgresql версии 9.6, для разных версий на разных операционных системах команды для перезапуска сервиса могут быть разные.
4. Проверка
Для теста пробуем подключиться к Postgre с помощью созданного пользователя:
Настройка прав доступа к базе с помощью групп
Сначала создадим групповую роль:
=# CREATE ROLE «myRole» NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION;
* данной командой создана группа myRole с минимальными правами.
Теперь добавим ранее созданного пользователя dmosk в эту группу:
=# GRANT «myRole» TO dmosk;
Подключимся к базе данных, для которой хотим настроить права
и предоставим все права для группы myRole всем таблицам базы database1
database1=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO GROUP «myRole»;
Редактирование пользователя
1. Смена пароля
Рассмотрим несколько примеров смены пароля пользователя.
=# ALTER USER postgres PASSWORD ‘password’
* в данном примере мы зададим пароль password для пользователя postgres.
С запросов ввода пароля:
* после ввода данной команды система потребует дважды ввести пароль для пользователя (в нашем примере, postgres).
Из командной строки Linux:
* по сути, мы выполняем также запрос в оболочке sql.
Удаление пользователей и групп
Удаление пользователя выполняется следующей командой:
database1=# REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM «dmosk»;
* обратите внимание, данный запрос отличается от предоставления прав двумя моментами: 1) вместо GRANT пишем REVOKE; 2) вместо TO «dmosk» пишем FROM «dmosk»;
Назначение особых прав пользователям PostgreSQL
Помимо ALL PRIVILEGES можно выдавать права на особые операции, например:
=# GRANT SELECT, UPDATE, INSERT ON ALL TABLES IN SCHEMA public TO «dmosk»;
* команда позволит выдать права на получение данных, их обновление и добавление. Другие операции, например, удаление будут запрещены для пользователя dmosk.
Назначение прав для определенной таблицы:
database1=# GRANT ALL PRIVILEGES ON table_users TO «dmosk»;
* в данном примере мы предоставим все права на таблицу table_users в базе данных database1;
Учетная запись для резервного копирования
Для выполнения резервного копирования лучше всего подключаться к базе с минимальными привилегиями.
Сначала создаем роль, которую будем использовать для выполнения резервного копирования:
=# CREATE USER bkpuser WITH PASSWORD ‘bkppasswd’;
* мы создадим учетную запись bkpuser с паролем bkppasswd.
Предоставляем права на подключения к базе
=# GRANT CONNECT ON DATABASE database TO bkpuser;
* в данном примере к базе database.
Подключаемся к базе (в нашем примере database):
Даем права на все последовательности в схеме:
=# GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO bkpuser;
* мы дали права для схемы public. Это схема является схемой по умолчанию, но в вашем случае она может быть другой. В таком случае, подставляем свое значение.
Графический интерфейс
Иногда проще воспользоваться программой для выставления прав и работы с PostgreSQL. Могу посоветовать приложение pgAdmin. Оно позволит в оконном режиме не только создать и удалить пользователей, но и полноценно работать с СУБД.
How to change PostgreSQL user password?
How do I change the password for PostgreSQL user?
22 Answers 22
To login without a password:
To reset the password if you have forgotten:
To change the the postgres user’s password follow this steps
If that does not work, reconfigure authentication by editing /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.
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
To request a new password for the postgres user (without showing it in the command):
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.
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
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 )
change password to postgres for user postgres
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):
PostgreSQL: Resetting password of PostgreSQL on Ubuntu [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
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:
(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).
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:
Keep in mind that you need to type postgres with a single S at the end
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.