Usermod command in linux

Содержание
  1. Команда Usermod в Linux
  2. Команда usermod
  3. Добавить пользователя в группу
  4. Изменить основную группу пользователя
  5. Изменение информации о пользователе
  6. Изменение домашнего каталога пользователя
  7. Изменение пользовательской оболочки по умолчанию
  8. Изменение UID пользователя
  9. Изменение имени пользователя
  10. Установка даты истечения срока действия пользователя
  11. Блокировка и разблокировка учетной записи пользователя
  12. Выводы
  13. usermod command in Linux with Examples
  14. Working with usermod command
  15. Modify User Accounts With Usermod Command
  16. 8 Practical examples of the usermod command
  17. 1. Change user name
  18. 2. Change the home directory of user
  19. 3. Change the login shell of the user
  20. 4. Change the default user group
  21. 5. Add the user to other groups
  22. 6. Lock and unlock user account
  23. 7. Set an expiry date to the user account
  24. 8. Change the UID of a user
  25. A Complete Guide to Usage of ‘usermod’ command – 15 Practical Examples with Screenshots
  26. Requirements
  27. Options of Usermod
  28. 1. Adding Information to User Account
  29. 2. Change User Home Directory
  30. 3. Set User Account Expiry Date
  31. 4. Change User Primary Group
  32. 5. Adding Group to an Existing User
  33. 6. Adding Supplementary and Primary Group to User
  34. 7. Change User Login Name
  35. 8. Lock User Account
  36. 9. Unlock User Account
  37. 10. Move User Home Directory to New location
  38. 11. Create Un-encrypted Password for User
  39. 12. Change User Shell
  40. 13. Change User ID (UID)
  41. 14. Modifying User Account with Multiple Options
  42. 15. Change UID and GID of a User
  43. Conclusion
  44. If You Appreciate What We Do Here On TecMint, You Should Consider:

Команда Usermod в Linux

usermod — это утилита командной строки, которая позволяет изменять данные для входа пользователя.

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

Команда usermod

Синтаксис команды usermod имеет следующий вид:

Только root или пользователи с доступом sudo могут вызывать usermod и изменять учетную запись пользователя. В случае успеха команда не выводит никаких результатов.

Добавить пользователя в группу

Наиболее типичный вариант использования usermod — добавление пользователя в группу.

Чтобы добавить существующего пользователя во вторичную группу, используйте параметры -a -G после имени группы и имени пользователя:

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

Например, чтобы добавить пользователя linuxize в группу games , вы должны выполнить следующую команду:

Всегда используйте параметр -a (добавить) при добавлении пользователя в новую группу. Если вы опустите опцию -a , пользователь будет удален из групп, не перечисленных после опции -G .

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

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

Чтобы изменить основную группу пользователя, вызовите команду usermod с параметром -g следующим за именем группы и именем пользователя:

В следующем примере мы меняем основную группу пользователя linuxize на developers :

Каждый пользователь может принадлежать ровно к одной основной группе и нулю или более вторичных групп.

Изменение информации о пользователе

Чтобы изменить информацию GECOS (полное имя пользователя), запустите команду с параметром -c за которым следует новый комментарий и имя пользователя:

Вот пример, показывающий, как добавить дополнительную информацию пользователю linuxize:

Эта информация хранится в /etc/passwd .

Изменение домашнего каталога пользователя

В большинстве систем Linux домашние каталоги пользователей названы по имени пользователя и создаются в каталоге /home .

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

По умолчанию команда не перемещает содержимое домашнего каталога пользователя в новый. Чтобы переместить содержимое, используйте параметр -m . Если новый каталог еще не существует, он создается:

Вот пример, показывающий, как изменить домашний каталог пользовательских www-data на /var/www :

Изменение пользовательской оболочки по умолчанию

Оболочка по умолчанию — это оболочка, которая запускается после входа в систему. По умолчанию в большинстве систем Linux в качестве оболочки по умолчанию используется Bash Shell.

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

В приведенном ниже примере мы меняем оболочку пользователя на Zsh:

Вы можете узнать, какие оболочки доступны в вашей системе, просмотрев содержимое файла /etc/shells .

Изменение UID пользователя

UID (идентификатор пользователя) — это номер, присвоенный каждому пользователю. Он используется операционной системой для обозначения пользователя.

Чтобы изменить UID пользователя, вызовите команду с параметром -u следующим за новым UID и именем пользователя:

В приведенном ниже примере показано, как изменить номер «UID» на «1050»:

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

Изменение имени пользователя

