Linux learning notes

1, Common commands

Teaching video of station B:
https://www.bilibili.com/video/BV1mW411i7Qf?p=106

tab Automatic completion if you want to switch paths, such as cd Desktop Can enter cd Des tab Key automatic completion
 Direction keys up and down can automatically the previous command
clear Clear screen
whoami  View current login user

1.1 document processing command

cd /tmp/Chinese  Switch directory   
cd ..  Return to the previous path
pwd  Displays the current path

ls  Displays all files in the current path. Blue represents folders and white represents files
ls -a Show all files, including hidden files   .xxx All files are hidden files
ls -lh First three correspondences ugo,File modification times, file owner, file group,-h File size,
ls *.txt Display all under the current path txt file
ls 1*  Displays all files starting with 1 in the current path

mkdir cc    establish cc folder
mkdir -p /tmp/Chinese/liudehua  Can be created at the same time Chinese Create under folder liudehua folder,-p Recursive creation

cp Copy, the original file is not deleted, mv Move is to delete the original file,mv Another function is that it can be renamed
cp -rp /etc/grub2.cfg /tmp  hold cfg Copy files to tmp
cp -r aa/bb .  hold aa Under folder bb Copy folder to current directory(.)lower

mv test.txt cc hold test Move the file to under the current path cc Folder, relative path
mv Chinese/aa.txt /home/hebe/Desktop/cc   This is the absolute path to move
mv /tmp/grub2.cfg /tmp/grub3.cfg Put the current file grub2 Rename to grub3

rm -f /tmp/grub3.cfg   Delete file
rm -rf /tmp/cc    delete cc folder      -f Force deletion -r Circular recursive deletion


touch test.txt  Create file in current directory

