Linux users and groups

Posted by amob005 on Tue, 04 Jan 2022 10:53:34 +0100

Why introduce users and groups?
- permission management (which files can be read and written by a user and which processes can be started by a user)
- Resource Management (storage resources, IO, CPU resources)

[root@localhost ~]# id root
uid=0(root) gid=0(root) group=0(root)
Each user has a unique uid and gid
 A user can have different groups
 A group can have different users

useradd add userdel delete usermod modify users query (view the current login user)

What files are involved in creating a user?
By default, creating a user will add a group with the same name as the user, and the user will be added to the group by default

1. And account related documents


Save basic information of user account

[root@hahah ~]# cat /etc/passwd
  • Field 1: user name
  • Field 2: password placeholder, usually x or *.
    Because the file can be accessed by anyone, the password is not secure;
    The real test password is placed in / etc/shadow
  • Field 3: user id
  • Field 4: id of the basic group to which it belongs
  • Field 5: user description information
  • Field 6: home directory location
  • Field 7: login shell information

Find out the user whose uid in linux system is greater than 2000, and display its name, uid, shell and home directory

[root@192 nginx]# cat /etc/passwd|awk -F : '$3>2000 {print $1,$3,$7,$6}'
nobody 65534 /sbin/nologin /


[root@192 ~]# cat /etc/shadow

Second field: Password Field
*The operating system comes with no password
!! User built, no password
Prompt: if the password field is empty, the password will be cleared.
View users without passwords

cat /etc/shadow|awk -F: 'BEGIN{i=0}length($2)<=2{print $1,"No password set";i++}END{print "Altogether"i"Users"}'
[root@localhost ~]# diff /etc/passwd /etc/passwd-
< sc:x:1023:1023::/home/sc:/bin/bash

/etc/passwd - and / etc/shadow - are backup files of / etc/passwd and / etc/shadow. There is always one operation less than the original file

2. Group information related files


[root@192 ~]# cat  /etc/group
hejin13: x :1022: 
sc : x: 1023:



3. Home directory information related files

Creating a user creates a folder with the same name in / home by default


User environment default settings file
Copy the files under / etc/skel / to the user's home directory

[root@localhost skel]# ll -a
 Total consumption 24
drwxr-xr-x.  2 root root   76 11 November 15:31 .
drwxr-xr-x. 80 root root 8192 11 November 15:31 ..
-rw-r--r--.  1 root root    0 11 November 15:31 aa.txt
-rw-r--r--.  1 root root   18 7 May 21, 2020 .bash_logout
-rw-r--r--.  1 root root  141 7 May 21, 2020 .bash_profile
-rw-r--r--.  1 root root  376 7 May 21, 2020 .bashrc


User environment default property settings file
– specifies the starting date of uid, the number of days the password expires, and the encryption algorithm of the password

  • 0 root superuser
  • 1 ~ 201 users (system users and program users) after the system is installed: the function is to start or log in a program
  • 201 ~ 999 newly created system users do not have home directory. They are managed by the system and do not need to log in
  • 1000 ~ 60000 new users

The UID of superuser root is 0
UID1-999 program user
The UID of ordinary users is greater than or equal to 1000


Mail directory
/Create a file with the same name under var/spool/mail

Exercise 1: find users with uid greater than 1000

Find out the users with uid greater than 1000 in the system, and display the name, uid, home directory and shell information

[root@localhost /]# awk -F: '$3>=1000{print $1,$3,$6,$7}' /etc/passwd
hejin12 1021 /home/hejin12 /bin/bash
hejin13 1022 /home/hejin13 /bin/bash
sc 1023 /home/sc /bin/bash
sc2 1024 /home/sc2 /bin/bash
>>> import os
>>> os.geteuid()  Effective user root User valid uid Is 0
>>> os.getegid()
>>> os.getpid()
>>> help(os.walk)
# Output the file name in the folder by swimming through the tree, up or down.
>>> list(os.walk("."))
[('.', [], ['passwd', 'access.log', 'config', 'ifcfg-ens33', 'hosts', 'test2.txt', 'path.txt', 'selinux', 'sshd_config', 't.txtr', 't.txt', '.test.txt.swp', 'test.txt'])]

Exercise 2: verify that the user exists

