mycpen

Mycpen

记录学习历程与受益知识
github
telegram
bilibili

14_Linux Basics - Users and Groups 1

1. Practice#

Example 1
---------------------------------------------------------------------------------------------------------------------------------
menu(){
    echo "1. Monitor memory usage, if memory usage exceeds 80%, give a reminder"
    echo "2. Scan local network IPs, check which IP addresses are in use"
    echo "3. Monitor if the file /etc/passwd has been modified, check every 5 minutes"
    echo "4. Monitor if the nginx process exists, if not, give a corresponding reminder"
}

option_1(){
    total=`free -m|grep -i mem|tr -s " "|cut -d " " -f2`
    #free=`free -m|grep -i mem|tr -s " "|cut -d " " -f4`
    used=`free -m|grep -i mem|tr -s " "|cut -d " " -f3`
    used_rate=`echo "scale=4;$used/$total" |bc`
    #used_1=`echo "$total*0.8"|bc `
    result=` echo "$used_rate>0.8"|bc `
    #echo $result
    if (( $result  == 1 ))
    then
        echo -e "\e[31mUsage exceeds 80%, please expand memory in time to avoid unnecessary losses\e[0m"
    else
        echo  " nothing to do"
    fi
}

option_2(){
        for ip in `seq 255`
    do
        ( ip_full=192.168.0.$ip
        ping -c 1 $ip_full &>/dev/null && echo $ip_full >>up.txt || echo $ip_full >>down.txt
        ) &     # Note: Run in the background as a subprocess
    done
wait # Parent process waits for child processes to complete before exiting
}

option_3(){
    check_num=`diff /etc/passwd /lianxi/passwd |wc -l`
    [[ check_num -eq 0 ]] && echo "File has not been modified" || echo "File has been modified"
}

option_4(){
    pidof nginx && echo "nginx is running" || echo "nginx is down"
}

menu
read -p "Please enter your choice:" option
case $option in
1)
    option_1
    ;;
2)
    option_2
    ;;
3)
    option_3
    ;;
4)
    option_4
    ;;
*)
    echo "Please enter 1-4"
esac
Example 2: Repeat Selection
--------------------------------------------------------------------------------------------
Repeat Selection
while : 
do
done

echo "#########################"
echo "1. View memory usage"
echo "2. Scan local network IPs"
echo "3. Check if the file has been modified"
echo "4. Check nginx process"
echo "5. Exit"
echo "#########################"

while : 
do
    read -p "Please enter your choice:" options
    case $options in
    1)
    /root/shell/mem.sh
    ;;
    2)
    /root/shell/scan_ip.sh
    ;;
    3)
    /root/shell/passwd_test.sh
    ;;
    4)
    /root/shell/ngnix_test.sh
    ;;
    5)
    echo "Exiting"
    exit
    ;;
    *)
    echo "1-4"
    esac
done
--------------------------------------------------------------------------------------------
Example 3: Using awk to get
case $options in

1)
    memory_monitor(){
        total=`free -m |grep Mem |awk '{print $2}'`
        used=`free -m |grep Mem |awk '{print $3}'`
        use_rate=`echo "scale=2;$used/$total" |bc`
        result=`echo "$use_rate>0.8" |bc`
        if(( $result == 1 ))
        then
            echo "Memory usage exceeds 80%!!!"
        else
            echo "Memory usage is good!"
        fi
    }
    memory_monitor
    ;;

2. User Group Users and Groups#

2.1 Common Commands#

id view
useradd create
userdel delete
passwd create user password
su switch user
usermod change user information

2.2 Why introduce users and groups?#

  1. Security

  2. Permission management

  3. Resource control

Access to files can be controlled for reading and writing

Process management --> Who can manage

2.3 Users and Groups#

Each user has a unique UID
Each group also has a unique GID

A user can belong to different groups
A group can have different users # Note: Many-to-many relationship

Users and groups --> Permission resource control
When a user joins a group, they can have the permissions of that group
By default, when creating a user, a group with the same name as the user will be added