Хотя не очень часто, иногда вам может потребоваться изменить имя существующего пользователя. Параметр -l используется для изменения имени пользователя:

В приведенном ниже примере мы переименовываем пользователя linuxize в lisa в «1050»:

При изменении имени пользователя вы также можете изменить домашний каталог пользователя, чтобы отразить новое имя пользователя.

Установка даты истечения срока действия пользователя

Дата истечения срока — это дата, когда учетная запись пользователя будет отключена. Чтобы установить дату истечения срока действия пользователя, используйте параметр -e :

Срок годности должен быть установлен в формате YYYY-MM-DD .

Например, чтобы отключить пользователя linuxize 21 2022-02-21 , вы должны выполнить следующую команду:

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

Используйте команду chage -l для просмотра даты истечения срока действия пользователя:

Дата истечения срока хранения хранится в /etc/shadow .

Блокировка и разблокировка учетной записи пользователя

Параметр -L позволяет заблокировать учетную запись пользователя:

Команды вставят восклицательный знак ( ! ) Перед зашифрованным паролем. Если поле пароля в /etc/shadow содержит восклицательный знак, пользователь не сможет войти в систему, используя аутентификацию по паролю. Другие методы входа в систему, такие как аутентификация на основе ключей или переключение на пользователя , по-прежнему разрешены. Если вы хотите заблокировать учетную запись и отключить все методы входа в систему, вам также необходимо установить дату истечения срока действия равной 1.

Читайте также:  Windows phone как обойти

В следующих примерах показано, как заблокировать пользователя linuxize :

Чтобы разблокировать пользователя, запустите usermod с параметром -U :

Выводы

Мы показали вам, как использовать команду usermod для установки информации об учетной записи пользователя.

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

Источник

usermod command in Linux with Examples

usermod command or modify user is a command in Linux that is used to change the properties of a user in Linux through the command line. After creating a user we have to sometimes change their attributes like password or login directory etc. so in order to do that we use the Usermod command. The information of a user is stored in the following files:

When we execute usermod command in temrinal the command make the changes in these files itself.

Note: usermod command needs to be executed only as a root user.

Working with usermod command

1. To add a comment for a user

This will add a comment about the user or a short description related to the user.

2. To change the home directory of a user

This will change the home directory of the user to /home/manav.

3. To change the expiry date of a user

This will change the expiration date of account “test_user”

4. To change the group of a user

This command will now change the group of test user from test_user to manav

5. To change user login name

This will now change the login name of the user “test_user”.

6. To lock a user

This will lock the “test_user” account and will display a! sign in shadow file before the username

7. To unlock a user

This will unlock the “test_user” which was locked by the previous command

8. To set an unencrypted password for the user

This will set the password “test_password” in the unencrypted form for the user “test_user”

9. To create a shell for the user

This command will now create a shell for the user “test_user” from /bin/sh

10. To change the user id of a user

This command will change the user id of “test_user” to 1234

Источник

Modify User Accounts With Usermod Command

You can create a new user with useradd command but if you mis-configured the account, you don’t necessarily have to delete the user. You can change the user account settings with usermod command in Linux.

The usermod (short for user modification) enables you to modify various aspects of a user account. You can change the home directory and shell of the user. You can add the user to different groups or lock the account.

8 Practical examples of the usermod command

Since you are dealing with user account management, you must be either root or have sudo rights to run the usermod command.

Let me show you some examples.

1. Change user name

You can change the username with the option -l of usermod command:

Keep in mind that apart from the user name, nothing else changes on its own. You’ll have to manually change the home directory and mail spool.

2. Change the home directory of user

You can change the home directory of the user to another directory.

Keep in mind that it will change the home directory even if the directory doesn’t exist but it will not create it on its own.

A better way to change the home directory of the user is to use -m option with -d. This way, it will create the new home directory if it doesn’t exist. Apart from that, it will also move the content of the old home directory to the new home directory with correct file permissions and ownership.

Here’s an example:

Order of m and d is also important here.

3. Change the login shell of the user

You can also change the default shell of a user with usermod command. Let’s say you want to change the login shell to zsh, here’s what you could do:

4. Change the default user group

You can also change the default group of a user. This is particularly helpful when you have changed the user name. It would be good idea to change the default user group as well.

5. Add the user to other groups

This is perhaps the most common usage of the usermod command. If you want to add a user to the sudoer list, all you have to do is to add the user to the sudo group.

Did you notice that I used option -aG here and not just -G. It’s because if you use only -G option, it will replace the user groups with the new group you provided.