//cat -n test.txt check the file -n and add the line number in front to make it clearer
//more test.txt view the file, turn the page with blank space, enter the next line, and q exit
((recommended) less test.txt  Check the file, turn the page and enter the next line. For example, you want to search serve  Just input/serve input n Just find the next one q sign out

head -10 /etc/services  Check the first ten lines of this file and change the number
tail -10 /etc/services  Look at the last ten lines of this file-f Files can be displayed dynamically

link -s /etc/issue /tmp/issue.soft  Create a soft link, the latter points to the former, and the soft link is equivalent to windows Shortcut to, all permissions are rwxrwxrwx
link /etc/issue /tmp/issue.hard  (It's OK to know and rarely use) to create a hard link. The latter points to the former, which is equivalent to copy plus synchronous update (synchronous update is because i (same node)

1.2 authority management command

ls -lh yum.log
 Output, corresponding to the first three ugo  
chmod u=rw yum.log  

In practice, r=4,w=2,x=1    rwxrw-r-- For 764 three, three for all|Group|Other person permissions
chmod 764 yum.log  

If you want to change folder permissions, join-R
chmod -R 777 /tmp/cc   change cc The permissions of all files under the folder are 777

Only two people can change the file permissions, root+File owner
chown root /home/Chinese/abcd   hold abcd Folder file owner changed to root(Change file owner)
chgrp root /home/Chinese/abcd   hold abcd The group to which the folder file belongs is changed to root(Change file (Group)

umask -S View default permissions mkdir Folder, and then ls -lh Folder, that's the result, but touch There will be fewer files x,because x Represents executable, so x All become-,Don't let him do it to ensure safety

1.3 file search command

find /etc -name init  stay etc Directory, search for file names=init of
find /etc -name *init*  stay etc Directory, the search file name contains init of
 Note: put/etc change into/,It's the root directory. Check the whole system and replace it with.,Just look it up in the current directory, init*,namely init The first file will be found,-iname It's case insensitive. You can find it INIT

find / -size +204800  Find more than 100 in the root directory MB Documents
find /etc -size +163840 -a -size -204800 stay etc Find more than 80 in the directory MB Less than 100 MB Documents
 be careful:-a Two conditions are met at the same time  -o Is to satisfy any one
+n Is greater than,-n Is less than, n Is equal to, Linux 1 data block in the system=0.5KB,100MB=102400KB=204800

find /home -user cccc  stay home Find the owner under the directory is cccc Documents

find /home -group cccc  stay home The group found under the directory is cccc Documents

find /etc -cmin -5  stay etc Find the files and directories whose attributes have been modified within 5 minutes under the directory
find /etc -mmin -30  stay etc Find the files and directories that have been modified within 30 minutes under the directory

locate inittab Search file name=inittab,Add parameters-i Case insensitive
 It looks for documents in the document database, so the search speed is very fast, but the newly created documents can't be found. There are other problems/tmp The file was created under and could not be found because tmp It is not included in the document database
updatedb Upgrade file database 

which and whereis  Can get the absolute path of the file

grep mysql /root/install.log  stay install.log Find in the contents of the file mysql
-i ignore case
-n Output line number
-v Reverse lookup
--color=auto  The color displayed by the search keyword
grep -n --color=auto "root" /etc/passwd  stay/etc/passwd Find in the contents of the file root,Displays the line number. root Add red

1.4 help information command

man ls  see ls Help information for the command  
man services View profile services Help information for
man Absolute path not allowed

whatis ls View command(ls)Short message for
apropos services View profile(services)Short message for

ls --help see ls Help information for the command
help umask
help Is to get shell Built in command

1.5 user management commands

useradd yangmi Add new user yangmi
passwd yangmi Enter to yangmi Add password page

who Current user information tty Local terminal vm Virtual machines, pts It's a remote terminal, that is xshell/Securecrt Connection tool
w Current user details, first line up Indicates how long the server is running, users Represents several users, load average Indicates load balancing

1.6 compression and decompression command

.gz The format cannot compress the folder and keep the original file, so you need to tar pack
gzip cccc Compressed file
gunzip cccc.gz decompression  cccc.gz

.tar.gz format
tar -cvf ccc.tar ccc hold ccc Package folders into ccc.tar   
gzip ccc.tar Compress the folder and compress the files packaged above ccc.tar.gz
 Two steps in one: tar -zcf ccc.tar.gz ccc  Pack and compress
tar -zxf ccc.tar.gz decompression 

.zip Format compression ratio is not high
zip aaa.zip aaa Compressed file
zip -r aaa.zip aaa Compressed folder
unzip You can extract files and folders

.bzip2 format
bzip2 -k ccc    Compressed file,-k Source file retention
tar -cjf ccc.tar.bz2 ccc  Pack and compress
bunzip2 -k ccc.bz2 Decompress,-k Compressed packet retention
tar -xjf ccc.tar.bz2 decompression 

1.7 network command

before who Commands to see which users are currently online, for example liudehua on-line
write liudehua   Enter this first, and then enter the information on the second line to liudehua Users send messages, ctrl+D Save end
wall hello  Press enter directly to send a message to all users hello Information, including myself, will also be received

ping -c 4 www.baidu.com   And windows Different, this ping If you don't specify 4, it will always ping down
ifconfig    Second line inet Intranet address is the most important
ifconfig ens33 192.168.8.250 Temporary changes to intranet settings ip,Restart will fail

mail root   This is for root Send e-mail because you are root,In fact, it's also an email to yourself, Subject input test,Second line input hello nihao,then ctrl+D   Console re input mail  You can see the email. Enter 1 to view the first email. When you see the details, enter h,Re input d 1,Delete the first email and enter it again h,Just show No applicable messages,Then enter q sign out

last View the information of the personnel who logged in the server system in the past and now
lastlog -u root  see root Last login information of user

traceroute www.baidu.com  Track the route and display the access path between the data packet and Baidu

netstat  Display network related information (the following are the three most common uses)
netstat -tlun View the port that this machine listens to
netstat -an  View all network connections of this machine
netstat -rn  Local routing table view

setup Configure the network, which is a permanent configuration

1.8 shutdown and restart command

shutdown -h now  Shut down
shutdown -r now  restart

Other shutdown commands: halt/poweroff/init 0
 Other restart commands: reboot/init 6

init  There are 0-6  Run level
runlevel  You can view the current running level. It should be N 3  N Indicates the previous running level, and 3 indicates the current running level

logout Exit login 

1.9 vim editor

vim aaa.txt  Enter any text

Insert command: Esc Key input“ a" Insert after the character of the cursor
 Set line number command: Esc Key input“:set nu" Set line number input“:set nonu" suppress line number
 Delete command: Esc Key input“ x" Delete character input“:9,12d" Delete 9-12 that 's ok

Copy and cut commands: Esc Key in "4" yy" Copy the current line and enter "4" in the following 4 lines dd" Cut 4 lower case lines below the current line p Paste below the line where the cursor is located, in uppercase P Paste above the line of the cursor

Replace character command: Esc Key input“ R"  Appear below replace
 Cancel the previous operation command: Esc Key input“ u"

Find keyword command: Esc Key input“/str" Search in documents str Keyword input“ n" Next occurrence  
Replace keyword command: Esc Key input“:1,10s/ftp/yangmi/g" In 1-10 OK, as long as there is ftp Delete all the places and replace them with yangmi
":%s/ftp/yangmi/g"  Full text replacement

Save modify exit command:
Esc Key input“:w /tmp/ccc.txt" Save as this path ccc.txt
Esc Key input“:wq" Save changes and exit
Esc Key input“:q!" Exit without saving changes

Import the file contents and command execution results vim Medium:
Esc Key input“:r /etc/issue" Put the issue Import the contents of the file into the current vim Cursor
Esc Key input“:r !date" Import the execution result of this command into the current vim Cursor


Continuous line comments:
Esc Key input“:set nu" set nu 
Esc Key input“:1,4s/^/#/g"  1-4 Row join#Note No
Esc Key input“:1,4s/^#//g "uncomment lines 1-4

2, Software package management

Default installation path of RPM package
/etc/Profile installation directory
/usr/binExecutable command installation directory
/usr/libWhere to save the function library used by the program
/usr/share/docStorage location of basic software user manual
/usr/share/manHelp file save location
Source package installation location = = = / usr/local / software name
As a result RPM Package, you can use service To manage

For example: RPM Package installed apache The starting method is

/etc/rc.d/init.d/httpd start   Absolute path startup, which is a general method

service httpd start   This is a simplified method, except centos,Other systems may not work. This service can be started because rpm The default installation path of the package. The system will automatically find the package from the default installation path and start

For example: httpd-2.4.6-80.el7.centos.x86_64.rpm(This is called Bao's full name)
httpd==Package name
2.4.6==Software version
80==Number of software releases
el7.centos==compatible Linux platform
x86_64==Suitable hardware platform( noarch Everything is OK, i686 All computers are OK)
rpm==rpm Package extension

2.1 rpm command management

Installation:
rpm -ivh Package full name    -i install -v Show details -h Show progress
 If appear error Look at the second line, is needed by ahead, rpm Install the front, if it appears again error,again rpm needed In front, this is the existence of dependency, which is very troublesome

Upgrade:
rpm -Uvh Package full name    

Uninstall:
rpm -e Package name    

Query whether the package has been installed:
rpm -q Package name

Query all installed packages in the system:
rpm -qa  

Query the details of installed packages:
rpm -qi Package name

Query where the files in the installed package are installed:
rpm -ql Package name

Query which system files belong to rpm Package:
rpm -qf System file name
 For example: first rpm -ql words  Copy any path and rpm -qf The path can be reversed to see which one it belongs to rpm package

Query the dependencies of installed packages:
rpm -qR Package name
 Query the dependencies of packages that are not installed if you want to install them:
rpm -qRp Package full name  
such as rpm -qRp httpd-2.4.6-80.el7.centos.x86_64.rpm

RPM Package verification:
rpm -V Installed package name
 Note: if nothing is displayed, the description file has not been modified
1.The first few out . The representative didn't modify it
S=The file size has been modified, M=File type or permission( rwx)Modified, 5=md5 Being modified means that the content of the document is modified, D=,L=The file path has been modified, U=The owner of the file is changed, G=The group to which the file belongs has been changed, T=The modification time of the file has been changed
2.file type
c=configuration file(config file),d=General documents, g=((rare) indicates that the file should not be deleted rpm contain, l=Authorization document(license file),r=Description file(read me)

The system file was deleted by mistake and can be deleted RPM File extraction in package:
rpm2cpio Package full name |cpio -idv .File absolute path
 For example:
1.rpm -qf /bin/ls  query ls Which package does the command belong to
2.mv /bin/ls /tmp   cause ls False deletion by command
3.rpm2cpio /mnt/cdrom/Packages/coreutils-8.4-19.el6.i686.rpm|cpio -idv ./bin/ls
4.cp /root/bin/ls /bin/ls

2.2 yum online management (common)

yum yes rpm Automation, no need for cumbersome dependencies

Query the list of all available packages:
yum list

Search all keyword related packages on the server:
yum search Package name

Installation:
yum -y install Package name 
1.install gcc yum -y install gcc
2.Query whether the package has been installed: rpm -q gcc

Upgrade:
yum -y update Package name    
Note: if you do not add a package name, you are upgrading all software packages, including linux Kernel because of upgrade linux The kernel needs to be manually configured to start, so execute yum -y update After that, the server cannot be powered on

Uninstall:
yum -y remove Package name  
be careful: yum Uninstall, for example a rely on b,b rely on c,When uninstalling, abc Will be uninstalled together, but b and c Not just by a Dependent on other software packages or linux System dependent, so use yum When the command is uninstalled, the server will be down

List all available software groups: yum grouplist
 Install the specified software group: yum groupinstall "Software group name"    "Software group name"Must be in English
 Uninstall the specified software group: yum groupremove "Software group name"
Note: instead of installing software packages one by one, you can directly install one software group at a time in the virtual machine, yum grouplist,It's in English

2.3 source package installation

Here to install httpd take as an example

1.install gcc yum -y install gcc
2.Download the source package Baidu network disk to the laptop desktop httpd-2.2.9.tar.gz
3.use securefx,Drag to linux Under directory, enter ls You can view the compressed file if the compressed package is placed in root Directory, first cd /root
4.Decompression: tar -zxvf httpd-2.2.9.tar.gz
[[optional] du -sh httpd-2.2.9  See how big it is after decompression
5.Enter the decompression directory:cd httpd-2.2.9    ls Look at the files
6.Enter command“./configure --prefix=/usr/local/apache2"
7.Enter command“ make"    This is the compilation process, which translates the file into machine code. If an error is reported, enter make clean,Clean it up
8.Enter command“ make install"    Compile and install to/usr/local/apache2 Write data
9.Enter command“/usr/local/apache2/bin/apachectl start"    start-up apache
10.Browser input 192.168.239.129  Just( service httpd start/stop)
explain:
1.Source code save location:/usr/local/src   Software installation location:/usr/lcoal
2.vim INSTALL You can see how to install after step 5
3.Uninstall: rm -rf /usr/local/apache2

2.4 script installation package

The installation process is artificially written into an automatic installation script
 Here to install Webmin For example, this is a web-based linux System management interface, graphical way on Web page

1.Download the source package Baidu network disk to the laptop desktop webmin-1.981.tar.gz
2.use securefx,Drag to linux Under directory, enter ls You can view the compressed file if the compressed package is placed in root Directory, first cd /root
3.Decompression: tar -zxvf webmin-1.981.tar.gz
[[optional] du -sh webmin-1.981.tar.gz  See how big it is after decompression
4.Enter the decompression directory:cd webmin-1.981    ls Look at the files
5.Enter command“./setup.sh"
6.Until you get back login name   input admin Password 123 re-enter y
7.After the installation, look up three lines and there is this http://192.168.239.129:10000 / browser open it
8.input admin 123  left Webmin Click on==change language==web ui language(Personal choice)==simplified Chinese==make change==Refresh page

3, User and user group management

3.1 user profile

In Linux, user information is mainly viewed and modified through user configuration files. The later user and user group management commands are essentially to modify the information in these configuration files

1. User information file (common)
vim /etc/passwd   Looking at the configuration file, you can see that there are seven fields
 First field: user name
 The second field: password flag, x Represents that the user has a password
 3rd field: UID Is the user id,0 On behalf of superuser, 1-499 Represents system users, more than 500 represents ordinary users, uid Change to 0 and the user becomes root
 4th field: GID,User initial group ID,The initial group has permissions from the beginning. The corresponding additional group is the permissions added later
 Field 5: user description
 Field 6: home directory(User initial login directory)  Ordinary users:/home/hebe   Super user:/root
 Field 7: after login shell

2. User information shadow file
vim /etc/shadow   Looking at the configuration file, you can see that there are 9 fields
 First field: user name
 The second field: encryption password, SHA512 Hash encryption algorithm, if yes“!!"Or“*"It means you can't log in without a password
 The third field: the date when the password was last modified, in 1970.1.1 As the start date, it shows how many days have passed
 The fourth field: the interval between two password changes. If it is 10, it means that the password is changed on the first day. After 10 days, the password can be changed again
========================================================================
Timestamp conversion date: date -d "1970-01-01 16066 days"
Date conversion timestamp: echo $(($(date --date="2021/10/28" +%s)/86400+1)) 
Example: if the fifth field is 90, the sixth field is 7, and the seventh field is 5
 It means that when the password expires after 90 days, the password should be changed. A warning message should be sent 7 days in advance to warn the user that the password should be changed. The password can still be used after 90 days. On the 95th day, the official password will become invalid
========================================================================
The fifth field: password validity period. 99999 stands for permanent validity
 The sixth field: the warning message before the password expires. The password will be changed soon
 The seventh field: the grace days after the password expires. 0 means the password expires immediately,-1 It means it will never fail
 The eighth field: account expiration time, with timestamp-Number, this is account invalidation, not password invalidation
 The ninth field: reserved field, which is temporarily useless

3. File group information
vim /etc/group   Looking at the configuration file, you can see that there are four fields
 The first field: group name. The default group name is the same as the user name
 The second field: group password flag, x The representative group has a password. It is not recommended to set it
 3rd field: GID,group ID
 Field 4: additional users in the group

4.Shadow file group information
vim /etc/gshadow   Looking at the configuration file, you can see that there are four fields
 First field: group name
 Field 2: group password
 Field 3: group administrator user name
 Field 4: additional users in the group

3.2 user management related documents

1.Home directory (user's initial login location)
Ordinary users:/home/The user name, owner and group belong to this user, and the permission is 700
 Super user:/root,Both the owner and the group are root User, permission is 550

2.User's mailbox
/var/spool/mail/user name

3.User template directory
/etc/skel

3.3 user management commands

1.Add user command: useradd
useradd tfz
passwd tfz  
Parameters:-u appoint uid||-d Specify home directory||-c Specify user description||-g Specify initial group||-G Specify additional groups||-s Specify user login shell

2.Modify user password: passwd
passwd tfz  to tfz User set password, only root Before you can set a password for others
passwd Enter is the password set by the current user
-S (can only root)View password status user name||Password setting time||Password modification interval||Password validity||Warning time||Password does not expire
-l (can only root)Lock user 
-u Unlock user

3.Modify user information: usermod  Modify user password status: chage
usermod tfz  yes tfz Modify user information by user
 Parameters:-u modify uid||-c Modify user description||-G Modify additional groups||-L Temporarily lock users||-U Unlock user

chage tfz  yes tfz User password status for user modification
 Parameters:-l Lists the detailed status of the user password
chage -d 0 tfz  This command sets the password change date to zero, so that the user will change the password as soon as he logs in

4.Delete user: userdel View user id: id User name user switching command: su
userdel -r tfz  Usually add-r,Delete the user's home directory while deleting the user
su - root   Usually plus-Use it this way,-Means to switch with the user's environment variables, that is, to switch to root user
su - root -c "useradd user3" No switching root User, just borrowing root Identity, execute the command to add users, or do you need to root password

3.4 user group management commands

1.Add user group
groupadd Group name

2.Modify the user group (generally, it is not modified, but directly deleted and a new group is created)
groupmod -n New group name old group name change old group name to new group name
 Parameters:-g GID Modify group id      -n New group name modify group name

3.Delete user group
groupdel Group name
 Note: if there is an initial user in the group, delete the user first and then delete the user group. If it is an additional user, it will not affect the deletion of the group

4.Add or remove users from a group
gpasswd -a user1 root  Put users user1 join root Group, after joining user1 Belong to additional users
gpasswd -d lamp1 root  Put users lamp1 from root Delete from group

4, Authority management

4.1 ACL permissions

be similar to windows Right click the attribute to directly assign read-write permissions to users

ACL Permission opening method, Linux It is on by default
1.View which partitions the system has: df -h 
2.Command to query detailed file system information of a specified partition: dumpe2fs -h /dev/sda1  
3.Temporarily open partition ACL jurisdiction(Restart failure): mount -o remount,acl /   Remount the root partition and mount the join acl jurisdiction
4.Permanently open partition ACL jurisdiction: vi /etc/fstab  join acl  then mount -o remount /

1.see ACL jurisdiction
getfacl /project/   see project Catalog ACL jurisdiction

2.For users or groups, set ACL jurisdiction
setfacl -m u:tfz:rx /project/  To users tfz Set pair project Catalog rx read-write permission
setfacl -m g:group1:rwx /project/  Give group group1 Set pair project Catalog rwx Read / write execution permission

3.Maximum valid permissions mask
 If I give users ACL Permission is required and mask The user's real permission can only be obtained by "matching" the user's permission
setfacl -m m:rx /project/  such mask=r-x,No one else except the initial user w Write permission

4.delete ACL jurisdiction
setfacl -x u:tfz /project/  To users tfz Delete permissions
setfacl -x g:group2 /project/  Give group group2 Delete permissions
setfacl -b /project/   Put everything in the directory ACL If you delete them, you will return to the original default permission

5.recursion ACL jurisdiction
 Recursion is set by the parent directory ACL Permission, all sub files and subdirectories will have the same permissions ACL jurisdiction
setfacl -m u:tfz:rx -R /project/  For all files in the directory ACL jurisdiction

6.default ACL jurisdiction
 If default is set for parent directory ACL Permission, then all newly created child files in the parent directory will inherit the permissions of the parent directory ACL jurisdiction
setfacl -m d:u:tfz:rx /project/  There are all the new files in the directory ACL jurisdiction

setfacl Parameters:-m set up ACL jurisdiction||-x Delete the specified ACL jurisdiction||-b Delete all ACL jurisdiction||-d Set default ACL jurisdiction||-k Delete default ACL jurisdiction||-R Recursive setting ACL jurisdiction

4.2 special permissions of documents

SetUID,abbreviation SUID,File only
(1)Only executable binary programs can be set SUID jurisdiction
(2)The command executor should have control over the program x((execution) authority
(3)(Important) main function: when executing the program, the command executor obtains the identity of the owner of the program file, such as changing from ordinary user to root
(4)SetUID Permission is only valid during the execution of the program

set up SetUID How to: chmod 4755 File name or  chmod u+s file name
 cancel SetUID How to: chmod 755 File name or  chmod u-s file name

SUID Is a very unsafe command, except that it is owned by the system by default SUID In addition to commands, common passwd,We try not to give the program SUID
SetGID,abbreviation SGID,For file
(1)Only executable binary programs can be set SGID jurisdiction
(2)The command executor should have control over the program x((execution) authority
(3)(Important) main function: when the command executor executes the program, the group identity is upgraded to the group of the program file, that is, the group identity is changed
(4)SetGID Permission is only valid during the execution of the program

For directory
(1)Ordinary users must own this directory r and x Permission to enter this directory
(2)The valid group of ordinary users in this directory will become the group of this directory
(3)If ordinary users own this directory w Permission, the default group of the newly created file is the group of this directory

set up SetGID How to: chmod 2755 File name or  chmod g+s file name
 cancel SetGID How to: chmod 755 File name or  chmod g-s file name

SGID Is a very unsafe command, except that it is owned by the system by default SGID In addition to commands, common locate,We try not to give the program SGID
Sticky BIT,abbreviation SBIT Adhesive bit, valid only for directory
(1)The directory is owned by ordinary users w and x jurisdiction
(2)If there is no adhesive bit, it is owned by ordinary users w Permission, so you can delete all files in this directory, including files created by other users. Once the adhesive bit is given, except root You can delete all files, even if ordinary users have them w Permission, you can only delete files created by yourself, but you cannot delete files created by other users

set up SBIT Method of sticking position: chmod 1755 Directory name or  chmod o+t Directory name
 cancel SBIT Method of sticking position: chmod 777 Directory name or  chmod o-t Directory name

Common, such as tmp catalogue

4.3 file system attribute chatr permission

chattr [+-=] [option] File or directory name this command is mainly used to prevent misoperation of files
+: Add permissions -: Delete permissions =: Give a permission

option i: If the file is set i Property, then it is not allowed to delete or rename the file, or add or modify data. It is equivalent to locking the file root Users are also unable to manipulate files;If the directory is set i Property, you can only modify the data of files in the directory, but you are not allowed to create or delete files.
option a:If the file is set a Property, data can only be added to the file, but cannot be deleted or modified, that is, existing data cannot be modified, but new data can be added;If the directory is set a Property, you can only create and modify files in the directory, but you are not allowed to delete them

View file system properties
lsattr Option file name     To use the corresponding command, traditional ls no way
 option a: Show all files and directories
 option d: If the target is a directory, only the attributes of the directory itself are listed, not the attributes of the sub files

4.4 system command sudo permission

(1)to grant authorization sc The user can restart the server
visudo sc ALL=/sbin/shutdown -r now

(2)switch sc user
su - sc

(3)sc Users view available sudo command
sudo -l

(4)sc User executed by root The command given can be used here whereis View the absolute path of the command
sudo /sbin/shutdown -r now

In the actual working environment, root Do not grant to ordinary users vim Command, this is a very dangerous operation

5, File system management

5.1 common commands of file system

File system view command df
df -a  Displays all file system information, including hidden special file systems
df -h  Normal display capacity unit, which is commonly used

Statistics directory size du
du -h /etc/  see etc Subdirectory size
du -sh /etc/  see etc Total directory size, which is commonly used

File system repair command fsck
fsck -y Partition device file name
 Just know this, every time linux When the system starts up, the system will repair automatically without manually entering commands

Display disk status command dumpe2fs
dumpe2fs Partition device file name

Mount command mount
mount [-t file system][-L Volume label][-o Special options] Device file name mount point
 Note: mount point is equivalent to windows of c disc d Disc, in linux In, use an empty directory;Mount is to connect the device file name with the mount point

5.2 mounting CD and U SB flash disk

Mount CD
(1)Establish mount point
mkdir /mnt/cdrom/
(2)True to disc
(3)Mount CD
mount -t iso9660 /dev/cdrom /mnt/cdrom/
(4)View disc contents
cd /mnt/cdrom/
ls

Uninstall disc
(5)Uninstall command
cd    Exit the mount point first
umount /mnt/cdrom
mount  U disc
(1)Establish mount point
mkdir /mnt/usb/
(2)Real put U disc
(3)mount  U disc
mount -t vfat /dev/sdb1 /mnt/usb/
(4)View disc contents
cd /mnt/usb/
ls

uninstall U disc
(5)Uninstall command
cd    Exit the mount point first
umount /dev/sdb1
mount  NTFS File system, such as mobile hard disk
 utilize NTFS-3G plug-in unit
 Wait until you have practical needs

5.3 fdisk partition process and manual mount

Linux A new hard disk is added to the system
(1)fdisk -l    Check to see if the hard disk is recognized,No partition under hard disk
(2)fdisk /dev/sdb    Input in sequence n,p,1,2048,+2G
(3)input p  See if the partition exists
(4)Input in sequence n,e,2,enter,enter
(5)input p  See if the second partition exists
(6)Input in sequence n,l,enter,+2G
(7)input p  See if the partition exists
(8)input w Save exit
(9)input partprobe      Sometimes the last step w Save and exit, and you will be prompted to restart if it is occupied linux,direct partprobe,Forced re reading of partition table information can be regarded as a convention. Even if there is no prompt, enter the command once
(10)The format partition system is extened The extended partition cannot be formatted
mkfs -t ext4 /dev/sdb1
mkfs -t ext4 /dev/sdb5
(11)Establish mount point and mount
mkdir /disk1
mkdir /disk5
mount /dev/sdb1 /disk1/
mount /dev/sdb5 /disk5/
(12)df -h   Check whether it is mounted

5.4 automatic mount and fstab file repair

dumpe2fs -h /dev/sdb1  View the corresponding UUID

(1)vim /etc/fstab   The essence of automatic mount is to modify the text
(2)Enter the following in the format
/dev/sdb1               /disk1                  ext4    defaults        1 2
(3)Exit again vim
(4)input mount -a  If no error is reported, the document is correct

If it's really wrong and linux Restart, the system failed
 input root password
mount -o remount,rw /
vim /etc/fstab  Then modify the text

First field:Partition device file name or UUID(Universal unique identification code of hard disk)
Second field:Mount point
 Third field:file system name
 Fourth field:Mount parameters
 Fifth field:Specifies whether the partition is dump Backup, o Represents no backup, 1 represents daily backup, and 2 represents irregular backup
 Sixth field:Specifies whether the partition is fsck Detection, 0 means no detection, and other numbers represent the priority of detection. Of course, 1 has a higher priority than 2

6, Shell programming

6.1 execution mode of shell script

bash shell is mainly used

1.mkdir sh    establish sh Directory. Put all the scripts here in the future
2.cd sh/

3.vim hello.sh   newly build hello.sh file

4.               Enter script file code
#!/bin/bash
#tys
echo "hello world"

5.:wq         Save exit

6.chmod 755 hello.sh   then./hello.sh    This is more commonly used
 perhaps bash hello.sh

6.2 basic functions of Bash

Historical command and command completion:

history [option][Save file with history command]    
direct history Commands can also be used
-c Clear history command  -w Writes the history commands in the cache to the save file(~/.bash_history)

You can save 1000 environment variables in the default configuration file/etc/profile Modify in
 Up and down arrows, tab Key automatic completion
alias alias='Original order'
# Set command alias

alias 
# Query command alias

vim /root/.bashrc
# Make alias permanent

unalias alias 
# Delete alias

ctrl+C Force termination of current command
ctrl+L Clear screen, equivalent to clear
ctrl+U Command before cutting
ctrl+Y paste ctrl+U Cut content
ctrl+D Exit the current terminal, logout
Output redirection
 command > abc 2>&1
# Overwrite the output result of the correct command or the error message of the wrong command into the abc file

command >> abc 2>&1
# Add the output result of the correct command or the error message of the wrong command to the abc file 

command >> abc 2>>bcd
# The output result of the correct command is appended to the abc file, and the error information of the wrong command is appended to the bcd file 

input redirection 
wc < file name
 such as wc < anaconda-ks.cfg  View installation log cfg Number of rows+Number of words+Number of characters
Multi command executorformateffect
;Command 1; Command 2Multiple commands are executed in sequence, and there is no logical connection between commands
&&Command 1 & & Command 2When command 1 is executed correctly, command 2 will be executed; When command 1 is not executed correctly, command 2 will not be executed
||Command 1 | Command 2When command 1 is executed correctly, command 2 will not be executed; When command 1 is executed incorrectly, command 2 will be executed
date ; dd if=/dev/zero of=/root/testfile bs=1k count=100000 ; date

dd The command [options] is generally used to copy hard disk partitions
if=Input file specifies the source file or source device
of=Output file specifies the target file or target device
bs=Number of bytes 	  Specify one input/How many bytes are output, that is, these bytes are regarded as a data block
count=Number of specified inputs/How many data blocks are output

command && echo yes || echo no  
#See if the command is executed correctly

Pipe symbol|  Logical or|| 

Command 1 | Command 2
#The correct output of command 1 is the operation object of Command 2
netstat -an | grep ESTABLISHED   Check how many remote connections the current server has
wildcardeffect
?Match one character
*Match all
[]Match any character in parentheses, such as [abc] for a or b or c
[-]For example, [a-z] means to match all lowercase letters
[^]Logical non, such as [^ 0-9] represents matching a character that is not a number

6.3 Bash variables

In Bash, the default type of variables is string type. If you want to perform numerical operation, you must modify the specified variable type to numeric type

==============================================================================
User defined variables, i.e. local variables

name="shen chao"
#Custom variable

echo $name
#Variable call

set
#Variable view

unset name
#Variable deletion
==============================================================================
Setting environment variables

export Variable name=Variable value
#Declarative variable

env
#Query environment variables

unset Variable name
#Delete variable
==============================================================================
Position parameter variable
$n n Is a number, $0 On behalf of the order itself, $1-$9 Represents the first to ninth parameters. Parameters above ten need to be contained in braces, such as ${10}
$* Represents all parameters in the command line, and regards all parameters as a whole
$@ Represents all parameters in the command line, but treat each parameter differently
$# Represents the number of all parameters in the command line
==============================================================================
Predefined variables 
$? The return status of the last executed command. If it is 0, it proves that the last command was executed correctly
$$ The process number of the current process
$! The process number of the last process running in the background
==============================================================================
Read keyboard input
read [option][Variable name]
-p "Output information":Waiting read When inputting, output prompt information
-t Seconds:Specify the waiting time
-n Number of characters:read The command accepts only the specified number of characters
-s: Hide input data

6.4 Bash operators

declare Declare variable type

declare [+/-] [option] Variable name
-:Set type properties for variables
+:Cancels the type attribute of a variable
-i:Declare variables as integers
-x:Declare variables as environment variables
-p:Displays the declared type of the specified variable
====================================================================================
Numerical operation
aa=11
bb=22
ff=$(($aa+$bb))      ff=aa+bb 

6.5 environment variable configuration file

source configuration file
#Make the modified configuration file effective

/etc/profile
/etc/profile.d/*.sh
~/.bash_profile
~/.bashrc
/etc/bashrc

~/.bash_logout  Environment variable profile in effect at logoff
~/bash_history  history Command file
/etc/issue      Welcome information of local terminal  
/etc/issue.net  Welcome information of remote terminal  

6.6 regular expressions

Regular expressions are used to match strings that meet the criteria in the file. Regular expressions include matching
 Wildcards are used to match qualified file names, and wildcards are exact matches

grep "aa*" test.txt
 Match contains at least one a Okay, a*Represents 0 or any number of matches, in linux It doesn't make any sense

grep "s..d" test.txt   
Match out said soid Like this
grep "s.*d" test.txt   
and*Same effect, s and d There can be any character in the middle
grep ".*" test.txt   
Match everything,

grep "^M" test.txt
 Match in uppercase M First line
grep "n$" test.txt
 Match in lowercase n Ending line
grep -n "^$" test.txt
 Match blank lines

\{n\}Indicates that the preceding character just appears n second   [0-9]\{4\}Match 4 digits
\{n,\}Indicates that the preceding characters appear no less than n second   [0-9]\{2,\}Match 2 or more digits
\{n,m\}Indicates that the preceding character appears at least n Times, up to m second   [a-z]\{6,8\}Match 6-8 Bit lowercase letters

6.7 character commands

cut [option] file name    grep Look, OK cut Look at the column
-f Which column is extracted by column number
-d Separator splits the column according to the specified separator

printf '%s %s %s\n' 1 2 3 4 5 6 
Output 123line wrap 456

awk The command can intercept spaces
 give an example: df -h | awk '{print $1 "\t" $5 "\t" $6}'

awk Can join BEGIN,END,  Execute first begin Content, printing test!!,Then output the second column
awk 'BEGIN{print "test!!"} {print $2 "\t" $5}' student.txt

because/etc/passwd Files, separated by colons, awk Only spaces or tab,So join FS Built in variable
awk '{FS=":"}{print $1 "\t" $3}' /etc/passwd

sed It is a lightweight stream editor, which is mainly used to select, replace, delete and add data
-a Add  -c Row replacement -i Insert, or modify the file directly -d delete -p Print -s String substitution -n default sed All contents will be output,-n Output specified content
sed -n '2p' student.txt  Output second line
sed '2,4d' student.txt   Delete the second to fourth lines and only change the output without changing the contents of the file itself

Sort command sort
sort [option] The file name is generally direct sort File name,
-f ignore case
-r Reverse sort

Statistical command wc
wc [option] file name 
-l Count rows only
-w Only count the number of words
-m Count only characters

6.8 condition judgment

Judge by document type

Test optionseffect
-b documentsDetermine whether the file exists and whether it is a block device file
-c DocumentsJudge whether the file exists and whether it is a character device file
-d documentsJudge whether the file exists and whether it is a directory file
-e documentsDetermine whether the file exists
-f fileJudge whether the file exists and whether it is an ordinary file
-L fileJudge whether the file exists and whether it is a symbolic link file
-p fileJudge whether the file exists and whether it is a pipeline file
-s fileJudge whether the file exists and is not empty
-S fileDetermine whether the file exists and whether it is a socket file

Judge according to file permissions

Test optionseffect
-r fileJudge whether the file exists and whether the file has read permission
-w fileJudge whether the file exists and whether the file has write permission
-x fileJudge whether the file exists and whether the file has execution permission
-u fileJudge whether the file exists and whether the file has SUID permission
-g fileJudge whether the file exists and whether the file has SGID permission
-k fileJudge whether the file exists and whether the file has SBit permission

Compare between two files

Test optionseffect
File 1 -nt file 2Judge whether the modification time of file 1 is newer than that of file 2
File 1 -ot file 2Judge whether the modification time of file 1 is older than that of file 2
File 1 -ef file 2Judge whether file 1 and file 2 are the same file through the Incode number

Compare between two integers

Test optionseffect
Integer 1 -eq integer 2Determine whether integer 1 is equal to integer 2
Integer 1 -ne integer 2Judge whether integer 1 is not equal to integer 2
Integer 1 -gt integer 2Judge whether integer 1 is greater than integer 2
Integer 1 -lt integer 2Judge whether integer 1 is less than integer 2
Integer 1 -ge integer 2Judge whether integer 1 is greater than or equal to integer 2
Integer 1 -le integer 2Judge whether integer 1 is less than or equal to integer 2

String judgment

Test optionseffect
-z stringJudge whether the string is empty
-n stringJudge whether the string is non empty
String 1 = = string 2Determine whether string 1 is equal to string 2
String 1= String 2Determine whether string 1 is not equal to string 2
Two judgment formats
test -e /root/install.log && echo yes || echo no  
[ -e /root/install.log ] && echo yes || echo no  

6.9 process control

if sentence
if [Conditional judgment formula 1]
  then 
  	When condition 1 is true, execute the procedure
elif [Conditional judgment formula 2]
  then
    When condition 2 is true, execute the procedure
else
  When the conditions are not satisfied, execute the procedure
fi
======================================================================================
case sentence
case $cho in
	"yes")
		echo "Your choice yes"
		;;
	"no")
		echo "Your choice no"
		;;
	*)
		echo "Your choice error"
		;;
esac
======================================================================================
for sentence
s=0
for((i=1;i<=100;i=i+1))
	do
		s=$(($s+$i))
	done
echo "The sum of 1+2+..+100 is:$s"

for i in 1,2,3,4   such for Circulation is also OK
======================================================================================
while sentence
#From 1 to 100, if i is less than or equal to 100, the loop is executed
i=1
s=0
while [ $i -le 100]
	do
		s=$(( $s+$i ))
		i=$(( $i+1 ))
	done
echo "The sum is:$s"
======================================================================================
until sentence    while Is to execute the cycle according to the cycle conditions, until Yes, stop the cycle when the cycle condition is reached
#From 1 to 100, if i is greater than 100, stop the cycle
i=1
s=0
until [ $i -gt 100]
	do
		s=$(( $s+$i ))
		i=$(( $i+1 ))
	done
echo "The sum is:$s"

7, Service management

chkconfig --list view the service self startup status, and you can see the services installed by all RPM packages

Check the service installation location of the source package, usually under / usr/local

catalogueeffect
/etc/init.d/Start script location, based on independent service
/etc/sysconfig/Initialize environment profile location
/etc/Profile location
/etc/xinetd.confxinetd configuration file
/etc/xinetd.d/Startup script based on xinetd service
/var/lib/The data generated by the service is placed here
/var/log/journal

7.1 management of RPM package installation service - independent service management

Startup of independent services (both are OK),service yes Redhat series linux (unique)

/etc/init.d/Independent service name start|stop|status|restart   
give an example  /etc/init.d/httpd restart
service Independent service name start|stop|status|restart  
give an example service httpd restart
=====================================================================================
Self start of independent service to httpd For example, the second one can look at things added in history, but the first one is more convenient, but it needs to be viewed status
chkconfig --level 2345 httpd on/off   
perhaps
 modify/etc/rc.d/rc.local File join /etc/rc.d/init.d/httpd start

7.2 management of RPM package installation service - xinetd based service management

be based on xinetd Service management,There are few now. Just find out
 and xinetd Service startup is the same as self startup, that is, when self startup is closed, startup is closed

1.install xinetd And telnet
yum -y install xinetd
yum -y install telnet
yum -y install telnet-server

2.xinetd Service startup
vim /etc/xinetd.d/telnet
 hold disable Change to no

3.restart xinetd service
service xinetd restart

4.xinetd Self start of service
chkconfig telnet on

7.3 management of source package services

Using the absolute path, call the startup script to start

Different source packages have different startup scripts

for example Apache Startup of source package
 /usr/local/apache2/bin/apachectl start/stop
 
for example Apache Self start of source package
vim /etc/rc.d/rc.local
 join   /usr/local/apache2/bin/apachectl start

8, System management

8.1 process view

ps aux  #View all processes in the system

USER:Which user generated the process;
PID:Process ID number;
%CPU:Occupied by this process CPU The higher the percentage of resources, the more resources the process consumes;
%MEM:The percentage of physical memory occupied by the process. The higher the occupation, the more resources the process consumes;
VSZ:The size of virtual memory occupied by this process, unit: KB;
RSS:The size of the actual physical memory occupied by the process, in KB;
TTY:The terminal in which the process is running. among tty1-tty7 Represents the local console terminal, tty1-tty6 It is a local character interface terminal, tty7 Is a graphics terminal. pts/0-255 Represents a virtual terminal.? It is directly generated by the kernel
STAT:Process status. Common states are:R:Operation S:Sleep T:Stop status s:Including child processes+:In the background
START:The start time of the process
TIME:Occupied by this process CPU The operation time of is not the system time
COMMAND:The name of the command that generated this process
==================================================================================
top   #View system health status
 Enter letters directly P/M/N/q
P:with CPU Sort by usage. This option is selected by default
M:Sort by memory usage
N:with PID sort
q:sign out top
==================================================================================
yum install psmisc   Install first pstree
pstree [option]
-p Displays the of the process pid
-u Displays the user to which the process belongs

The first line of the top command is the task queue information

contentexplain
12:26:46Current system time
up 1 day,13:32The system has been running for 13 hours and 32 minutes a day
2 usersCurrently, 2 users are logged in
load average: 0.00,0.01,0.05The average load of the system in the previous 1 minute, 5 minutes and 15 minutes. It is generally believed that when it is less than 1, the load is small, and when it is greater than 1, it exceeds the load

The second line of the top command is the process information

contentexplain
Tasks: 95 totalTotal number of processes in the system
1 runningNumber of running processes
94 sleepingSleep process
0 stoppedStopping process
0 zombieZombie process. If it is not 0, you need to check the zombie process manually

The information on the third line of the top command is CPU information

contentexplain
%Cpu(s): 0.0usPercentage of CPU occupied by user mode
0.3syCPU percentage occupied by system mode
0.0niPercentage of CPU used by user processes with changed priority
100.0idCPU percentage of idle CPU
0.0waPercentage of CPU consumed by processes waiting for input / output
0.0hiPercentage of CPU occupied by hard interrupt request service
0.0siPercentage of CPU used by soft interrupt request service
0.0stst virtual time percentage is the percentage of time that the virtual CPU waits for the actual CPU when there is a virtual machine

The information on the fourth line of the top command is the physical memory information

contentexplain
Mem: 997956 totalTotal physical memory in KB
472100 freeAmount of free physical memory
190672 usedAmount of physical memory used
335772 buff/cacheAmount of memory to buffer

The fifth line of the top command is the exchange partition information

contentexplain
Swap: 1023996 totalTotal size of swap partition (virtual memory)
472100 freeSize of free swap partition
0 usedThe size of the interactive partition that has been used
610212 avail MemThe size of the interactive partition as a cache

8.2 termination process

pstree -p  #View the id number of the corresponding service
kill -1 process id number    #Restart process
kill -9 process id number    #Force kill process
==================================================================================
killall -9 httpd     
in other words killall+Process name   kill+A string of numbers
==================================================================================
pkill The command is generally used to kick out the user according to the terminal number
w  #Query the logged in users of this machine
pkill -t -9 pts/1   #Force to kill the process logged in from pts/1 virtual terminal

8.3 work management

1.Put the process in the background
 Add after the command&Is to execute commands in the background
 For example: tar -zcf etc.tar.gz /etc &     
Another is that during the execution of the command, ctrl+z,The command is also put into the background, but the work in the background is suspended
2.View all work running in the background
jobs -l  
remarks:+Number represents the last job put into the background,-The number represents the penultimate work put into the background
3.Resume the work suspended in the background to the foreground for execution
fg %Job number 
4.Resume the work suspended in the background to the background
bg %Job number 

8.4 viewing system resources

vmstat 1 3   #Monitor system resources. This command integrates the top command and refreshes every 1 second, a total of 3 times

dmesg  #Kernel detection information at boot time
 such as dmesg | grep CPU

free  #View memory usage
 such as free -m   according to MB View memory

cat /proc/cpuinfo     #View CPU Information

uptime     #Displays the startup time and average load of the system, which is the first line of the top command

uname -a    #View system and kernel related information

file /bin/ls    #View the number of digits in the system

cat /etc/redhat-release    #View the release version of the system

lsof [option]    #Lists the file information opened or used by the process
-c String: lists only files opened by processes that begin with a string
-u User name: only the files opened by a user's process are listed
-p pid: List a pid Files opened by the process

8.5 system scheduled tasks

1.
crond Service management and access control  #By default, crond starts directly and automatically
service crond restart  #Start command
chkconfig crond on   #Set to self start command

2.
crontab -l   #Query crontab task
crontab -r   #Delete all crontab tasks

3.
crontab -e   #Enter the editing interface to write scheduled tasks
45 22 * * * /root/sh/auto.sh   Execute the script at 22:45 every day
projectmeaningRange
First "*"What minute of an hour0-59
Second "*"What hour of the day0-23
Third "*"What day of the month1-31
Fourth "*"What month of the year1-12
The fifth "*"Day of the week0-7, 0 and 7 represent Sundays
timemeaning
45 22 * * commandExecute the order at 22:45
0 17 * * 1 commandExecute the order at 17:00 every Monday
0 5 1,15 * * commandExecute the order at 05:00 on the 1st and 15th of each month
40 4 * * 1-5 commandsExecute the order from 40:00 on Monday to 04:00 on Friday
*/10.4 * * commandExecute the command every 10 minutes at 4 a.m. every day
0 0 1,15 * 1 commandOrders will be executed on the 1st and 15th of each month and at 00:00 on Monday

9, Log management

9.1 log files for log management

log fileexplain
/var/log/cronLogs related to system scheduled tasks are recorded.
/var/log/cupsLog of printing information
/var/log/dmesgIt records the information of kernel self-test when the system is powered on. You can also use the dmesg command to directly view the kernel self-test information.
/var/log/btmpLog login errors. This file is a binary file, which cannot be viewed directly by vi, but by using the lastb command
/var/log/lastlogLog the last login time of all users in the system. This file is also a binary file, which cannot be viewed directly by vi, but by using the lastlog command
/var/log/mailogRecord mail information
/var/log/messageA log recording important information of the system. This log file will record most important information about the Linux system. If there is a problem with the system, the first thing to check should be this log file.
/var/log/secureRecord authentication and authorization information, as long as procedures involving accounts and passwords are recorded. For example, system login, ssh login, su switching users, sudo authorization, and even adding users and changing user passwords will be recorded in this log file.
/var/log/wtmpPermanently record the login and logout information of all users, and record the startup, restart and shutdown events of the system. Similarly, this file is also a binary file, which cannot be viewed directly by vi, but needs to be viewed by using the last command
/var/run/utmpRecord the information of the currently logged in user. This file will change with the user's login and logout, and only record the information of the currently logged in user. Similarly, this file can't be queried directly by vi, but by using w, who, users and other commands.

9.2 rsyslogd service

1.Log file format
 The basic log format contains the following four columns:
>Time of occurrence
>The hostname of the server on which the event occurred
>The name of the service or program that generated the event
>Specific information of the event

2./etc/rsyslog.conf configuration file
cat /etc/rsyslog.conf  Randomly copied a line of examples
authpriv.*                  /var/log/secure
 Service name+Connection symbol+Log level       Logging location
Service nameexplain
authSecurity and authentication related messages (authpriv is not recommended)
authprivSecurity and authentication related messages (private)
cronLogs generated by system scheduled tasks cront and at
daemonLogs related to each daemon
ftpLogs generated by ftp daemon
kernLog generated by kernel (not generated by user process)
local0-local7Reserved services for local use
lprPrint the generated log
mailMail sending and receiving information
newsNews server related logs
syslogThere are log information generated by syslogd service (although the service name has been changed to rsyslogd, many configurations still follow syslggd, and the service name is not modified here).
userLog information of user level category
uucpThe log information of uucp subsystem. Uucp is the protocol for data transmission in early linux system, and later it is also commonly used in newsgroup service.
Connection symbolexplain
"*" represents all log levelsFor example, "authpriv. *" represents the log generated by authpriv authentication information service, and all log levels are recorded
“.” It means that as long as the log is higher than the later level (including this level), it will be recorded.For example, "cron.info" represents the log generated by the cron service. As long as the log level is greater than or equal to the info level, it will be recorded
". =" means that only the logs of the required level are recorded, and the logs of other levels are not recorded.For example: "*. = emerg" represents the logs generated by the person and the log service. As long as the level is emerg, it will be recorded. This usage is rare. Just understand it
“.!” Represents not equal to, that is, except for the logs of this level, the logs of other levels are recorded.
Grade name (from low to high)explain
debugGeneral commissioning information description
infoBasic notification information
noticeGeneral information, but it has certain importance
warningWarning information, but it will not affect the operation of the service or system
errError information, which generally reaches err level and can affect the operation of service or system
critCritical condition information, more serious than err level
alertWarning status information is more serious than crit. Immediate action must be taken
emergPain level information, the system is no longer available
Logging locationexplain
Absolute path of log fileSuch as "/ var/log/secure"“
System equipment fileSuch as "/ dev/lpo" this is the printer
Forward to remote hostSuch as "@ 192.168.0.210:514"
user nameSuch as "root"
Ignore or discard logs"~"

9.3 log cutting and rotation

1.Naming rules for log files
 Add in configuration file“ dateext"The file name after the parameter is automatically added with the date

2.logrotate configuration file
cat /etc/logrotate.conf

3.rpm Packages do not need to be rotated manually. Only source packages are needed, such as apache The following code is added to the log in turn
vim /etc/logrotate.conf
/usr/local/apache2/logs/access_log {
	daily
	create
	rotate 30
}

4.
logrotate [option] file name
-v The log rotation process is displayed   -f Mandatory rotation whether or not it is time for rotation
Parameters (logrotate configuration file)explain
dailyThe log rotation cycle is daily
weeklyThe log rotation cycle is weekly
monthlyThe log rotation cycle is monthly
rotate numberNumber of log files retained. 0 means there is no backup
compressWhether the old logs are compressed during log rotation
create mode owner groupCreate a new log, and specify the permissions, owner and group of the new log. For example, create 0600 root utmp
mail addressWhen the log rotates, the output content is sent to the specified email address by email. Such as mail tfz@163.com
missingokIf the log does not exist, the warning information of the log is ignored
notifemptyIf the log is an empty file, log rotation is not performed
minsize sizeMinimum value of log rotation. That is, the log must reach the minimum value before rotation, otherwise it will not rotate even if the time reaches
Size sizeLog rotation is performed only when the log is larger than the specified size, rather than by time, such as size 100k
dateextUse the date as the suffix of the log rotation file, such as secure-20220306

10, Start management

10.1 operation level

Run levelmeaning
0Shut down
1Single user mode, mainly used for system repair, similar to Windows security mode
2Incomplete command line mode without NFS service
3The complete command line mode is the standard character interface
4System retention
5Graphical mode (if the graphical interface is followed, enter init 5 command to enter the graphical interface)
6restart
init  There are 0-6  Run level
runlevel  You can view the current running level. It should be N 3  N Indicates the previous running level, and 3 indicates the current running level
======================================================================================
System default run level( Centos7 (this file is no longer available)
vim /etc/inittab
id:3:initdefault:
#Which operation level will the system enter directly after startup? Either 3 or 5

10.2 startup process

The startup process of linux system is very long and complex, which is useless. Just understand it and don't take notes

10.3 Grub configuration

cat /etc/default/grub

CentOS 7 is totally different from video, so the function of this configuration file is to modify it in the configuration file and select which linux system to start and which linux kernel to start. Moreover, the content is not important. It is not used for general work, so you don't have to read it

11, Backup and recovery

11.1 general

1.Linux Data to be backed up
/root/catalogue
/home/catalogue
/var/spool/mail/catalogue
/etc/catalogue
 Other directories

2.Data for installation services

Apache Data to be backed up
 configuration file+Homepage home directory+log file

MySQL Data to be backed up
 Source package installation mysql: /usr/local/mysql/data/
RPM Package installed mysql: /var/lib/mysql/

3.Backup strategy

Full backup: refers to the complete backup of all data to be backed up, such as the complete backup of the whole hard disk; Full backup of the entire partition directory

Incremental backup: full backup on the first day, backup the content added on the first day on the second day, backup the content added on the second day on the third day, and so on
 Disadvantages: recovery is also a day-to-day recovery, which is slow

Differential backup: it is a compromise concept to combine the advantages of full backup and incremental backup, but there are more than two kinds of actual work. Just know this

11.2 dump and restore commands

====================================================================================
backups
 1. yum -y install dump
 dump [option] File name after backup original file or directory
 -level: It's 0-9 Ten backup levels, 0 for full backup, 1 for the first incremental backup, and 2 for the second incremental backup
 -f File name: Specifies the file name after backup
 -u: After the backup is successful, record the backup time in the/etc/dumpdates file
 -v: Show more output information during backup
 -j: Compress backup files into.bz2 format
 -W:Display allowed dump The backup level and backup time of the partition
 
 2.Example: Backup boot Partition( Centos7 (changed)
 dump -0uj -f /root/boot.bak.bz2 /boot/    #Perform a full backup first, and compress and update the backup time
 cat /etc/dumpdates                        #View backup time file
 cp install.log /boot/                     #Copy log files to boot partition
 dump -1uj -f /root/boot.bak1.bz2 /boot/   #Incrementally backup the boot partition and compress it
 dump -W            					   #Query the backup time and backup level of the partition
 ====================================================================================
 recovery
 1.restore [Mode options] [option]
 Mode options:
 -C: Compare the changes of backup data and actual data
 -i: Enter the interactive mode and manually select the files to be recovered
 -t: View mode, which is used to view what data is in the backup file
 -r: Restore mode for data restore
 Options:
 -f: Specifies the file name of the backup file
 
 2.give an example:
 (1)Compare the changes of backup data and actual data
	mv /boot/vmlinuz-2.6.32-279.el6.i686 /boot/vmlinuz-2.6.32-279.el6.i686.bak
	#Change the name of the kernel image file in the / boot directory
	restore -C -f /root/boot.bak.bz2
	#restore found that the kernel image file is missing
	
(2)View mode
	restore -t -f /root/boot.bak.bz2
	
(3)Restore mode, restore boot.bak.bz2 Partition backup
	mkdir boot.test             #Create a new directory and select which directory to restore to
	cd boot.test/
	restore -r -f /root/boot.bak.bz2     #Restore full backup
	restore -r -f /root/boot.bak1.bz2    #Restore incremental backup

Teaching video of station B:
https://www.bilibili.com/video/BV1mW411i7Qf?p=106

Keywords: Linux CentOS

Added by infomamun on Sun, 06 Mar 2022 11:50:09 +0200