[root@sanchuang-linux ~]# id chenpeng			# Note: id view user and group information
uid=1030(chenpeng) gid=1030(chenpeng) group=1030(chenpeng)	
--------------------------------------------------------------------------------------------
[root@localhost ~]# useradd sanchuang
[root@localhost ~]# id sanchuang
uid=1000(sanchuang) gid=1000(sanchuang) group=1000(sanchuang)
[root@localhost ~]# less /etc/passwd
[root@localhost ~]# less /home/sanchuang/
[root@localhost ~]# passwd sanchuang
Changing password for user sanchuang.
New password:
Invalid password: Password is less than 8 characters
Re-enter new password:
passwd: All authentication tokens have been successfully updated.
[sanchuang@localhost ~]$ 		# Note: Default location after login is the user's home directory (logged in as user sanchuang)
[root@localhost ~]# less /etc/shadow			# Note: shadow stores user password information
[root@localhost ~]# less /etc/shadow
shadow   shadow-  
[root@localhost ~]# less /etc/passwd
passwd   passwd-  
[root@localhost ~]# diff /etc/passwd /etc/passwd-	# Note: passwd- backup file, each time there will be one less latest operation
21d20												# Note: Can roll back to the previous version
< sanchuang:x:1000:1000::/home/sanchuang:/bin/bash
[root@localhost ~]# diff /etc/shadow /etc/shadow-	# Note: shadowd- backup file, each time there will be one less latest operation
21d20												# Note: Can roll back to the previous version
< sanchuang:$6$dKQsah/D$6sm6owwvDEnVs8BclDWQZ7meYSaMf5Y7AofxzxwxO0PPrvzqHHVCer1G656iY2gE.sUOarUl9beKi2usYdATQ1:18571:0:99999:7:::
[root@localhost ~]# less /etc/group					# Note: Stores group information
[root@localhost ~]# less /etc/gshadow				# Note: Stores group password information

[root@localhost ~]# cd /home/sanchuang/				# Note: New user has three hidden files
[root@localhost sanchuang]# ls
[root@localhost sanchuang]# ls -al		# Note: New user account is copied from /etc/skel directory
Total usage 12
drwx------. 2 sanchuang sanchuang  62 Nov  5 10:25 .
drwxr-xr-x. 3 root      root       23 Nov  5 10:25 ..
-rw-r--r--. 1 sanchuang sanchuang  18 Apr  1 2020 .bash_logout
-rw-r--r--. 1 sanchuang sanchuang 193 Apr  1 2020 .bash_profile
-rw-r--r--. 1 sanchuang sanchuang 231 Apr  1 2020 .bashrc
[root@localhost sanchuang]# cd /etc/skel/			# Note: Template, copy one over
[root@localhost skel]# ls -al
Total usage 24
drwxr-xr-x.  2 root root   62 Oct  6 16:33 .
drwxr-xr-x. 77 root root 8192 Nov  5 10:27 ..
-rw-r--r--.  1 root root   18 Apr  1 2020 .bash_logout
-rw-r--r--.  1 root root  193 Apr  1 2020 .bash_profile
-rw-r--r--.  1 root root  231 Apr  1 2020 .bashrc

[root@localhost skel]# less /etc/login.defs		# Note: About account setting information
# Min/max values for automatic uid selection in useradd
#
UID_MIN                  1000					# Note: Up to 59000 users can be created
UID_MAX                 60000
# System accounts
SYS_UID_MIN               201
SYS_UID_MAX               999
CREATE_HOME     yes									# Note: Create home directory
ENCRYPT_METHOD SHA512								# Note: Specify the method for encrypting user passwords

[root@localhost skel]# ls /etc/group				# Note: Groups also have backup files
group   group-  
[root@localhost skel]# ls /etc/gshadow
gshadow   gshadow-  

[root@localhost spool]# cd /var/spool/mail/			# Note: Mail directory
[root@localhost mail]# ls							# Note: Create a file with the same name under /var/spool/mail/
sanchuang

[sanchuang@localhost ~]$ less /etc/shadow			# Note: Ordinary users do not have permission to view /etc/shadow which stores password information
/etc/shadow: Permission denied								 # Note: Only root user can read

2.4 Files Involved in User Creation#

Account Information Related Files

  • /etc/passwd --> Stores user-related information

  • /etc/shadow --> Stores user passwords

  • /etc/passwd- and /etc/shadow- are backup files of /etc/passwd and /etc/shadow, always one operation less than the original files

Group Related Files

  • /etc/group --> Stores group information

  • /etc/gshadow --> Stores group passwords

  • /etc/group- and /etc/gshadow- backup files

Default User Environment Settings

  • When creating a user, files from /etc/skel/ are copied to the user's home directory

User's Home Directory

  • By default, a folder with the same name will be created under /home

