Linux change user password terminal

Меняем пароль в Linux

Так как Linux — платформа многопользовательская, да еще и с особым уклоном в безопасность, то приходится иметь дела с полномочиями и паролями. Последний особенно часто нужен даже для выполнения тривиальных задач вроде установки свежего программного обеспечения.

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

Если речь идет о каком-нибудь администрируемом сервере, то наверняка пользователь с наивысшими полномочиями вынуждает других менять пароль чуть ли не каждый месяц, а того и чаще. Все зависит от требований конкретного человека.

Собственно, об этом и поговорим. Как сменить пароль в Linux, каким должен быть этот пароль, как заставить поменять пароль других пользователей и так далее. Полный экскурс в мир безопасности на платформе Linux.

Утилита passwd

Вообще, в Linux есть несколько программ для управления паролями. Многие из них имеют графический интерфейс и визуально напоминают таковые из других операционных систем (Windows или macOS). Но использовать их все вовсе не обязательно, потому что есть универсальный способ изменения пароля, который вшит в Linux и поддерживается на любом дистрибутиве. Речь об утилите passwd.

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

Также у passwd есть еще несколько преимуществ. С помощью нее можно вынуждать менять пароли других пользователей, а также ставить сроки действия пароля. То есть устанавливать некий таймер, по истечении работы которого пароль просрочится и перестанет работать. А еще можно проделывать любые махинациями с паролями других пользователей.

Синтаксис и опции утилиты passwd

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

passwd (название утилиты) опции и имя пользователя .

Как видите, все довольно просто. Легко запомнить и самостоятельно разобраться.

А вот и список доступных опций:

  • -d — с помощью этой опции можно удалить пароль у любого пользователя без возможности его вернуть (придется создавать новый). Естественно, после выполнения этой команды пользователь не сможет зайти в систему.
  • -e — эта опция обозначает пароль выбранного пользователя устаревшим. Если ею воспользоваться, то система при следующей попытке пользователя войти, вынудит его сменить пароль, объясняя требование как раз-таки устаревшим паролем.
  • -iи время — если воспользоваться этой опцией и указать определенный период времени, то после устаревания пароля, спустя этот временной отрезок пользователь будет удален из системы. Если в течение действия опции пользователь успеет заменить пароль на новый, то с учетной записью ничего не произойдет и она будет работать так же, как и раньше.
  • -l — эта опция никак не связана с изменением пароля. Она выполняет одну простую функцию — блокирует пользователю доступ к системе.
  • -u — а эта пригодится, чтобы разблокировать аккаунт и вернуть доступ выбранному пользователю.
  • -nи количество — с помощью этой опции можно указать минимальное количество суток, которое должно пройти с последней смены пароля, чтобы вновь можно было изменить пароль выбранного пользователя.
  • -S — воспользуйтесь этой опцией, чтобы получить полный перечень параметров, связанных с паролем у выбранной учетной записи. Она показывает, когда был установлен пароль, как часто он должен меняться, когда следующая смена, придет ли оповещение о необходимости сменить пароль и прочие полезные данные.
  • -xи количество — этим параметром задается количество дней, в течение которого выбранный пользователем пароль будет являться актуальным.
  • -wи количество — здесь тоже указывается количество дней. Спустя указанное количество суток после смены пароля (именно тогда вступает в действие эта опция) пользователь получит предупреждение о том, что его пароль устарел и его необходимо сменить.
Читайте также:  Linux автоматический перезапуск службы

Дальше поговорим о конкретных примерах использования passwd с некоторыми из перечисленных опций.

Меняем свой пароль

Начнем с самой простой и, наверное, самой востребованной операции. Обычная смена пароля для самого себя. То есть для пользователя, под данными которого вы выполнили вход и от лица которого запустили терминал.

  • Для смены пароля просто вводим команду passwd . Никакие опции и параметры здесь не нужны. Программа сама определит, что вы за пользователь, а отсутствие опций даст ей понять, что нужно без лишней суеты просто поменять пароль.

Источник

Passwd Command in Linux – Options + Examples

Security is one of the many bragged features about Linux and it can be justified by the way it manages and authenticates its users. Authentication of users is done in Linux through passwords and public keys.

