Psql как изменить пароль пользователя

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

На чтение 5 мин Просмотров 10.6к. Опубликовано 17.12.2021

Это необходимо для защиты ваших данных и информации от любых вторжений, которые могут быть выполнены с помощью паролей для ваших пользователей. Пароли используются для защиты ваших данных от любых неудач в будущем, чтобы ни один другой пользователь, кроме вас, не мог войти в систему. Они необходимы, когда вы вошли в систему или вошли в определенную систему для целей аутентификации.

В PostgreSQL, когда вы однажды установили программу установки, она попросит вас установить пароль для базы данных по умолчанию, то есть «postgres». Вы также можете позже создать собственного пользователя в PostgreSQL и установить для него пароль. Но что, если возникает необходимость изменить пароль для управления базой данных или административных функций, и в вашей голове возникает вопрос, как и откуда вы можете изменить пароль? Не о чем беспокоиться, потому что эта статья будет специально посвящена ответу на ваш вопрос с помощью простых и различных способов изменения паролей пользователей в PostgreSQL. Это руководство поможет вам изменить пароли пользователей и четко определить каждый шаг для вашего лучшего понимания.

Различные режимы изменения пароля пользователя:

Вы можете изменить пароли пользователей двумя разными способами в PostgreSQL. В обоих методах вы можете создать и установить пароль, а также изменить его. Вот эти два метода:

  • Используя pgAdmin.
  • Используя psql.

Содержание

  1. Шаги по изменению пароля с помощью pgAdmin
  2. Изменить пароль через psql
  3. Измените пароль с помощью операторов ALTER ROLE
  4. Измените пароль с помощью мета-команды
  5. Вывод

Шаги по изменению пароля с помощью pgAdmin

Когда вы открываете PostgreSQL, перед вами отображается примерно следующее:

вы открываете PostgreSQL, перед вами отображается

С левой стороны можно увидеть меню навигации, в котором определены «Логин / Групповые роли». При нажатии на нее появляется выпадающий список.

левой стороны можно увидеть меню навигации, в котором определены

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

Давайте сначала создадим имя пользователя и установим пароль для этого имени пользователя, а затем мы изменим пароль. Чтобы создать имя пользователя, нажмите «Логин / Роли группы» и нажмите «Создать» логин или групповую роль. Здесь мы создадим роль входа в базу данных с желаемыми ролями.

Давайте сначала создадим имя пользователя и установим пароль

После нажатия на «Логин / Групповые роли» появится следующее:

После нажатия на «Логин 

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

В поле имени вы можете указать любое имя, какое захотите

В «Привилегиях» определите свои роли пользователей и в конце сохраните данные для входа в систему.

«Привилегиях» определите свои роли пользователей и

Теперь вы создали пользователя и можете просто изменить пароль, щелкнув свое имя пользователя, а затем «Свойства» на боковой панели навигации следующим образом:

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

В окне «Свойства» откроется тот же экран, на котором вы создали имя пользователя для входа в систему. Здесь в «Паролях» вы можете ввести свой новый пароль и сохранить его в конце.

В окне «Свойства» откроется тот же экран, на котором вы

В поле «Пароли» повторно введите новый пароль, и ваш пароль будет изменен на имя пользователя «saeed_raza».

Изменить пароль через psql

В оболочке SQL (psql) вы также можете изменить пароль двумя способами:

  • Использование операторов ALTER ROLE.
  • Использование мета-команд.

Измените пароль с помощью операторов ALTER ROLE

Операторы ALTER ROLE используются для изменения паролей пользователя в PostgreSQL. Вот основной синтаксис для использования операторов ALTER Role в вашей базе данных:

Операторы ALTER ROLE используются для изменения паролей

В приведенном выше заявлении укажите имя пользователя вместо «имени пользователя», пароль которого вы хотите изменить. Затем введите новый пароль вместо new_password, чтобы изменить пароль. Предложение VALID UNTIL не является обязательным; он используется для ввода периода времени, в течение которого вы хотите, чтобы пароль действовал после указанной даты или времени, когда истечет срок действия пароля.