User Default Attribute Setting File

  • /etc/login.defs

Mail Directory

  • A file with the same name is created under /var/spool/mail/

2.5 Detailed Explanation of /etc/passwd File#

[root@localhost mail]# cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
sanchuang:x:1000:1000::/home/sanchuang:/bin/bash
·Use: Separator
·Field 1: Username
·Field 2: Password placeholder, usually "x" or "*" (because this file is readable by anyone, the actual password is stored in /etc/shadow)
·Field 3: User ID							# Note: -u specifies
·Field 4: User's primary group ID					 # Note: -g specifies primary group
·Field 5: User description information						  # Note: New users generally do not set this (no -c option)
·Field 6: Home directory							# Note: Absolute path of home directory			(-d option)
·Field 7: Login shell information
Example
--------------------------------------------------------------------------------------------
[root@localhost ~]# ls -ld /etc/shadow
----------. 1 root root 2330 Nov  5 20:51 /etc/shadow		# Note: Ordinary users/groups cannot read or execute
[root@localhost ~]# ls -ld /etc/passwd
-rw-r--r--. 1 root root 2006 Nov  5 20:51 /etc/passwd

#Note: Configuration files installed through yum are generally placed in /etc

2.6 Exercise: Find users in the system with UID greater than 1000, displaying their name, UID, home directory, and shell#

Find users in the system with UID greater than 1000, displaying their name, UID, home directory, and shell

[root@sanchuang-linux ~]# awk -F: '$3>1000{print $1,$3,$6,$7}' /etc/passwd
chenpeng 1030 /home/chenpeng /bin/bash

#Note: Using cat and directly using awk consumes similar memory
#Note: Syntax: awk options 'pattern+action' file		# Note: If no pattern is specified, the entire text is captured

2.7 Exercise: Find out how many types of shell information are in /etc/passwd#

Find out how many types of shell information are in /etc/passwd

2.8 Detailed Explanation of useradd#

Shell Settings
[root@sanchuang-linux ~]# awk -F: '{print $7}' /etc/passwd |sort|uniq		# Note: Sort and remove duplicates
/bin/bash		# Note: System default user shell environment information --> Normal shell used
/bin/sync		# Note: Flush the cache in memory to disk --> Similar to Python's fp.flush()
/sbin/halt		# Note: Shut down upon login
/sbin/nologin	# Note: User cannot log in (not allowed to log in)
--------------------------------------------------------------------------------------------
#Note: The shutdown command will execute sync to flush the cache in memory to disk
[root@localhost ~]# sync
--------------------------------------------------------------------------------------------
#Note: Use the which command to view the absolute path of the command
[root@localhost ~]# which sync
/usr/bin/sync
Executing a command in /bin/bash will take us to our current terminal environment.

3. Relationship Between Users and Groups#

  • Each account has a unique UID

  • Each group also has a unique GID

  • Multiple accounts can belong to the same group

image-20220812074315487

Files Related to Accounts

  • /etc/passwd, /etc/shadow

Files Related to Groups

  • /etc/group, /etc/gshadow

File Source in Account's Home Directory

  • When creating a new user account, files are copied from the /etc/skel directory # Note: Initialize user home directory

Default Attribute File for Accounts

  • /etc/login.defs

File Used to Save Basic User Account Information

  • File Location: /etc/passwd

  • Each line corresponds to a user account record

  • Field 1: Username

  • Field 2: Password string or password placeholder “x

  • Field 3: UID of the user account

  • Field 4: GID of the primary group account

  • Field 5: User description information

  • Field 6: Home directory

  • Field 7: Login shell information


User Accounts:

  • Superuser root
  • Program user
  • Ordinary user

UID (User Identity, User Identification Number)

  • The UID of the superuser root is 0
  • The UID of program users is 1-999
  • The UID of ordinary users is greater than or equal to 1000

6. Adding and Deleting Users#

useradd Command

  • Format: useradd [options]... username

Common Command Options

  • -u: Specify UID number
  • -d: Specify home directory, default is /home/username
  • -e: Specify account expiration date
  • -g: Specify the user's primary group name (or GID)
  • -G: Specify the user's supplementary group name (or GID)
  • -M: Do not create and initialize a home directory for the user
  • -s: Specify the user's login shell
  • -c: User comment description information
  • -r: Create a system user, no new home directory will be created

#Note: Each time a new user is created, the UID will be incremented by 1 from the previous user's UID
#Note: By default, new users start from 1001