The sys module and os module will be used to verify the existence of users with python scripts

os. The return value of system (CMD) is the exit status code of the script. There will only be 0 (success), 1,2
os.popen(cmd) returns the output of the script execution as the return value
Mode 1

import sys
import os
username = sys.argv[1]

result = os.system(f"id {username}")
if result == 0:
# if not result:
    print("User presence")
    print("user does not exist")

Mode 2

import sys
user1 = sys.argv[1]
with open("/etc/passwd") as f:
    userList = []
    for data in f:
        data = data.strip()
        lst = data.split(':')
    if user1 in userList:        print("User presence")
        print("user does not exist")

4. ftp protocol (File Transfer Protocol)

ftp is a file transfer service, which is mainly used to upload and download files and share files.
vsftpd is the abbreviation of "very secure TTP daemon". It is a completely free and open source ftp server software.

  • 1. Install vsftp service
    yum install vsftpd -y
    Check if vsftpd is installed
    rpm -qa|grep vsftpd
  • 2. Install client software
    yum install lftp ftp -y
    lftp and ftp are both ftp clients
  • 3. Start service
    Basically, all services installed using yum can be started using systemctl;
    systemctl start vsftpd
    Check whether the startup is successful
    ps aux|grep vsftpd
  • 4. Edit profile
    vim /etc/vsftpd/vsftpd.conf
    Line 12, the default is NO, and anonymous users are not allowed to log in
    The vsftpd service in CentOS 8 does not allow anonymous users to log in by default
    anonymous_enable=NO is changed to YES
    To reload the configuration file or restart the service
    systemctl restart vsftpd
  • 5. Use
[root@sanchuang-linux ~]# cat /etc/passwd
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin	 # Note: anonymous users of vsftpd are public users
#Note: / var / ftp FTP is the user's home directory file
[root@sanchuang-linux ~]# lftp ftp@	 # Note: use ftp user to access the login program
 password: 							  Note: ftp Is the default user