Ниже приведена иллюстрация изменения пароля пользователя «saeed_raza» на новый пароль «data».

ALTER ROLE saeed_raza WITH PASSWORD ‘data’;

Команда ALTER ROLE после оператора SQL обеспечивает изменение пароля в базе данных.

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

ALTER ROLE saeed_raza WITH PASSWORD ‘defined’

VALID UNTIL ‘March 30, 2022’ ;

Я изменил пароль с «данные» на «определенный» для имени пользователя «saeed_raza» и упомянул дату, когда пароль для этого имени пользователя станет действительным, а именно «30 марта 2022 года». Срок действия пароля истечет до этой даты, но если вы не добавите в оператор предложение VALID UNTIL, пароль будет действителен в течение всего времени жизни.

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

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

Эта команда отобразит все списки ролей, которые присутствуют

В приведенных выше выходных данных вы можете ясно видеть, что в имени роли «saeed_raza» пароль действителен до 30 марта 2022 года.

Измените пароль с помощью мета-команды

В приведенном выше методе для изменения пароля с помощью операторов ALTER ROLE мы увидели, что пароль виден системе, и она также передаст этот пароль на сервер, который также может быть сохранен в истории операторов psql. Вы можете изменить пароль, сохранив его в надежном и безопасном месте в журнале сервера и его истории с помощью этого метода.

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

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

Я ввел имя пользователя saeed_raza, потому что хочу изменить пароль этого пользователя в PostgreSQL. Теперь следуйте этому простому синтаксису, который также изменит пароль пользователя или пароль по умолчанию PostgreSQL, просто используя метакоманду:

postgres=# password

Enter new password:

Enter it again:

Теперь пароль для пользователя saeed

Теперь пароль для пользователя saeed_raza изменен с помощью этой простой метакоманды.

Вывод

В этом руководстве мы узнали, как можно изменить пароль пользователя с помощью pgAdmin и psql, а также с различными способами psql. Все методы, которые мы использовали в этой статье, были эффективными и простыми, которые вы можете реализовать в своей системе, чтобы окончательно ответить на ваши вопросы о том, как изменить пароли пользователей в PostgreSQL.

In this Postgresql tutorial, we are going to learn about “Postgresql set user password”, which means changing the password of an existing user in the Postgres database on different environments like Windows, Ubuntu, etc.

We are going to cover the following topics.

  • How to set user password in PostgreSQL in windows OS
  • Set user password in PostgreSQL in ubuntu
  • Change user password using pgadmin in PostgreSQL

In Postgresql, We can change the password of the user using the below syntax.

Syntax:

ALTER USER user_name WITH PASSWORD 'new_password';

Here ALTER USER is a command that changes the attributes of a PostgreSQL user account, user_name is the name of the user whose password is to be altered and new_password is the password that you want to set for the user.

We can change password of a Postgresql user account using the command line in windows.

The following are the instructions to change the password of the user.

Open CMD on your computer using CTRL+R and type cmd in the box, then hit Enter from your keyboard.

Enter into psql command prompt as postgres user using below command.

If it asks for a password, then enter the password of the user and remember the password.

psql -U postgres

Now change the password of the current user postgres.

ALTER USER postgres WITH PASSWORD '23456';

Now remember this new password and forget the password that we have remembered before for a user named postgres.

Exit from the psql prompt.

q -- To exit from psql prompt in Postgresql databast
postgresql set user password windows
PostgreSQL set user password windows

We have successfully change the password of a user named Postgres.

Now log in again with the new password of user Postgres.

psql -U postgres

if it asks for a password, enter the new password that we have set recently.

Postgresql set user password windows
Postgresql set user password windows

Read: How to create a table in PostgreSQL

Postgresql set user password ubuntu

In Ubuntu, we can change the password of the Postgresql user account using the terminal.