Shell Settings

/bin/bash			# Note: System default user shell environment information --> Normal shell used
/bin/sync			# Note: Flush the cache in memory to disk --> Similar to Python's fp.flush()
/sbin/halt			# Note: Shut down upon login
/sbin/nologin		# Note: User cannot log in, neither ssh nor su can log in
/sbin/shutdown		# Note: Shut down upon login
Example: -s /sbin/nologin
--------------------------------------------------------------------------------------------
#Note: This machine is used to run services, cannot log in
[root@localhost mail]# useradd -s /sbin/nologin sanchuang2
[root@localhost mail]# echo 123456|passwd sanchuang2 --stdin
Changing password for user sanchuang2.
passwd: All authentication tokens have been successfully updated.
[root@localhost mail]# ssh sanchuang2@192.168.136.136	#Note: ssh login to local sanchuang2
……………………………………
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.136.136' (ECDSA) to the list of known hosts.
sanchuang2@192.168.136.136's password: 
This account is currently not available.	# Note: Prompt user is unreachable, because sanchuang2's shell is nologin, cannot log in directly
Connection to 192.168.136.136 closed.
[root@localhost ~]# su - sanchuang2			# Note: Cannot switch
Last login: Thu Nov  5 11:49:14 CST 2020 from 192.168.136.136pts/2
This account is currently not available.
--------------------------------------------------------------------------------------------
[root@localhost ~]# usermod -s /bin/bash sanchuang2		# Note: usermod -s change user's shell information
[root@localhost ~]# cat /etc/passwd|grep sanchuang2
sanchuang2:x:1001:1001::/home/sanchuang2:/bin/bash

Exercise: Display users in the system with UID greater than 1000 and whose username contains sanchuang (username, userId, user home directory)#

Display users in the system with UID greater than 1000 and whose username contains sanchuang (username, userId, user home directory)

[root@localhost ~]# awk -F: '$3>1000{print $1,$3,$6}' /etc/passwd
sanchuang2 1001 /home/sanchuang2
Method 1
[root@localhost ~]# awk -F: '$3>1000{print $1,$3,$6}' /etc/passwd |grep sanchuang
sanchuang2 1001 /home/sanchuang2
Method 2
[root@localhost ~]# awk -F: '$3>1000 && $1 ~ /sanchuang/{print $1,$3,$6}' /etc/passwd
sanchuang2 1001 /home/sanchuang2			# Note: $1 ~ /sanchuang/ matches sanchuang

7. Processes#

Process: A program that is currently running

Program: A collection of code, stored on disk

A process is the basic unit of resource allocation in a computer

The core of a process: Process Control Block (PCB)

PCB generally includes

  1. pid Unique identifier for the process

  2. Effective user information -euid, egid (usually uid, gid) # Note: This indicates which user the process belongs to

  3. Program status

  4. Program priority

  5. Program context


8. Using the os Module in Python to View Current Process User Information#

Using the os Module in Python to View Current Process User Information

>>> import os
>>> os.geteuid()					# Note: Get the current process user's UID information
0									# Note: 0 indicates root user
>>> os.getuid()						# Note: Usually, uid and euid are the same
0
--------------------------------------------------------------------------------------------
Ordinary user importing os module
[sanchuang2@localhost ~]$ python3
>>> import os
>>> os.geteuid()
1001
>>> os.getuid()
1001
[sanchuang2@localhost ~]$ id sanchuang2
uid=1001(sanchuang2) gid=1001(sanchuang2) group=1001(sanchuang2)

9. FTP Protocol (File Transfer Protocol)#

9.1#

vsftpd service and local users

FTP service is for file transfer, uploading or downloading a file to a specified location

FTP is a file transfer service, mainly used for uploading and downloading files, achieving file sharing

Both anonymous users and local users can log in to the FTP service, and they can only operate files or folders under their home directory after logging in

Three types of users:

  1. Anonymous users

  2. Local users # Note: FTP transfer can use local Linux users; SSH login can also use local users

  3. Virtual users