This is why you should use the append option -a so that the user is added to the new group additionally and not removed from its previous groups.

6. Lock and unlock user account

You can lock a user account in Linux with usermod command option -L. A locked user cannot log in to the system.

You can also unlock the user with option -U:

7. Set an expiry date to the user account

Suppose an intern joins your organization for two months. You’ll have to remove the user account once the intern departs. You can play smart here and set an expiry date to the intern’s account so that it automatically disables the account.

To set an expiry date to an user account, you can use the option -e with date in YYYY-MM-DD format.

8. Change the UID of a user

You can change the UID (user ID) of a user with the option -u:

Читайте также:  Firewall для alt linux

In the end…

There are a few more options that you may explore by referring to its man page.

In my opinion, what you just saw is the most common examples of usermod command. If you have any questions or suggestions, do let me know.

Источник

A Complete Guide to Usage of ‘usermod’ command – 15 Practical Examples with Screenshots

In Unix/Linux distributions, the command ‘usermod‘ is used to modify or change any attributes of a already created user account via command line. The command ‘usermod‘ is similar to that ‘useradd‘ or ‘adduser‘ but the login granted to an existing user.

15 usermod Command Examples

The command ‘useradd‘ or ‘adduser‘ is used for creating user accounts in Linux systems. To know more about on how to create system users, read our complete guide at:

After creating user accounts, in some scenarios where we need to change the attributes of an existing user such as, change user’s home directory, login name, login shell, password expiry date, etc, where in such case ‘usermod’ command is used.

When we execute ‘usermod‘ command in terminal, the following files are used and affected.

  1. /etc/passwd – User account information.
  2. /etc/shadow – Secure account information.
  3. /etc/group – Group account information.
  4. /etc/gshadow – Secure group account information.
  5. /etc/login.defs – Shadow password suite configuration..

Basic syntax of command is:

Requirements

  1. We must have existing user accounts to execute usermod command.
  2. Only superuser (root) is allowed to execute usermod command.
  3. The usermod command can be executed on any Linux distribution.
  4. Must have basic knowledge of usermod command with options

Options of Usermod

The ‘usermod‘ command is simple to use with lots of options to make changes to an existing user. Let us see how to use usermod command by modifying some existing users in Linux box with the help of following options.

  1. -c = We can add comment field for the useraccount.
  2. -d = To modify the directory for any existing user account.
  3. -e = Using this option we can make the account expiry in specific period.
  4. -g = Change the primary group for a User.
  5. -G = To add a supplementary groups.
  6. -a = To add anyone of the group to a secondary group.
  7. -l = To change the login name from tecmint to tecmint_admin.
  8. -L = To lock the user account. This will lock the password so we can’t use the account.
  9. -m = moving the contents of the home directory from existing home dir to new dir.
  10. -p = To Use un-encrypted password for the new password. (NOT Secured).
  11. -s = Create a Specified shell for new accounts.
  12. -u = Used to Assigned UID for the user account between 0 to 999.
  13. -U = To unlock the user accounts. This will remove the password lock and allow us to use the user account.

In this article we will see ‘15 usermod commands‘ with their practical examples and usage in Linux, which will help you to learn and enhance your command-line skills using these options.

1. Adding Information to User Account

The ‘-c‘ option is used to set a brief comment (information) about the user account. For example, let’s add information on ‘tecmint‘ user, using the following command.

After adding information on user, the same comment can be viewed in /etc/passwd file.

Add Information to User

2. Change User Home Directory

In the above step we can see that our home directory is under /home/tecmint/, If we need to change it to some other directory we can change it using -d option with usermod command.

For example, I want to change our home directory to /var/www/, but before changing, let’s check the current home directory of a user, using the following command.

Now, change home directory from /home/tecmint to /var/www/ and confirm the home director after changing.

Change User Home Directory

3. Set User Account Expiry Date

The option ‘-e‘ is used to set expiry date on a user account with the date format YYYY-MM-DD. Before, setting up an expiry date on a user, let’s first check the current account expiry status using the ‘chage‘ (change user password expiry information) command.

The expiry status of a ‘tecmint‘ user is Dec 1 2014, let’s change it to Nov 1 2014 using ‘usermod -e‘ option and confirm the expiry date with ‘chage‘ command.

Set User Account Expiry Date

4. Change User Primary Group

To set or change a user primary group, we use option ‘-g‘ with usermod command. Before, changing user primary group, first make sure to check the current group for the user tecmint_test.