Open the terminal using CTRL+ALT+T from your keyboard and log into the Postgres prompt using the below command.

sudo su - postgres

Enter into psql prompt.

psql

Now change the password of the user named postgres.

ALTER USER postgres WITH PASSWORD '23456';

Exit from psql prompt and logout from Postgres prompt.

exit -- To exit from psql and postgres prompt
Postgresql set user password ubuntu
Postgresql set user password ubuntu

From the above output, we see the output “ALTER ROLE”, which means the password changed successfully.

Now again log in with the new password and if it asks for a password, then enter the new password.

sudo -i -u postgres

You will successfully be logged in.

Read: PostgreSQL installation on Linux

Postgresql change user password pgadmin

In Postgresql, we can also change the user password from the pgAdmin application.

The following are the instructions to change passwords in the Postgresql database.

Open pdAdmin, go to Browser section and expand icon > in front of Server then expand the icon > in front of Login/Group Roles.

Postgresql change user password pgadmin
Postgresql change user password pgadmin

Now select postgres user from Login/Group Roles, right-click on that and click on option Properties.

Postgresql change user password pgadmin
Postgresql change user password pgadmin

After clicking on Properties, a Login Role-postgres dialog appears, click on the Definition tab and enter the password then click on the Save button at the bottom right corner.

Postgresql change user password pgadmin
Postgresql change user password pgadmin

After clicking on Save, we have successfully changed the password of a user named postgres. Now, close the pgAdmin application, and log in again with the new password.

You may also like some of our latest articles on PostgreSQL.

  • PostgreSQL WHERE IN
  • Postgres date range
  • Postgresql if else
  • PostgreSQL CASE
  • Postgresql create user with password
  • PostgreSQL DATE Format
  • PostgreSQL ADD COLUMN
  • PostgreSQL vs SQL Server
  • Postgres RegEx
  • Postgresql date between two dates
  • Postgresql create database

So in this tutorial, we have learned about “Postgresql set user password” and changed the password of existing users. We have covered the following topics.

  • How to set user password windows in PostgreSQL
  • Set user password ubuntu in PostgreSQL
  • How to change user password pgadmin in PostgreSQL

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

Postgres Change Password

Introduction to Postgres Change Password

In this article, we will learn how we can change the Postgres Change Password of the user if present and if not how we can assign a password to the user for further authenticated usage by him in the PostgreSQL database server. There are two methods to do so. The first method involves using the ALTER query statement to change the password and the second method is to use the meta-command password in PostgreSQL’s psql utility.

To proceed with changing the password process, we first need to understand how password mechanism works in PostgreSQL and what password policy is set to the default superuser which is most often user named Postgres.

In any Unix distribution system of PostgreSQL, there are two types of authentication methods namely ident and peer. The default authentication method depends on which version of PostgreSQL does it use and how is PostgreSQL installed on your machine.

Ident Authentication method: In this method, TCP port with 113 as port number authenticates the user’s credentials where the identification server of the operating system is running.

Peer Authentication Method: In the peer authentication method, the current user’s password of PostgreSQL is matched with the password of the operating system user’s password.

Syntax

Format 1:

ALTER USER name [ [ WITH ] option [ ... ] ] where option can be:
CREATEDB | NOCREATEDB
| CREATEUSER | NOCREATEUSER
| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'newPassword'
| VALID UNTIL 'expirytime'

Explanation: Using the above alter command the password of the user can be changed and along with that other options can also be reassigned.

Name: It is the name of the user or role whose properties or password you want to change.

Option: We can change multiple parameters and privileges associated with the user using this format.

CREATEDB: This can be specified if you want to give the privilege to the user to create a new database

NOCREATEDB: This can be mentioned if you want to restrict the user from creating any new database.

CREATEUSER: This property can be specified to allow the user to create new users.

NOCREATEUSER: When this property is mentioned in the query in the above format the user won’t be able to create new users.