============================================================================================
1. Service Installation
[root@sanchuang-linux ~]# yum install vsftpd
--------------------------------------------------------------------------------------------
2. Start Service
[root@sanchuang-linux ~]# service vsftpd restart
Redirecting to /bin/systemctl restart vsftpd.service
[root@sanchuang-linux ~]# ps -ef |grep vsftp			# Note: Default root user starts
root        3377       1  0 14:51 ?        00:00:00 /usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf
root        3379    3184  0 14:52 pts/1    00:00:00 grep --color=auto vsftp
--------------------------------------------------------------------------------------------
3. Install Client
#Note: In CentOS 8, vsftpd service does not allow anonymous users to log in by default
    To use anonymous user (ftp) to log in, modify the configuration in /etc/vsftpd/vsftpd.conf to anonymous_enable=YES
#Note: Restart the vsftpd service after modifying the configuration

After logging in, it will read the home directory files of the ftp user in the system by default
-----------------------------------------------------
[root@sanchuang-linux ~]# yum install lftp -y			# Note: lftp is the client for vsftpd
[root@sanchuang-linux ~]# yum install ftp	-y			# Note: ftp is also the client for vsftpd
#Note: Both are FTP clients
============================================================================================
[root@sanchuang-linux ~]# lftp ftp@192.168.0.27		# Note: Log in as ftp user
Password: 											   # Note: ftp is the default user
[root@localhost ~]# ftp 192.168.136.136				# Note: Log in to FTP service
………………………………
Name (192.168.136.136:root): ftp					# Note: Anonymous user ftp login
331 Please specify the password.
Password:											# Note: Press Enter
230 Login successful.
………………………………
ftp> 
============================================================================================
[root@localhost ~]# cat /etc/passwd
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin			# Note: vsftpd's anonymous user, public user
#Note: /var/ftp is the home directory file for the ftp user
============================================================================================
[root@localhost ~]# vim /etc/vsftpd/vsftpd.conf 	# Note: Enable anonymous user login in CentOS 8
anonymous_enable=YES									# Note: Not needed in CentOS 7
#Note: Restart the vsftpd service after modifying the configuration
============================================================================================
After logging in, it will read the home directory files of the ftp user in the system
/var/ftp
-----------------------------------------------------
[root@localhost ~]# cd /var/ftp/
[root@localhost ftp]# ls
pub
[root@localhost ftp]# cd pub
[root@localhost pub]# ls					# Note: /var/ftp/pub/ is empty
[root@localhost pub]# touch aa bb			# Note: Create files aa bb
--------------------------------------------------------------------------------------------
ftp> ls										# Note: Current path /var/ftp
………………………… 
drwxr-xr-x    2 0        0              26 Nov 05 07:20 pub
ftp> cd pub
………………………… 
ftp> ls										# Note: Display files aa bb
………………………… 
-rw-r--r--    1 0        0               0 Nov 05 07:20 aa
-rw-r--r--    1 0        0               0 Nov 05 07:20 bb
226 Directory send OK.
--------------------------------------------------------------------------------------------
ftp> get aa									# Note: Download file
local: aa remote: aa
………………………… 
ftp> !ls									# Note: View current system command files
aa	 addstr.py
ftp> !pwd									# Note: View current system command path
/root
#Note: Anonymous users cannot upload
============================================================================================
[root@localhost ~]# ftp 192.168.136.136
Name (192.168.136.136:root): sanchuang		# Note: Local user sanchuang logs in
Password:
230 Login successful.						# Note: 230 indicates login successful
--------------------------------------------------------------------------------------------
ftp> put first.py 							# Note: Upload file
local: first.py remote: first.py			# Note: Anonymous users cannot upload
………………………… 
1097 bytes sent in 0.0157 secs (69.83 Kbytes/sec)
ftp> ls
………………………… 
-rw-r--r--    1 1000     1000         1097 Nov 05 07:34 first.py
226 Directory send OK.
============================================================================================
[root@localhost pub]# less /etc/services 		# Note: # less /etc/services to view default port number
ftp             21/tcp							# Note: FTP service default is port 21
ftp             21/udp          fsp fspd

9.2 Both anonymous users and local users can log in to the FTP service, and they can only operate files or folders under their home directory after logging in#

Both anonymous users and local users can log in to the FTP service, and they can only operate files or folders under their home directory after logging in

Three types of users:

  1. Anonymous user # Note: Anonymous user ftp; No password required; Home directory /var/ftp; ftp is also a local user in the system, the system automatically creates the ftp user, nologin, can log in via ftp
  2. Local user # Note: This is a user on the Linux system; After logging in via ftp, they are in the local user's home directory
  3. Virtual user # Note: Create a virtual user, mapped to a local user