Linux distributions allow to set administrative accounts during the OS installation and this can be changed later if you have the required privilege. Generally, there is no default password set for any user accounts in Linux. When new users are created using the useradd, the account doesn’t have a password; in order to login, the password has to be created separately.

In this tutorial, we’ll be learning about passwd command in Linux to change passwords in Linux.

Prerequisites

  • Any Linux system
  • Basic knowledge of Linux command line
  • An existing user account
  • Required privilege to run the command

Passwd Command

passwd is a command that changes user account passwords in the Linux system. A regular user has the privilege to only change the password for their individual account while a superuser (root) exercises the privilege to change passwords for any account in the system.

Читайте также:  Назначение прав доступа папке linux

The passwd command changes the user’s password by modifying the passwords that are stored as encrypted strings in the /etc/shadow file. It can also be used to change the validity periods and other related settings for passwords associated with the account.

After entering the passwd command in the terminal, users first need to enter their current password for verification. Superusers are exempt from this step when changing the passwords for other accounts, especially necessary to reset the forgotten passwords for user accounts.

After verifying the current password, passwd makes sure if the current user has the privilege to alter the password.

Only if the current user has the privilege, s/he is prompted for a new password. It checks the complexity of the set user passwords in the next step. If the password passes the complexity test, passwd prompts for retyping the new password. If the two passwords match, a new password is set for the user.

The configuration files passwd uses are:

  • /etc/passwd — stores the user account information
  • /etc/shadow — stores secure user account information
  • /etc/pam.d/passwd — stores PAM configuration for passwd

Passwd command Options

Option Description
-a , —all Display password status of every account in the system
-d , —delete Remove user password
-e , —expire Expire user’s password immediately
-h , —help Show this help information
-k , —keep-tokens Change password only in case of expired authentication tokens
-i , —inactive INACTIVE Deactivate the password after INACTIVE number of days following the password expiry
-l , —lock Lock the password for the account specified
-n , —mindays MIN_DAYS Set the minimum number of days between password changes to MIN_DAYS
-q , —quiet Enable quiet mode
-r , —repository REPOSITORY Change password in REPOSITORY repository
-R , —root CHROOT_DIR Specify directory to chroot into
-S , —status Display account status information
-u , —unlock Unlock the password of the named account
-w , —warndays WARN_DAYS Set the number of days before the required password change the user will be warned to WARN_DAYS
-x , —maxdays MAX_DAYS Set the maximum number of days the password remains valid for a user to MAX_DAYS

Passwd Command Examples

Now, we’ll be seeing the passwd commands in action with the following examples.

Источник

How to Change Your Password in Linux Using Terminal

wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, 11 people, some anonymous, worked to edit and improve it over time.

The wikiHow Tech Team also followed the article’s instructions and verified that they work.

This article has been viewed 125,650 times.

Changing a password on Linux can be confusing for those who are unfamiliar with it. This guide will show you how to change your account’s password for most Linux systems.

Open a terminal window.

Image titled Change Your Password in Linux Step 1

Open the Terminal if using a desktop environment. The keyboard shortcut to do this is Ctrl + Alt + T .

Читайте также:  Astra linux ifconfig команда

Type «passwd» at the prompt and press «Enter.»

Image titled Change Your Password in Linux Step 2

The passwd command will prompt you to enter your old password. You’ll you’re your old password to create a new one.

Enter your old password and press «Enter.»

Image titled Change Your Password in Linux Step 3

If your password is correct, you’ll be able to create a new one. The password characters will not be displayed on the screen while you type so onlookers will not be able to guess at the length of the password.

Enter and confirm a new password.

Image titled Change Your Password in Linux Step 4

Type the new password and press ↵ Enter . You’ll need to confirm by typing it one more time and pressing Enter again. You have now reset your password using the terminal.

Community Q&A

To change the root password, you will need to log in as root. Depending on your Linux distribution, you can do this a variety of ways. Most common distributions require you to become root using the command «sudo -i», «sudo su -«, or «su root». You may then change the root password by executing the «passwd» command.

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

The password you type becomes invisible, but it’s still there. Just be careful not to make a mistake in the password.

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

Refer to our article How to Reset Forgotten Password in Linux for help resetting your login password.

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

Источник

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