ENCRYPTED: This property determines whether the password stored in the pg_catalog’s pg_shadow table is stored in the form of an MD5 encrypted format.

UNENCRYPTED: The password is not stored in encrypted format in pg_catalog. If neither ENCRYPTED or UNENCRYPTED property is specified and neither this is done while user creation then the default password storing mechanism is decided based on password_encryption configuration variable.

PASSWORD: The new password is the string that you want to set as the password for the user. If this field is not specified and the user doesn’t have any previously set password to it then no authentication will be done for the user and the user can log in to the system without mentioning the password. But in case if you switch to a password authentication system then the user won’t be able to log in.

VALID UNTIL expiry time: This field can be used if you want to allow the set password up to some specific period. This field if the timestamp up to which you want to permit the assigned password to work.

Examples to Implement Postgres Change Password

Below are examples mentioned:

Example #1

We will firstly login to the system by Postgres default user. Here we have assigned a password to the Postgres role already. So, we will enter the password.

Code:

sudo su - postgres

Output:

Postgres Change Password1

Example #2

Further, let us check all the users which are present in the database server by firing the command using psql promo:

Code:

select username from pg_catalog.pg_user;

Output:

Postgres Change Password2

Example #3

Let us try to login using a user:

Code:

sudo su – a;

Output:

Postgres Change Password3

Example #4

As we have forgotten the password associated to that user assigned to it while its creation, we will reset it to pay by using the format 1 ALTER USER query in the following way:

Code:

ALTER USER a WITH ENCRYPTED PASSWORD 'payal';

Output:

Postgres Change Password4

As the output is ALTER ROLE. The password has been reset successfully.

Format 2:

ALTER USER name RENAME TO alteredName

This format is only used to alter the name of the user to some other name “alteredName”.

Example #5

Code:

ALTER USER a RENAME TO payal;

Output:

Postgres Change Password5

Example #6

Let us verify the available users in our database server now.

Code:

SELECT usename FROM pg_catalog.pg_user;

Output:

verify the available users

Example #7

Code:

ALTER USER name SET parameter { TO | = } { targetValue | DEFAULT }

the parameter can be any configuration property of PostgreSQL. You can see all the configuration properties by firing the command

SHOW ALL;

Output:

configuration property of PostgreSQL

Example #8

ALTER USER name RESET parameter

This command is used to reset the value of any field related to the user. Example –

Now, in case if we want to reset the password of the payal user. we can do so by using the query statement :

Code:

ALTER USER payal RESET password;

Output:

reset the password

That gives the output “ALTER ROLE” which means that password for payal user has been reset successfully.

Example #9

MetaCommand to change password: In PostgreSQL, we have this amazing functionality called meta-commands that can be used with the help of psql utility. MetaCommands are short commands which are provided to make the working

of database administrator easy and efficient. These metacommands internally fire the SQL commands which are basic like ALTER, CREATE, SELECT, etc. One such meta-command for changing the password of the user is available and named password. It asks to enter the password and then reenter the password for confirmation and then sets the entered password for that user.

password

Let us check the working of metacommand with the help of an example. Suppose we want to change the password of Postgres user after login to the Postgres database. Then we will query for the same in the following steps:

Code:

psql -d postgres -U postgres
password

Output:

working of metacommand

Conclusion

We can change the password of the user either by using the ALTER command or metacommand password in PostgreSQL.

Recommended Articles

This is a guide to Postgres Change Password. Here we discuss an introduction to Postgres Change Password, syntax, examples with code and output. You can also go through our other related articles to learn more –

  1. PostgreSQL Database
  2. PostgreSQL Trunc()
  3. PostgreSQL cluster
  4. PostgreSQL Functions

Понравилась статья? Поделить с друзьями:
  • Provider named pipes provider error 40 ошибка
  • Ps4 ошибка ce 34788 0 как исправить
  • Ps4 ошибка ce 33937 5
  • Ps4 ошибка ce 32753 0
  • Ps4 как изменить имя аккаунта