#Note: The 6th field in /etc/passwd is the user's home directory
#Note: Check the user's home directory in the /etc/passwd file

9.3 Common FTP Commands#

Common FTP Commands

Common FTP commands:
Upload file: put # Note: Anonymous users cannot upload
Download file: get
View: ls
Change path: cd

9.4* Two Working Modes of FTP#

Two Working Modes of FTP (Interview)

When asked: Summarize (mention port numbers)

Both active and passive modes will open port 21 for connection

The difference is in the way data connections are established

Active Mode: The server actively opens port 20 to establish a data connection with the client and transfer data

Passive Mode: The client obtains a randomly opened port and then connects to the server for data transfer, the client establishes a connection to this random port for data transfer

1. Active Mode (Active mode is the default)

  1. The client requests the FTP server to connect to the command port (port 21)

  2. The 21 port returns information indicating whether login is successful or failed

  3. After successful login, the client requests data transfer (initiates a request to port 21), opening a random port

  4. The server actively opens its port 20 to send its data to the client's random port

The server actively opens port 20 to send data to the client

2. Passive Mode

  1. The client requests the FTP server to open the command connection port (port 21)

#Note: Port 21 is used for command connections

  1. The 21 port returns information indicating whether login is successful or failed

  2. The client requests data transfer (when the client requests data transfer, it sends a pasv command to the server, telling the server to receive commands in passive mode. At this point, the server opens a port, which can be specified in a range, and returns this port number to the client)

  3. The server opens the specified port number

  4. The client connects to the server port to transfer data (establish a connection with port 5555)

Assuming port 5555 is opened, the server will open port 5555, and the port will be in listening state, allowing others to connect, thus establishing a connection with this host and transferring data through port 5555

#Note: Passive mode requires configuration, active mode is default

Regardless of active or passive mode, port 21 must be up

In active mode, port 20 is up; in passive mode, port 20 may not be up

#Note: Data requests and command requests are not on the same port

image-20220812080812262


10. usermod userdel#

usermod#

usermod Command

Format: usermod [options]... username

Common Command Options

  • -l: Change the login name of the user account
  • -L: Lock the user account
  • -U: Unlock the user account
  • The following options have the same meaning as in the useradd command

​ -u, -d, -e, -g, -G, -s

userdel#

userdel Command

  • Format: userdel [-r] username
  • Adding the -r option indicates that the user's home directory will also be deleted # Note: Recommended to use
Example
--------------------------------------------------------------------------------------------
[root@localhost ~]# useradd stu01  
[root@localhost ~]# ls -ld /home/stu01/
drwx------ 2 stu01 stu01 4096 09-09 12:38 /home/stu01/  
[root@localhost ~]# userdel -r stu01				# Note: Delete user account stu01
[root@localhost ~]# ls -ld /home/stu01/  
ls: /home/stu01/: No such file or directory

11. useradd#

useradd Command

  • Format: useradd [options]... username

Common Command Options

  • -u: Specify UID number
  • -d: Specify home directory, default is /home/username
  • -e: Specify account expiration date
  • -g: Specify the user's primary group name (or GID) # Note: Only one primary group is allowed
  • -G: Specify the user's supplementary group name (or GID) # Note: Multiple supplementary groups can be used; regardless of primary or supplementary groups, users can obtain all permissions
  • -M: Do not create and initialize a home directory for the user
  • -s: Specify the user's login shell
  • -c: User comment description information
  • -r: Create a system user, no new home directory will be created

12. Users#

12.1#

User Accounts:

  • Superuser root # Note: Has the highest permissions
  • Program user # Note: Users needed during program execution
  • Ordinary user # Note: Users created manually

UID (User Identity, User Identification Number)

  • The UID of the superuser root is 0
  • The UID of program users is 1-999
  • The UID of ordinary users is greater than or equal to 1000
Example: mysql uid
--------------------------------------------------------------------------------------------
[root@localhost ~]# id mysql
uid=1000(mysql) gid=1000(mysql) group=1000(mysql)
[root@localhost ~]# id sanchuang2
uid=1001(sanchuang2) gid=1001(sanchuang2) group=1001(sanchuang2)