Now, set the babin group as a primary group to user tecmint_test and confirm the changes.

Change User Primary Group

5. Adding Group to an Existing User

If you want to add a new group called ‘tecmint_test0‘ to ‘tecmint‘ user, you can use option ‘-G‘ with usermod command as shown below.

Add Group to User

Note: Be careful, while adding a new groups to an existing user with ‘-G’ option alone, will remove all existing groups that user belongs. So, always add the ‘-a‘ (append) with ‘-G‘ option to add or append new groups.

6. Adding Supplementary and Primary Group to User

If you need to add a user to any one of the supplementary group, you can use the options ‘-a‘ and ‘-G‘. For example, here we going to add a user account tecmint_test0 with the wheel user.

Читайте также:  Mac os high sierra год выпуска

So, user tecmint_test0 remains in its primary group and also in secondary group (wheel). This will make my normal user account to execute any root privileged commands in Linux box.

Add Multiple Groups to User

7. Change User Login Name

To change any existing user login name, we can use ‘-l‘ (new login) option. In the example below, we changing login name tecmint to tecmint_admin. So the username tecmint has been renamed with the new name tecmint_admin.

Now check for the tecmint user, It will not be present because we have changed it to tecmint_admin.

Check for the tecmint_admin account it will be there with same UID and with existing group what we have added before.

Change User Login Name

8. Lock User Account

To Lock any system user account, we can use ‘-L‘ (lock) option, After the account is locked we can’t login by using the password and you will see a ! added before the encrypted password in /etc/shadow file, means password disabled.

Check for the locked account.

Lock User Account

9. Unlock User Account

The ‘-U‘ option is used to unlock any locked user, this will remove the ! before the encrypted password.

Verify the user after unlock.

Unlock User Account

10. Move User Home Directory to New location

Let’s say you’ve a user account as ‘pinky‘ with home directory ‘/home/pinky‘, you want to move to new location say ‘/var/pinky‘. You can use the options ‘-d‘ and ‘-m‘ to move the existing user files from current home directory to a new home directory.

Check for the account and it’s current home directory.

Then list the files which is owned by user pinky.

Now we have to move the home directory from /home/pinky to /var/pinky.

Next, verify the directory change.

Check for the files under ‘/home/pinky‘. Here we have moved the files using -m option so there will be no files. The pinky user files will be now under /var/pinky.

Move User Home Directory

11. Create Un-encrypted Password for User

To create an un-encrypted password, we use option ‘-p‘ (password). For demonstration purpose, I’m setting a new password say ‘redhat’ on a user pinky.

After setting password, now check the shadow file to see whether its in encrypted format or un-encrypted.

Create Unencrypted User Password

Note: Did you see in the above image, the password is clearly visible to everyone. So, this option is not recommended to use, because the password will be visible to all users.

12. Change User Shell

The user login shell can be changed or defined during user creation with useradd command or changed with ‘usermod‘ command using option ‘-s‘ (shell). For example, the user ‘babin‘ has the /bin/bash shell by default, now I want to change it to /bin/sh.

After changing user shell, verify the user shell using the following command.

Change User Login Shell

13. Change User ID (UID)

In the example below, you can see that my user account ‘babin‘ holds the UID of 502, now I want to change it to 888 as my UID. We can assign UID between 0 to 999.

Now, let’s change the UID for user babin using ‘-u‘ (uid) option and verify the changes.

Change User UID

14. Modifying User Account with Multiple Options

Here we have a user jack and now I want to modify his home directory, shell, expiry date, label, UID and group at once using one single command with all options as we discussed above.

The user Jack has the default home directory /home/jack, Now I want to change it to /var/www/html and assign his shell as bash, set expiry date as December 10th 2014, add new label as This is jack, change UID to 555 and he will be member of apple group.

Let we see how to modify the jack account using multiple option now.

Then check for the UID & home directory changes.

Account expire check.

Check for the group which all jack have been member.

Using Multiple Options with usermod

15. Change UID and GID of a User

We can change UID and GID of a current user. For changing to a New GID we need an existing group. Here already there is an account named as orange with GID of 777.

Now my jack user account want to be assigned with UID of 666 and GID of Orange (777).

Check for the current UID and GID before modifying.

Modify the UID and GID.

Check for the changes.

Change User UID and GID

Conclusion

Here we have seen how to use usermod command with its options in very detailed fashion, Before knowing about usermod command, one should must know ‘useradd’ command and its options to use the usermod. If I’ve missed any point in the article do let me know via comments and don’t forget to add your valuable comments.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

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