[root@kafka01 ~]# ftp  
Connected to (
220 (vsFTPd 3.0.3)
Name ( ftp   #The program user ftp in the system uses ftp anonymous user login
331 Please specify the password.
Password:      #The password input will not be set directly by typing enter
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.

5. useradd command

Format: useradd [options]... User name
Common options
-u: Specifies the UID tag number
-d: Specify the host directory. The default is / home / user name
-e: Specify account expiration time
-g: Specifies the user's base group name (or GID number)
-G: Specifies the user's additional group name (or GID number)
-M: The host directory is not established and initialized for the user
-s: Specifies the login Shell of the user
-c: User annotation description information can tell others the purpose of creating and changing users
-r: New system users will not have a new home directory

adduser username does not create a home directory by default

Count several shell information in the current / etc/passwd

That is, what operations the user performs as soon as he logs on

[root@localhost etc]# cat passwd | awk -F: '{print $7}'|sort -n|uniq -c
     27 /bin/bash   
      1 /bin/sync
      1 /sbin/halt
     19 /sbin/nologin   #ssh Remote Login and su local login are not available
      1 /sbin/shutdown
[root@localhost etc]# awk -F: '{print $7}'   /etc/passwd |sort|uniq
/bin/bash    #shell information of the system default user
/bin/sync    #Brush memory cache to disk
/sbin/halt   #Log in and shut down
/sbin/nologin  #The user cannot log in to the system
/sbin/shutdown  #Shut down

useradd -s /sbin/nologin sc01 neither ssh nor su can log in
useradd -s /sbin/halt sc02 shutdown upon login

Find out that the uid in the system is greater than 1000, the shell information is / bin/bash, and the user name contains the user information of sanchuang (user name, user id, home directory)

[root@localhost ~]# cat /etc/passwd | awk -F: '$3>1000{print  $1,$3,$6,$7}'|grep /bin/bash|grep sangchuang
sangchuang03 1028 /home/sangchuang03 /bin/bash
sangchuang04 1029 /home/sangchuang04 /bin/bash

[root@localhost ~]# grep "sangchuang"  /etc/passwd |grep /bin/bash |awk -F: '$3>1000{print $1,$3,$6}'
sangchuang03 1028 /home/sangchuang03
sangchuang04 1029 /home/sangchuang04

[root@localhost ~]# awk -F: '$3>1000  && $1~/sangchuang/ && $7=="/bin/bash"  {print $1,$3,$6}' /etc/passwd
sangchuang03 1028 /home/sangchuang03
sangchuang04 1029 /home/sangchuang04
#Specifies the home directory, but is restricted by the security mechanism selinux
#selinux is a security subsystem of linux kernel. Because the security rules are too cumbersome, it is usually closed
[root@localhost ~]# useradd -d /tmp/sangchuang05 sangchuang05
useradd: cannot set SELinux context for home directory /tmp/sangchuang05
# Modify the security mechanism and restart the system to take effect
[root@localhost ~]# vim /etc/selinux/config
SELINUX=enforcing ->SELINUX=disabled
# Getenforceto see if it takes effect
#Specify group name
[root@localhost ~]# useradd -g sanchuang01 -G  sangchuang04,sangchuang05  sangchuang07
[root@localhost ~]# id sangchuang07
uid=1031(sangchuang07) gid=1026(sanchuang01) group=1026(sanchuang01),1029(sangchuang04),1030(sangchuang05)

6. userdel command

Format: userdel [-r] username
When the - r option is added, it means to delete the user's host directory
When the - f option is added, it means forced deletion

[root@localhost ~]# userdel sangchuang04  #Delete user accounts without deleting related files. 
userdel: Group“ sangchuang04"It was not removed because it contains other members.

7. usermod command

Format: usermod [options]... User name
Common options
-u: Modify UID
-d: Specify the host directory. The default is / home / user name
-e: Specify account expiration time
-g: Specifies the user's base group name (or GID number)
-G: Specifies the user's additional group name (or GID number)
-s: Specifies the login Shell of the user

-l: Change the login name of the user account
-50: L ock user account
-U: Unlock user account

[root@localhost ~]# usermod -u 1200 sc2  #Modify UID
[root@localhost ~]# id sc2
uid=1200(sc2) gid=1024(sc2) group=1024(sc2)
[root@localhost ~]# usermod -d /temp/ooo ooo  #Modify home directory
[root@localhost ~]# tail /etc/passwd
[root@localhost ~]# usermod -g 1026 ooo   #Modify gid
[root@localhost ~]# id ooo
uid=1025(ooo) gid=1026(sanchuang01) group=1026(sanchuang01)
[root@localhost ~]# usermod -G 1027 ooo #Modify group id
[root@localhost ~]# id ooo
uid=1025(ooo) gid=1026(sanchuang01) group=1026(sanchuang01),1027(snagchuang02)
[root@localhost ~]# usermod -c "Modify comments" sanchuang11 #Modify comments
[root@localhost ~]# tail /etc/passwd
sanchuang11:x:1033:1033:Modify comments:/tmp/sanchuang11:/bin/bash
sanchuang12:x:1034:1034:Description information:/home/sanchuang12:/bin/bash

Account locking is to modify the password field stored in the system and fail to verify the password to achieve the purpose of account locking
The locked state is actually adding a password in front of the password field!

[root@localhost ~]# usermod -L sangchuang07 lock
[root@localhost ~]# usermod -U sangchuang07 unlock

8. passwd command

Format: passwd [options]... User name
Common options:
-d: Clear the user's password so that he can log in without a password

  • l: Lock user account
    -u: Unlock user account
    -S: Check the status of the user account (whether it is locked)
    – stdin: receive another command stdout as stdin standard input setting password

The root user can change all user passwords without complexity
Ordinary users can only modify their own passwords, which requires password complexity

#Use standard input to set the password
[root@kafka01 lianxi]# echo 12345678 |passwd sanchuang13 --stdin

Exercise 1

Create 20 users, the user name starts with beautwen, and the specified home directory is / tmp/lianxi/beautiwen01... 20
The login shell is specified as / usr/bin/sh
Prompt: judge before creating. If the user exists, delete the current user

Exercise 2


add group

[root@localhost lianxi]# groupadd -g 5000 sanle
[root@localhost lianxi]# less /etc/group

10, groupmems

You can add or delete group members by modifying them
groupmems -g group name - a user name add users to this group
groupmems -g group name - l view users in the group


[root@kafka01 lianxi]# groupdel sanle  #Delete the group sanle
groupdel: cannot remove the primary group of user 'sanle1'#There is a member of sanle1 in the group, so it can't be deleted
[root@kafka01 lianxi]# userdel -r sanle1  #Delete member first
[root@kafka01 lianxi]# groupdel sanle     #Delete group again


[root@localhost lianxi]# groupadd -g 6000 sanchuang  #Add user specified GID
[root@localhost lianxi]# groupmod -g 4000 sanchuang  #Modify GID
[root@localhost lianxi]# groupmod -n sanchuang2 sanchuang  #Modify group name
[root@localhost lianxi]# tail -n 1 /etc/group

13. newgrp modify valid group

The user must be a member of a group to change a valid group
Effective group: when creating a new folder or file, the effective group is who belongs to the group

[root@localhost lianxi]# id usersanle
uid=1329(usersanle) gid=1329(usersanle) group=1329(usersanle),5000(sanle)
[usersanle@localhost ~]$ touch bb
[usersanle@localhost ~]$ ls -al
-rw-rw-r--   1 usersanle usersanle    0 11 October 17:51 bb
[usersanle@localhost ~]$ newgrp sanle
[usersanle@localhost ~]$ touch cc
[usersanle@localhost ~]$ ll
-rw-rw-r-- 1 usersanle usersanle 0 11 October 17:51 bb
-rw-r--r-- 1 usersanle sanle     0 11 October 17:55 cc
             Owner      Genus group

14. / etc/skel file

When creating a new user account, it will be copied to the host directory
It mainly controls the user initialization environment configuration
.bash_profile is executed every time a user logs in
. bashrc is executed when the user logs out
.bash_logout is executed every time the user enters a new bash environment
.bash_history user's history command. The historical command will be written to this file when exiting

/etc/bashrc is executed every time a new bash is turned on
/etc/profile is executed when the system is turned on
su - sanle: . bash_profile and bashrc will be executed
su sanle : . bashrc will only execute this file

#When I landed
.bash_profile  --> ~/.bashrc  --> /etc/bashrc

#When entering the new bash
.bashrc --> /etc/bashrc

15. su command

[root@localhost lianxi]# su - usersanle 
#Along with the environment, switch to usersanle, under the home directory bashrc   .bash_profile will be executed

[root@localhost lianxi]# su usersanle  
#Only the user is switched, the environment variable is not switched, and will only be executed bashrc

16. who/w command

View the user information that has logged in to the host

[root@kafka01 ~]# w  #It shows two more lines than who
 14:43:32 up  1:19,  3 users,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    11:10    2:35m  0.19s  0.19s -bash
root     pts/1    11:16    3:27m  0.01s  0.01s -bash
root     pts/2    14:42    1.00s  0.02s  0.01s w
User IDTerminals usedFrom which sideOnline timeDead timeCPU usageaction

17. last/lastlog command

last displays the user's recent login information
lastlog view the last login of all users

18. Audit security audit

system safety
Record some actions of a user
Record some operations of a program
Detailed explanation of audit


  • How do I know if a user exists in linux?
    1. id user name view
    2. View / etc/passwd

  • How to disable a user from logging in to the linux system?
    1. passwd -l username lock
    2. usermod -L user name lock
    3. useradd -s /sbin/nologin {username} modify the login shell

  • How do I know which groups a user belongs to?
    1,groups uname
    2. View with / etc/passwd and / etc/group
    3,id uname

  • How do I know which users are now logged in to linux?

  • Which users have logged in to the linux system?
    last displays the user's recent login information
    lastlog view the last login of all users

  • How to reset the password for the user?
    echo password | passwd sanchuang13 --stdin

  • What if the root password of linux is forgotten?
    Enter the single user mode and modify the root password

  • How to kick out users who have logged in to the system?
    pkill -KILL -t pts/0 (pts/0 is the user terminal number seen by the w command)
    ps aux | grep sshd view sshd process PID
    kill -9 10482 kill the sshd process PID logged in by test

  • And prevent it from logging into the system again?
    1. Kick out the suspicious root login user and change the password immediately
    2.sshd—>/etc/hosts.deny hosts.allow —>ip
    3./etc/ssh/sshd_ Config -- > denyusers -- > User
    4. Change / bin/bash to / sbin/nologin

Topics: Linux Operation & Maintenance bash