Example
--------------------------------------------------------------------------------------------
#Note: By default, if no uid is specified, it will increment by 1 from the previous user
[root@localhost ~]# useradd -u 1100 chenpeng1			# Note: Specify user ID
[root@localhost ~]# id chenpeng1
uid=1100(chenpeng1) gid=1100(chenpeng1) group=1100(chenpeng1)
[root@localhost ~]# useradd -u 1101 -g 1100 chenpeng2	# Note: Specify user ID, primary group
[root@localhost ~]# id chenpeng2						# Note: Inside the chenpeng1 group
uid=1101(chenpeng2) gid=1100(chenpeng1) group=1100(chenpeng1)

Example
--------------------------------------------------------------------------------------------
[root@localhost ~]# usermod -u 1200 chenpeng2			# Note: Modify user ID
[root@localhost ~]# id chenpeng2
uid=1200(chenpeng2) gid=1100(chenpeng1) group=1100(chenpeng1)

Example
--------------------------------------------------------------------------------------------
[root@localhost ~]# useradd -d /var/log/sanchuang6 sanchuang6	# Note: Specify user home directory
[root@localhost ~]# cd /var/log/sanchuang6/
[root@localhost sanchuang6]# ls
[root@localhost sanchuang6]# less /etc/passwd
sanchuang6:x:1201:1201::/var/log/sanchuang6:/bin/bash			# Note: Column 6 is the user's home directory

Example: Specify supplementary group
--------------------------------------------------------------------------------------------
[root@localhost sanchuang6]# useradd -g chenpeng1 -G sanchuang,sanchuang2 sanchuang7
[root@localhost sanchuang6]# id sanchuang7
uid=1202(sanchuang7) gid=1100(chenpeng1) group=1100(chenpeng1),1000(sanchuang),1001(sanchuang2)
#Note: Primary group chenpeng1  Supplementary groups sanchuang  sanchuang2
#Note: -g specifies primary group  -G specifies supplementary groups
============================================================================================
·-c: User comment description information
You can check the description information in the 5th column of /etc/passwd

12.2 userdel Delete User#

userdel Command

Format: userdel [-r] username

Adding the -r option indicates that the user's home directory will also be deleted

Example 1
--------------------------------------------------------------------------------------------
[root@localhost ~]# useradd stu01  
[root@localhost ~]# ls -ld /home/stu01/
drwx------ 2 stu01 stu01 4096 09-09 12:38 /home/stu01/  
[root@localhost ~]# userdel -r stu01						# Note: Delete user account stu01
[root@localhost ~]# ls -ld /home/stu01/  
ls: /home/stu01/: No such file or directory

Example 2
--------------------------------------------------------------------------------------------
[root@localhost sanchuang6]# userdel sanchuang7
[root@localhost sanchuang6]# less /etc/passwd				# Note: Deleted
[root@localhost sanchuang6]# cd /home/sanchuang7			# Note: Not deleted
[root@localhost sanchuang7]# ls /var/spool/mail/sanchuang7	# Note: Not deleted
/var/spool/mail/sanchuang7

13. usermod User Modification#

usermod Command

Format: usermod [options]... username

Common Command Options

  • -l: Change the login name of the user account
  • -L: Lock the user account
  • -U: Unlock the user account
  • The following options have the same meaning as in the useradd command
    -u, -d, -e, -g, -G, -s
Example: -L: Lock the user account
--------------------------------------------------------------------------------------------
#Note: After locking, cannot log in with password
#Note: Essentially adds a ! in front of the shadow password, causing password verification to fail during login
[root@localhost sanchuang7]# id sanchuang6
uid=1201(sanchuang6) gid=1201(sanchuang6) group=1201(sanchuang6)
[root@localhost sanchuang7]# usermod -L sanchuang6		# Note: Lock the user account
[root@localhost sanchuang7]# less /etc/shadow			# Note: A ! has been added in front of the password ciphertext
chenpeng2:!$6$P3yFUy.H$UOfUIbl8V3h1ng4J/OdVV1aWc3Cx3s5bldkysl33aDyrigsgK0VQ3nzrC4mojDNotpE9w61NbVQmZFqDDRfpl.:18571:0:99999:7:::
[root@localhost sanchuang7]# diff /etc/shadow /etc/shadow-
25c25
< chenpeng2:!$6$P3yFUy.H$UOfUIbl8V3h1ng4J/OdVV1aWc3Cx3s5bldkysl33aDyrigsgK0VQ3nzrC4mojDNotpE9w61NbVQmZFqDDRfpl.:18571:0:99999:7:::
---
> chenpeng2:$6$P3yFUy.H$UOfUIbl8V3h1ng4J/OdVV1aWc3Cx3s5bldkysl33aDyrigsgK0VQ3nzrC4mojDNotpE9w61NbVQmZFqDDRfpl.:18571:0:99999:7:::
#Note: SHA512 encryption technology  Ciphertext Plaintext
--------------------------------------------------------------------------------------------
[root@localhost ~]# ssh chenpeng2@192.168.0.188
chenpeng2@192.168.0.188's password: 					# Note: Cannot log in with password after locking
Permission denied, please try again.
………………………… 
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

