Короткий список команд для создания пользователя
sudo useradd -m -s /bin/bash weril sudo passwd weril sudo login weril - тестово логинемся sudo passwd -e weril - (expire) делаем пароль протухшим (после авторизации пользователя заставят поменять пароль) # sudo passwd -l weril - (lock) блокируем пользователя sudo vi /etc/ssh/sshd_config - добавляем в AllowUsers в sshd (AllowUsers <username>@*) sudo /etc/init.d/sshd restart - рестартуем службу (sudo service sshd restart)
При смене пароля может запрашивать старый пароль, мы его можем не знать (напр. потерял пользователь/учетная запись создана облаком), в таком случае меняем из под root.
sudo su passwd weril
В Centos чтобы не добавлять каждого пользователя отдельно есть группа wheel, в Ubuntu группа sudo. Если добавить в эту группу – будут так же права sudo.
sudo usermod -a -G wheel [user name] sudo usermod -a -G sudo [user name]
Типы пользователей
RHEL supports three fundamental user account types: root, normal, and service.
-
The root user, the superuser or the administrator with full access to all services and administrative functions, possesses full powers on the system. This user is automatically created during RHEL installation.
-
The normal users have user-level privileges. They cannot perform any administrative functions, but can run applications and programs that they are authorized to execute.
-
The service accounts are responsible for taking care of the installed services. These accounts include apache, ftp, mail, ntp, postfix, and qemu.
Ключевые файлы по управлению пользователями и группами
https://learning.lpi.org/en/learning-materials/010-160/5/5.2/5.2_01/
User account information for local users is stored in four files in the /etc directory. These files are passwd, shadow, group, and gshadow, and they are updated when a user account is created, modified, or deleted. The same files are referenced to check and validate the credentials for a user at the time of their login attempt into the system, and hence these files are referred to as user authentication files. These files are so critical to the operation of the system that, by default, the system maintains a backup of each of these files as passwd-, shadow-, group-, and gshadow- in the /etc directory. The shadow and gshadow files, as well as the user administration commands are part of the shadow-utils package that is installed on the system at the time of OS installation.
/etc/passwd
a file of seven colon-delimited fields containing basic information about users
frank:x:1001:1001::/home/frank:/bin/bash
Each line consists of seven colon-delimited fields:
- Username
- The name used when the user logs into the system.
- Password
- The encrypted password (or an
x
if shadow passwords are used). - User ID (UID)
- The ID number assigned to the user in the system.
- Group ID (GID)
- The primary group number of the user in the system.
- GECOS
- An optional comment field, which is used to add extra information about the user (such as the full name). The field can contain multiple comma-separated entries.
- Home directory
- The absolute path of the user’s home directory.
- Shell
- The absolute path of the program that is automatically launched when the user logs into the system (usually an interactive shell such as
/bin/bash
).
/etc/group
a file of four colon-delimited fields containing basic information about groups
developer:x:1002:
Each line consists of four colon-delimited fields:
- Group Name
- The name of the group.
- Group Password
- The encrypted password of the group (or an
x
if shadow passwords are used). - Group ID (GID)
- The ID number assigned to the group in the system.
- Member list
- A comma-delimited list of users belonging to the group, except those for whom this is the primary group.
/etc/shadow
a file of nine colon-delimited fields containing encrypted user passwords, file readable only by root and users with root privileges and contains the encrypted passwords of the users, each on a separate line:
frank:$6$i9gjM4Md4MuelZCd$7jJa8Cd2bbADFH4dwtfvTvJLOYCCCBf/.jYbK1IMYx7Wh4fErXcc2xQVU2N1gb97yIYaiqH.jjJammzof2Jfr/:18029:0:99999:7:::
Each line consists of nine colon-delimited fields:
- Username
- The name used when user logs into the system.
- Encrypted password
- The encrypted password of the user (if the value is
!
, the account is locked). - Date of last password change
- The date of the last password change, as number of days since 01/01/1970. A value of
0
means that the user must change the password at the next access. - Minimum password age
- The minimum number of days, after a password change, which must pass before the user will be allowed to change the password again.
- Maximum password age
- The maximum number of days that must pass before a password change is required.
- Password warning period
- The number of days, before the password expires, during which the user is warned that the password must be changed.
- Password inactivity period
- The number of days after a password expires during which the user should update the password. After this period, if the user does not change the password, the account will be disabled.
- Account expiration date
- The date, as number of days since 01/01/1970, in which the user account will be disabled. An empty field means that the user account will never expire.
- A reserved field
- A field that is reserved for future use.
/etc/gshadow
a file of four colon-delimited fields file containing encrypted group passwords, file readable only by root and by users with root privileges that contains encrypted passwords for groups, each on a separate line:
developer:$6$7QUIhUX1WdO6$H7kOYgsboLkDseFHpk04lwAtweSUQHipoxIgo83QNDxYtYwgmZTCU0qSCuCkErmyR263rvHiLctZVDR7Ya9Ai1::
Each line consists of four colon-delimited fields:
- Group name
- The name of the group.
- Encrypted password
- The encrypted password for the group (it is used when a user, who is not a member of the group, wants to join the group using the
newgrp
command — if the password starts with!
, no one is allowed to access the group withnewgrp
). - Group administrators
- A comma-delimited list of the administrators of the group (they can change the password of the group and can add or remove group members with the
gpasswd
command). - Group members
- A comma-delimited list of the members of the group.
vipw/vigr
- vipw – редактируем безопасно файл passwd & shadow
- vigr – редактируем безопасно файл group & gshadow
The vipw and vigr commands edits the files /etc/passwd and /etc/group, respectively. With the -s flag, they will edit the shadow versions of those files, /etc/shadow and /etc/gshadow, respectively. The programs will set the appropriate locks to prevent file corruption. When looking for an editor, the programs will first try the environment variable $VISUAL, then the environment variable $EDITOR, and finally the default editor, vi(1).
# vigr –s
vigr: Couldn't lock file: Interrupted system call
vigr: /etc/gshadow is unchanged
You have modified /etc/passwd. You may need to modify /etc/shadow for consistency. Please use the command 'vipw -s' to do so.
You have modified /etc/gshadow.
You may need to modify /etc/group for consistency.
Please use the command 'vigr' to do so.
pwck / grpck
pwck / grpck – verify integrity of password/group files
The pwck command verifies the integrity of the users and authentication information. It checks that all entries in /etc/passwd and /etc/shadow have the proper format and contain valid data. The user is prompted to delete entries that are improperly formatted or which have other uncorrectable errors.
~$ sudo pwck [sudo] password for admin: user 'ftp': directory '/var/ftp' does not exist user 'avahi-autoipd': directory '/var/lib/avahi-autoipd' does not exist pwck: no changes ~$ sudo pwck [sudo] password for redkin_p: user 'lp': directory '/var/spool/lpd' does not exist user 'news': directory '/var/spool/news' does not exist user 'uucp': directory '/var/spool/uucp' does not exist pwck: no changes
~$ sudo grpck
pwconv / grpconv or pwunconv / grpunconv : Activating and Deactivating Shadow Password Mechanism
- pwconv – Creates and updates the shadow file and moves user passwords over from the passwd file. Activates password shadowing if it is not already active. The activation tools reference the /etc/login.defs file for some password aging attributes while being executed. This command works quietly and does not display any output unless there is a problem. It creates the shadow file with read-only permission for the root user.
- pwunconv – Moves user passwords back to the passwd file and removes the shadow file. Deactivates password shadowing.
- grpconv – Creates and updates the gshadow file and moves group passwords over from the group file. Activates password shadowing at the group level if it is not already active. This command works quietly and does not display any output unless there is a problem. It creates the gshadow file with read-only permission for the root user.
- grpunconv – Moves group passwords back to the group file and removes the gshadow file. Deactivates password shadowing.
The Skeleton Directory
When you add a new user account, even creating its home directory, the newly created home directory is populated with files and folders that are copied from the skeleton directory (by default /etc/skel
). The idea behind this is simple: a system administrator wants to add new users having the same files and directories in their home. Therefore, if you want to customize the files and folders that are created automatically in the home directory of the new user accounts, you must add these new files and folders to the skeleton directory.
ID
id – просмотр информации по себе uid (user id), gid (primary group id – она назначается для новых файлов), список групп с их ID.
root@serv:~# id uid=0(root) gid=0(root) groups=0(root) user@serv:~$ id uid=1000(user) gid=1000(user) groups=1000(user),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev)
Useradd
https://linux.die.net/man/8/useradd
When invoked with only the -D option, useradd will display the current default values. When invoked with -D plus other options, useradd will update the default values for the specified options.
~# useradd -D GROUP=100 HOME=/home INACTIVE=-1 EXPIRE= SHELL=/bin/sh SKEL=/etc/skel CREATE_MAIL_SPOOL=no
[root@localhost ~]# useradd user2 - Create a User Account with Default Values defined in the useradd and login.defs files [root@localhost ~]# useradd -u 1010 -g 1001 -m -d /home/user3 -k /etc/skel -s /bin/bash user3 - Create user3 with UID 1010 (–u), home directory /home/user3 (–m and –d) shell /bin/bash (–s) membership in group 1001 (–g), and default startup files copied into this user’s home directory (–k) [root@localhost ~]# useradd -s /sbin/nologin user4 - Create user4 with shell file /sbin/nologin. This shell is primarily used for application accounts that do not require login access to the system. It can also be assigned to a regular user to disable access temporarily using the usermod command. [root@localhost ~]# ls /home/ user1 user2 user3 user4
### grep for user2 on the passwd, shadow, group, and gshadow files to check what the useradd command has added:
[root@localhost ~]# cd /etc; grep user2 passwd shadow group gshadow
passwd:user2:x:1001:1001::/home/user2:/bin/bash
shadow:user2:$6$k8Zc4syc$vGkOpb5g/kcNEE8SwYy9kcw5pc6I.eWP90bWwS7WXpk.gXzmiawBueQIvJOaiEtCaEIRDe3Nacr5hFKRDztM5/:17098:0:99999:7:::
group:user2:x:1001:
gshadow:user2:!::
[root@localhost etc]# cd /etc ; grep user3 passwd shadow group gshadow
passwd:user3:x:1010:1001::/home/user3:/bin/bash
shadow:user3:$6$4Y9/Kbaz$J3E6ndqZ7dOXGF5t/gTwDXL7vaDJjiadR9jg4JnfX5BLnClm0lfnRba6qkE6RSRcy6xpe9qNRZXuBXnXX58VM1:17098:0:99999:7:::
[root@localhost etc]# cd /etc ; grep user4 passwd shadow group gshadow
passwd:user4:x:1011:1011::/home/user4:/sbin/nologin
shadow:user4:$6$yjNYeAkL$GPmyvzx0ipg6ZKndwJyGA8VhUrKvjKpsOYSwX.KpvfBEjBY6H085l0WJtYa04DX.bFgDUuTEMsI2r2APgwk1v.:17098:0:99999:7:::
group:user4:x:1011:
gshadow:user4:!::
[user1@localhost ~]$ su - user2 Password: Last login: Mon Oct 24 17:20:51 MSK 2016 on pts/0 [root@localhost ~]# su - user4 Last login: Mon Oct 24 17:51:42 MSK 2016 on pts/0 This account is currently not available. -- The message “This account is currently not available” is displayed when a user with a nologin shell attempts to log in. [root@localhost ~]# su - user5 su: user user5 does not exist
[root@localhost ~]# useradd -GROUP=100 HOME=/home INACTIVE=-1 EXPIRE= SHELL=/bin/bash SKEL=/etc/skel CREATE_MAIL_SPOOL=yes
[root@localhost ~]# useradd -D -b /usr/home [root@localhost ~]# useradd -D GROUP=100 HOME=/usr/home INACTIVE=-1 EXPIRE= SHELL=/bin/bash SKEL=/etc/skel CREATE_MAIL_SPOOL=yes
[root@localhost ~]# grep -v ^# /etc/login.defs | grep -v ^$ MAIL_DIR /var/spool/mail PASS_MAX_DAYS 99999 PASS_MIN_DAYS 0 PASS_MIN_LEN 5 PASS_WARN_AGE 7 UID_MIN 1000 UID_MAX 60000 SYS_UID_MIN 201 SYS_UID_MAX 999 GID_MIN 1000 GID_MAX 60000 SYS_GID_MIN 201 SYS_GID_MAX 999 CREATE_HOME yes UMASK 077 USERGROUPS_ENAB yes ENCRYPT_METHOD SHA512
Usermod
- usermod -u 2000 -m -d /home/user2new -s /sbin/nologin -l user2new user2 – Modify the login name for user2 to user2new (–l), UID to 2000 (–u), home directory to /home/user2new (–m and –d) and login shell to /sbin/nologin (–s)
[root@localhost ~]# cd /etc; grep user2 passwd
user2new:x:2000:1001::/home/user2new:/sbin/nologin
Userdel
sudo userdel -r akandratov
passwd
passwd
[root@localhost ~]# passwd user2 Changing password for user user2. New password: Retype new password: passwd: all authentication tokens updated successfully.
Lock user4 using either of the following
[root@localhost ~]# usermod -L user2new
[root@localhost ~]# passwd -l user2new
Locking password for user user2new.
passwd: Success
[root@localhost ~]# cat /etc/passwd | grep user2new
user2new:x:2000:1001::/home/user2new:/sbin/nologin
chage / passwd / usermod for managing password aging
change
-
- chage -E 2024-12-31 user10 – deactivate user user10 at 2024-12-31
- chage -d 0 user60 – force to change the password at next login (аналог sudo passwd -e weril)
- chage -m 10 -M 30 -W 7 -E 2016-12-31 user3 – Configure password aging for user3 with mindays (–m) set to 10 (cannot change their password within 10 days after setting it), maxdays (–M) to 30 (password validity of 30 days), warndays (–W) to 7 (user should get warning messages for changing password for 7 days before their account is locked), and account expiry set to December 31, 2016
- passwd -n 7 -x 15 -w 3 user5 – configures password aging for user5 with mindays (–n) set to 7, maxdays (–x) to 16, and warndays (–w) to 3 using the passwd
- passwd -n 7 -x 28 -w 5 user2 – Configure password aging for user2 with mindays (–n) set to 7, maxdays (–x) to 28, and warndays (–w) to 5 using the passwd
-
usermod -e 2016-12-31 user2new
[root@localhost ~]# chage -l user2new | grep Account Account expires : Dec 31, 2016
- show
chage -l user10 – lists password aging attributes for user
# chage -l user10 Last password change : May 24, 2021 Password expires : never Password inactive : never Account expires : never Minimum number of days between password change : 0 Maximum number of days between password change : 99999 Number of days of warning before password expires : 7
[root@localhost ~]# chage -l user1 Last password change : never Password expires : never Password inactive : never Account expires : never Minimum number of days between password change : 0 Maximum number of days between password change : 99999 Number of days of warning before password expires : 7 [root@localhost ~]# chage -l user2 Last password change : Oct 24, 2016 Password expires : Nov 21, 2016 Password inactive : never Account expires : never Minimum number of days between password change : 7 Maximum number of days between password change : 28 Number of days of warning before password expires : 5 [root@localhost ~]# chage -l user3 Last password change : Oct 24, 2016 Password expires : Nov 23, 2016 Password inactive : never Account expires : Dec 31, 2016 Minimum number of days between password change : 10 Maximum number of days between password change : 30 Number of days of warning before password expires : 7
-
- The chage command changes the number of days between password changes and the date of the last password change. This information is used by the system to determine when a user must change
his/her password.
- The chage command changes the number of days between password changes and the date of the last password change. This information is used by the system to determine when a user must change
SU
The su command available in RHEL provides us with the ability to switch into other user accounts.
[user1@localhost ~]$ su Password: [root@localhost user1]#
[user1@localhost ~]$ su -
Password:
Last login: Mon Oct 24 18:27:52 MSK 2016 on pts/0
[root@localhost ~]#
[user1@localhost ~]$ su - user2new
To issue a command as a different user without switching into that user, the –c option is available with su. For example, the firewall-cmd command with the –list-services option requires superuser privileges. user1 can use su as follows and execute this privileged command to obtain desired results
[user1@localhost ~]$ su -c 'firewall-cmd --list-services'
Password:
dhcpv6-client ftp ssh
sudo/sudoers
-
- The sudoers file contains several examples with a brief explanation. It is a good idea to look at those examples for a better understanding.
Добавление конкретного пользователя в sudo (sudoers).
sudo vi /etc/sudoers ## Allow root to run any commands anywhere root ALL=(ALL) ALL weril ALL=(ALL) ALL
## Allows people in group wheel to run all commands
%wheel ALL=(ALL) ALL
user1 ALL=(ALL) ALL
## Allows people in group wheel to run all commands
%wheel ALL=(ALL) NOPASSWD: ALL
user1 ALL=(ALL) NOPASSWD: ALL
[user1@localhost ~]$ sudo cat [user1@localhost ~]$
## Allows people in group wheel to run all commands
%wheel ALL=/usr/bin/date,/usr/bin/cat
user1 ALL=/usr/bin/date,/usr/bin/cat
[user1@localhost ~]$ sudo cat 1
[sudo] password for user1:[user1@localhost ~]$ sudo tail 1
Sorry, user user1 is not allowed to execute '/bin/tail 1' as root on localhost.localdomain.
Cmnd_Alias PKGCMD = /usr/bin/yum, /usr/bin/rpm User_Alias PKGADM = user1, user2, user3, user4, user5 %PKGADM ALL = PKGCMD
groups
Просмотр групп без ID (с ID смотрим по ID).
$ groups user cdrom floppy audio dip video plugdev netdev
Add group shared with GID 9999. В файле /etc/group хранятся все группы (бекап в /etc/group-). groupmod используется для модификации существующей группы.
$ sudo groupadd -g 9999 shared
$ tail -1 /etc/group
shared:x:9999:
$ sudo usermod -G shared test_user1
$ sudo usermod -G shared test_user2
$ tail -1 /etc/group
shared:x:9999:test_user1,test_user2 # shared - имя группы,
х - пароль зашифрован (чаще всего отсутствует и хранится в отдельном файле gshadow),
9999 - id группы,
test_user1/2 - члены группы
Managing group accounts involves creating and modifying groups, adding and deleting group members and administrators, setting and revoking group-level password, and deleting groups. RHEL provides a set of tools and the graphical User Manager for performing these operations. The command toolset is part of the shadow-utils package and the User Manager GUI application becomes available when the system-config-users package is installed on the system.
groupadd – Adds a group. The groupadd command picks up the default values from the login.defs file. Command adds entries to the group and gshadow files for each group added to the system.
–g/–gid – Specifies the GID to be assigned to the group.
–o/–non-unique – Creates a group account sharing the GID of an existing group. When two groups share a common GID, members of each group get identical rights on each other’s files. This should only be done in specific situations.
–r – Creates a system group account with a GID below 1000.
groupname Specifies a group name.
Create group account admins with GID 6666:
[root@localhost ~]# groupadd -g 6666 admins
Create group account tests sharing the GID of group admins:
[root@localhost ~]# groupadd -o -g 6666 tests
groupmod – Modifies group attributes. most options identical groupadd.
[root@localhost ~]# groupmod -n tests666 tests
Change the GID of tests666 group to 6666
[root@localhost ~]# groupmod -g 6666 tests666
Usermod – Add user user1 to group admins while retaining the user’s existing memberships
[root@localhost ~]# usermod -a -G admins user1 [root@localhost ~]# id user1 uid=1000(user1) gid=1000(user1) groups=1000(user1),6666(admins) [root@localhost ~]# groups user1 user1 : user1 admins
groupdel – Deletes a group. Removes entries for the specified group from both group and gshadow files.
[root@localhost ~]# groupdel admins
gpasswd – can be used to add group administrators, add or delete group members, assign or revoke a group password, and disable access to a group via the newgrp command. The root user can perform all of these tasks, while the group administrator can perform only the last three. This command prompts to change the group password if invoked by root or the group administrator. The gpasswd command updates the group and gshadow files. This command picks up the default values from the /etc/login.defs file.
–A/–administrators – Adds one or more group administrators. Inserts an entry in the third field of the gshadow file.
–a/–add – Adds a group member. Inserts an entry in the fourth field of both group and gshadow files.
–d/–delete – Deletes a group member.
–M/–members – Substitutes all existing group members.
–R/–restrict – Disables access to a group for non-members. Members with a password can still join the group.
–r/–remove-password – Revokes the password set on a group. Only group members can join the group
If a password is set the members can still use newgrp(1) without a password, and non-members must supply the password. Group passwords are an inherent security problem since more than one person is permitted to know the password. However, groups are a useful tool for permitting co-operation between different users.
gpasswd -A user1,user2new admins - Add user1 and user2new as administrators to the group gpasswd -a user2new -a user3 admins - Add user2new and user3 as members to the group gpasswd -M user4 admins - Substitute user2new and user3 with user4 as a member of the group gpasswd admins - Set a password on the group
Log in as user4 and run the groups command to list group membership for user4. The primary group is listed first.
[user4@localhost ~]$ groups user4 admins
Temporarily change the primary group for user4 to admins:
[user4@localhost ~]$ newgrp admins
Verify the new primary group membership for user4. It should be listed first in the output.
[user4@localhost ~]$ groups admins user4
Return to the original primary group by issuing the exit command or pressing Ctrl+d, and verify
[user4@localhost ~]$ exit logout [root@localhost ~]# su - user4 Last login: Tue Oct 25 16:53:33 MSK 2016 on pts/1 [user4@localhost ~]$ groups user4 admins
questions
When invoked with only the -D option, useradd will display the current default values. When invoked with -D plus other options, useradd will update the default values for the specified options.
~# useradd -D GROUP=100 HOME=/home INACTIVE=-1 EXPIRE= SHELL=/bin/sh SKEL=/etc/skel CREATE_MAIL_SPOOL=no
5. Name the four local user authentication files.