14. /etc/shadow#

Used to store password strings, password expiration, and other information

  • File Location: /etc/shadow # Note: The file that stores user passwords, only root can view

  • Each line corresponds to a user's password record

  • Field 1: Username

  • Field 2: Encrypted password string information # Note: Field 2 stores the password field, the password is encrypted, ciphertext, using SHA512 algorithm

  • Field 3: Last password change time

  • Field 4: Minimum password validity days, default is 0

  • Field 5: Maximum password validity days, default is 99999

  • Field 6: How many days in advance to warn the user that the password will expire, default is 7

  • Field 7: How many days after the password expires to disable this user

  • Field 8: Account expiration date, default is empty

  • Field 9: Reserved field (unused)


15. passwd#

passwd Command

  • Format: passwd [options]... username

Common Command Options

  • -d: Clear the user's password, allowing login without a password
  • -l: Lock the user account
  • -S: View the status of the user account (whether it is locked)
  • -u: Unlock the user account
  • --stdin: Receive the stdout of another command as stdin to set the password

Root users can change all users' passwords without complexity requirements

Ordinary users can only change their own passwords, with complexity requirements

Example
--------------------------------------------------------------------------------------------
[root@localhost sanchuang7]# passwd -d sanchuang6		# Note: Clear user password
Clearing password for user sanchuang6.
passwd: Operation successful
[root@localhost sanchuang7]# useradd sanchuang5			# Note: Register without giving a password
[root@localhost mail]# less /etc/shadow
sanchuang6::18571:0:99999:7:::							# Note: Clearing user password leaves the password field empty
sanchuang5:!!:18571:0:99999:7:::						# Note: No password given, the password field defaults to two exclamation marks

#usermod and passwd locking accounts both modify the shadow encrypted field information of the account, causing them to fail to match during login, achieving a locked state
#usermod -L   adds a ! in front of the user's shadow password field				# Note: Locking the user adds a ! in front of the shadow password field
#passwd -l 	adds two ! in front of the user's shadow password field				# Note: Locking the user adds two ! in front of the shadow password field
#Note: To check if a user has set a password, check the /etc/shadow information

Example: usermod -L and passwd -l	Lock User
--------------------------------------------------------------------------------------------
[root@localhost mail]# useradd chen001
[root@localhost mail]# useradd chen002
[root@localhost mail]# useradd chen003
[root@localhost mail]# echo 123456|passwd chen001 --stdin
[root@localhost mail]# echo 123456|passwd chen002 --stdin
[root@localhost mail]# echo 123456|passwd chen003 --stdin
[root@localhost mail]# usermod -L chen002				# Note: Perform usermod -L operation on chen002
[root@localhost mail]# passwd -d chen003				# Note: Perform passwd -d operation on chen003
Clearing password for chen003.
passwd: Operation successful
[root@localhost mail]# less /etc/shadow
chen001:$6$y……k1q.yk8U1gOGp/:18571:0:99999:7:::
chen002:!$6$u……YF0.:18571:0:99999:7:::
chen003::18571:0:99999:7:::
------------------------------------------------------------------------
[root@localhost ~]# ssh chen003@192.168.136.136			# Note: Cannot log in
chen003@192.168.136.136's password: 
…………
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
[root@localhost ~]# ssh chen002@192.168.136.136			# Note: Cannot log in
chen002@192.168.136.136's password: 
…………
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
[root@localhost ~]# ssh chen001@192.168.136.136			# Note: No operations performed, remote login successful
chen001@192.168.136.136's password: 
[chen001@localhost ~]$ 

16. /etc/group#

/etc/group

​ Field 1: Group name

​ Field 2: Password field

​ Field 3: Group ID

​ Field 4: Stores which users are in the current group as supplementary groups

Example
--------------------------------------------------------------------------------------------
[root@localhost ~]# less /etc/group
tech:x:200:b1,b2,a1,a2
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.