Common commands for Linux - 04

Basic format of command

1. Command prompt

[root@localhost ~] #
  • []: This is the separator of the prompt and has no special meaning.
  • root: displays the current login user
  • @: separator, no special meaning
  • Localhost: the short host name of the current system (the full host name is localhost.localdomain).
  • ~: represents the current directory of the user. In this example, the current directory of the user is the home directory.
  • #: command prompt. Super users are #, ordinary users are$

2. Basic format of command

[root@localhost ~] # Command [options] [parameters]
  • Command name: ls
  • English original meaning: list
  • Path: / bin/ls
  • Execution Authority: all users
  • Function Description: displays the contents of the directory
[root@localhost ~] # ls [options] [file name or directory name]
Options:
		-a: Show all files
		--color=when: Support color output, when The default value of is always(Total display color), or never(Never show color) and auto((automatic)
		-d: Displays directory information instead of files in the directory
		-h: Humanized display, display the file size according to our customary units
		-i: Displays the of the file i Node number
		-l: Long format display

For example:

[root@localhost ~] # ls -l
total 24
lrwxrwxrwx.   1 root root    7 Apr 26 23:50 bin -> usr/bin

We have instructed the "- l" option to display the details of the file. What are the meanings of the seven columns displayed by the "- 1" option?

  • Column 1: permissions. The meaning of specific authority will be explained in section 4.5
  • Second column: reference count. The reference count of a file represents the number of hard links of the file, while the reference count of a directory represents the number of first-class subdirectories of the directory.
  • This is the third column to which all users belong. The default owner is the user who created the file
  • Column 4: group. The default group is the valid group of the file creation user. Generally, it is the group of the creation user.
  • Column 5: size. The default unit is bytes
  • Column 6: document modification time. The file status modification time or file data modification time will change this time. Note that this time is not the creation time of the file.
  • Column 7: file name

Option: is used to adjust the function of the command
Parameter: it is the operation object of the command. If the parameter is omitted, it is because there are default parameters

Directory operation command

1, ls command
Contents of the previous section

2, cd command
cd is the command to switch the directory. The basic information of this command is as follows

  • Command name: cd
  • English: change directory.
  • Path: Shell built-in command
  • Execution Authority: all users
    Function Description: switch directory

1. Simplified usage of CD command

Special symbols effect
~ Home directory representing the user
- Represents the last directory
. Represents the current directory
... On behalf of the parent directory

2. Absolute path and relative path

**Absolute path: * * take the directory as the reference, start from the root directory and enter the directory level by level
**Relative path: * * use the current as a reference to find the directory

3, mkdir command

mkdir is the command to create a directory. Its basic information is as follows:

  • Command name: mkdir
  • make directories
  • Path: / bin/mkdir
  • Execution Authority: all users
  • Function Description: create an empty directory

Command format

[root@localhost ~] # mkdir [options] directory name
 Options:
		-p: Recursively establish the required directory

4, rmdir command

Since there is a command to create a directory, there must be a command to delete the directory rmdir. The basic information is as follows:

  • Command name: rmdir
  • remove empty directories
  • Path: / bin/rmdir
  • Execution Authority: all users
  • Function Description: delete empty directory

Command format

[root@localhost ~] # rmdir [options] directory name
 Options:
		-p: Recursively delete directory

The function of rmdir command is very limited, because it can only delete an empty directory, so once there is content in the directory, an error will be reported
This command is "stupid", so we don't use it very often. In the future, no matter what files or directories are deleted, rm will be used

File operation command

1, touch command
Create an empty file or modify the file time. The basic information of this command is as follows.

  • Command name: touch
  • change file timestamps
  • Path: / bin/touch
  • Execution Authority: all users
  • Function Description: modify the timestamp of the file

2, stat command

stat is a command to view file details, and you can see the three times of the file. Its basic information is as follows:

  • Command name: stat
  • display file or file system status
  • Path: / usr/bin/stat
  • Execution Authority: all users

Function Description: displays the details of the file or file system

[root@localhost ~]# stat anaconda-ks.cfg
  File: 'anaconda-ks.cfg'
  Size: 2956            Blocks: 8          IO Block: 4096   regular file
Device: 803h/2051d      Inode: 33574980    Links: 1
Access: (0600/-rw-------)  Uid: (    0/    root)   Gid: (    0/    root)
Context: system_u:object_r:admin_home_t:s0
Access: 2020-04-26 23:57:54.841715229 -0700
Modify: 2020-04-26 23:57:31.854224235 -0700		#Data modification time
Change: 2020-04-26 23:57:31.854224235 -0700	#Status modification time
 Birth: -

3, cat command

The cat command is used to view the contents of the file. The basic information of this command is as follows

  • Command name: cat
  • concatenate file and print on the standard output
  • Path: / bin/cat
  • Execution Authority: all users

Function Description: merge files and print out to standard output

Command format

[root@localhost ~] # cat [options] file name
 Options:
		-A: amount to -vET Option to list all hidden symbols
		-E: Lists carriage returns at the end of each line $
		-n: set number 
		-T: hold Tab Key use ^I Show
		-v: List special characters

4, more command

more is the command to display files in split screen. Its basic information is as follows:

  • Command name: more
  • File Universal Filter for CRT viewing.
  • Path: / bin/more
  • Execution Authority: all users
  • Function Description: split screen display of file content

The more command is relatively simple. Generally, there are no options. The command will open an interactive interface, which can recognize some interactive commands. Common interactive commands are as follows

  • Spacebar: page down
  • b: Page up
  • Enter key: scroll down one line
  • /String: the string specified by the search element
  • q: Quit

5, less command

The less command is similar to the more command, except that more is a split screen display command, while less is a branch display command. Its basic information is as follows

  • Command name: less
  • Opposition of more
  • Path: / usr/bin/less
  • Execution Authority: all users
  • Function Description: display file content in branches

6, tail command

Since there is a command to display the beginning of the file, there will be a command to display the end of the file. The basic information of the tail command is as follows

  • Command name: tail
  • output the last part of files
  • Path: / usr/bin/tail
  • Execution Authority: all users
  • Function Description: displays the contents at the end of the file

Command format

[root@localhost ~] # tail [options] file name
 Options:
		-n Number of lines: displays the specified number of lines from the end of the file
		-f: New content of listening file

7, ln command

Let's take a look at the basic information of ln command

  • Command name: ln
  • make links between files
  • Path: / bin/ln
  • Execution Authority: all users
  • Function Description: establish links between files

1. The basic format of LN command is as follows

[root@localhost ~] # ln [options] source file destination file
 Options:
		-s: Create a soft link file. If not“-s"Option, a hard link file is established
		-f: Mandatory. If the target file already exists, delete the target file and then establish the linked file

If you create a hard link:

[root@localhost ~] # touch cangls
[root@localhost ~] # ln /root/cangls /tmp/
#Establish a hard link file. The target file does not have a file name, which will be consistent with the original name
#That is, / root/cangls and / tmp/cangls are hard linked files

If you create a soft link:

[root@localhost ~] # touch bols
[root@localhost ~] # ln -s /root/bols /tmp/
#Create soft link file

2. Characteristics of hard link and soft link

Hard link features:

  • The source file and hard link file have the same Inode and Block
  • Modify any one file and the other will change
  • Delete any one file and the other can be used
  • The hard link table is unclear, so it is difficult to confirm the location of the hard link file. It is not recommended to use it
  • Hard links cannot link directories
  • Hard links cannot cross partitions

Soft link features:

  • Soft links and source files have different incodes and blocks
  • Modify either of the two files and change the other
  • Delete the soft link and the source file will not be affected; Delete source file, soft link cannot be used
  • The soft link has no actual data and only saves the Inode of the source file. No matter how large the source file is, the size of the soft link remains the same
  • The permission of soft link is the maximum permission lrwxrwxrwx, However, due to the lack of actual data, the final access needs to refer to the source file permissions
  • Soft links can link directories
  • Soft links can span partitions
  • Soft link features are obvious, so it is recommended to use soft link

Commands that can operate on both directories and files

1, rm command

rm is a powerful delete command, which can delete not only files but also directories. The basic information of this command is as follows.

  • Command name: rm
  • remove files or directories
  • Path: / bin/rm
  • Execution Authority: all users
  • Function Description: delete files and directories

Command format

[root@localhost ~] # rm [options] file or directory
 Options:
		-f: Force deletion( force)
		-i: Interactive deletion. The user will be asked before deletion
		-r: Recursive deletion, you can delete the directory( recursive) 

2, cp command

cp is applicable to copying commands. The basic information is as follows:

  • Command name: cp
  • copy files and directories
  • Path: / bin/cp
  • Execution Authority: all users
  • Function Description: copy files and directories

Command format

[root@localhost ~] # cp [options] source file destination file
 Options:
		-a: amount to -dpr A collection of options, which we will introduce one by one
		-d: If the source file is a soft link (not valid for the hard disk link), the copied target file is also a soft link
		-i: Ask, if the target file already exists, ask whether to overwrite it
		-p: After copying, the target file retains the attributes of the original file (including owner, group, permission and time)
		-r: Recursive replication, used to copy directories

3, mv command

mv is a command for cutting. Its basic information is as follows:

  • Command name: mv
  • move (rename) files
  • Path: / bin/mv
  • Execution Authority: all users
  • Function Description: move files or change names

Command format

[root@localhost ~] # mv [options] source file destination file
 Options:
		-f: Force overwrite. If the target file already exists, you can directly force overwrite without asking
		-i: Interactively move. If the target file already exists, ask the user whether to overwrite it (default option)
		-v: Show details

Basic authority management

1, Introduction to permissions

Meaning of permission

When explaining the ls command earlier, we have instructed that the first column of long format display is the file permission, for example:

[root@localhost ~] # ls -ls install.log
-rw-r--r--. 1 root root 2960 Apr 26 23:58 initial-setup-ks.cfg

If the permission bit in the first column does not calculate the last "." (the meaning of this point will be explained later). There are 10 bits in total. The meaning of these 10 permission bits is shown in the figure:

  • The first digit represents the file type. Unlike Windows, Linux uses the extension to represent the file type, but uses the first bit of the permission bit to represent the file type. Although there are not as many types of Linux files as in Windows, there are also many classifications. For details, you can use the "info ls" command
  • "-": ordinary file
  • "b": block device file. This is a special device file, which is used for all storage devices. For example, the partition file / dev/sda1 is such a file
  • "c": character device file. This is also a special device file, which is generally used for input devices, such as mouse, keyboard, etc
  • "d": directory file. Everything in Linux is a file, so a directory is also a kind of file
  • "l": soft link file
  • "p": Manager file. This is a very rare special device file
  • 's': Socket file. This is also a special device file. Some services support Socket access. Jiuhui generates such a pair of files
  • The second to fourth digits represent the permissions of the file owner
  • r: Stands for read, which is read permission
  • w: On behalf of write, it is write permission
    If there are letters, it means that you have the corresponding permission; If it is "-", it means that there is no corresponding permission
  • The 5th to 7th digits represent the permissions of the group to which the file belongs, and also have "rwx" permissions
  • The 8th to 10th persons represent the authority of others and also have "rwx" authority

2, Basic permission command

First, let's look at the command chmod to modify permissions. Its basic information is as follows

  • Command name: chmod
  • change file mode bits
  • Path: / bin/chmod
  • Execution Authority: all users
  • Function Description: modify the permission mode of the file

1. Command format

[root@localhost ~] # chmod [options] permission mode file name
 Options:
		-R: Set permissions recursively, that is, set permissions for all files in the subdirectory

2. Permission mode
The format of the permission mode of the chmod command is [ugoa] [+ - = [perms]] "", that is, [user identity] [granting method] [permission] "
Let's explain the format of

  • User identity
    -u: on behalf of the owner (user)
    -g: represents the group to which it belongs
    -o: on behalf of other s
    -Identity: all (a)
  • Giving method:
    -+: Join permission
    --: minus permissions
    -=: set permissions
  • jurisdiction
    -r: read permission
    -w: write permission
    -x: execute permission

3. Digital rights

The way of giving digital permission is the simplest, but it is not as easy to remember and care as the previous letter permission. Let's look at the meaning of these digital permissions

  • 4: On behalf of "r" permission
  • 2: On behalf of "w" permission
  • 1: On behalf of "x" permission

Common permissions
The way of giving digital permission is simpler, but users need to be more familiar with these numbers. In fact, there are not many commonly used permissions, only the following

  • 644: the basic permission of this file means that the owner has read and write permission, while the group and others have read-only permission
  • 755: This is the execution permission of the file and the basic permission of the directory. It represents that the owner has read, write and execution permission, while the group and others have read and execution permission
  • 777: This is the maximum permission. In the actual production server, we should try to avoid giving such permissions to files or directories, which will cause certain security risks

Role of basic permissions

1, Interpretation of authority meaning

First, read, write and execute permissions have different effects on files and directories

  • Effect of permissions on files
    -Read (r): have read (r) permission to the file, which means you can read the data in the file. If the permission is corresponding to the command. Once you have read (r) permission on the file, you can execute cat, more, less, head, tail and other file viewing commands on the file
    -Write (w): you have write (w) permission on the file, which means you can modify the data in the file. If the permission is corresponding to the command, once you have write (w) permission on the file, you can execute commands such as vim and echo to modify the file data. Note: if you have write permission to the file, you can't delete the file itself. You can only modify the data in the file. If you want to delete a file, you need to have write permission to the parent directory of the file.
    -Execute (x): execute (x) permission on the file, which means that the file has execution permission and can run. In Linux, as long as the file has execution (x) permission, the file is an execution file. However, whether the file can be executed correctly depends not only on the execution (x) permission, but also on whether the code in the file is the correct language code. For a folder, the highest permission is not to execute (x)
  • Effect of permissions on directories
    -Read (r): having read (r) permission on the directory means that you can view the contents under the directory, that is, you can view the sub files and sub directories under the directory. If the permission is corresponding to the command, once you have read (r) permission on the directory, you can execute ls command under the directory to view the contents under the directory
    -Write (w): you have write (w) permission to the directory, which means you can modify the data under the directory, that is, you can create, delete, copy and cut sub files or sub directories in the directory. If the permission is mapped to the command, once you have write (w) permission to the directory, you can execute touch, rm, cp and mv commands in the directory. For a directory, write (w) permission is the highest permission
    -Execute (x): the directory cannot be run. If you have execute (x) permission on the directory, you can enter the directory. If the permission is mapped to the command, once you have the execute (x) permission on the directory, you can execute the cd command on the directory and enter the directory

1. Available permissions of the directory

In fact, the available permissions of the directory are only the following

  • 0: no permission is given
  • 5: Basic directory browsing and access rights
  • 7: Full authority

Owner and group commands

1. chown command
chown is a command to modify the owner and group of files and directories. Its basic information is as follows:

  • Command name: chown
  • change file owner and group
  • Path: / bin/chown
  • Execution Authority: all users
  • Function Description: modify the owner and group of files and directories

1) Command format

[root@localhost ~] # chown [option] owner: the file or directory of the group to which it belongs
 Options:
		-R: Set permissions recursively, that is, set permissions for all files in the subdirectory

Ordinary users cannot modify the owner of the file, even if they are the owner of the file
Ordinary users can modify the permissions of files whose owner is their own

2. chgrp command
chgrp is a command to modify the group of files and directories. Its basic information is as follows

  • Command name: chgrp
  • change group ownership
  • Path: / bin/chgrp
  • Execution Authority: all users
  • Function Description: modify the group of files and directories

umask default permissions

1. View umask permission of the system

[root@localhost ~] # umask
0022
# Display umask permissions with octal values
[root@localhost ~] # umask -s
u=rwx,g=rx,o=rx
# Use letters to indicate the initial permissions of files and directories

2. Calculation method of umask permission

We need to first understand the default maximum permissions for new files and directories

  • For files, the default maximum permission for new files is 666, No permission to execute (x). This is because the execution permission is dangerous for files. It cannot be given by default when creating a new file, but must be given manually by the user
  • For directories, the default maximum permission for creating a new directory is 777. This is because for the directory, the execute (x) permission only represents entering the directory, so there is no danger even if it is directly given by default when creating a new file. According to the official standard algorithm, the default permission of umask needs to use binary for logical and logical non joint operation to get the correct default permission of new files and directories. This method is neither easy to calculate nor easy to understand
    Here we will explain the calculation method of umask permission according to the permission letters. Let's calculate the default permissions of new files and directories according to the default umask value of 022
  • The maximum default permission of the file can only be 666, and the value of umask is 022
    "- RW RW RW -" minus "---- w – W -" equals "- rw-r – R -"
  • The maximum default permission of the directory can be 777, and the value of umask is 022
    "drwxrwxrwx" minus "d --- w – W -" equals "drwx-r-xr-x"

Note: the calculation of umask default permission is never a direct subtraction of numbers

For example, umask is 033?

  • The maximum default permission of the file can only be 666, and the value of umask is 033
    "- RW RW RW -" minus "---- Wx Wx" equals "- rw-r – R -"

Help command

1. man command

man is the most common help command and the main help command for Linux. Its basic information is as follows.

  • Command name: man
  • format and display the on-line manual pages
  • Path: / usr/bin/man
  • Execution Authority: all users
  • Function Description: displays the online help manual

Command format

[root@localhost ~] # man [options] Command
 Options:
		-f: See what level of help the command has
		-k: View all help related to the command
G Move to last page
q sign out
/String Search string down front page
? character string Search up the string from the current page
n When searching for a string, you can use the n key to find the next string
N When searching for a string, use the N key to reverse the query string. In other words, if you use the "/ string" method to search, the N key means to search the string upward; If "string" search is used, the N key means to search down the string

Help level of man command

level effect
1 Help for system commands and executable files that ordinary users can execute
2 The kernel can call the help of functions and tools
3 C language function help
4 Help with equipment and special documents
5 Help for profiles
6 Game help (there are games in personal Linux)
7 Miscellaneous help
8 Help with system commands that super users can execute
9 Kernel help
man -f Command or whatis command
# See what level of help the command has

man -k Command or apropos command
# View all help related to the command

info command

The help information of info command is a complete set of data, and the help information of each individual command is only a small chapter in this complete set of data

Shortcut key effect
up arrow Move up one line
Down arrow Move down one line
PgUp Turn up one page
PgDn Turn down one page
Tab Switch between nodes with "*" symbol
enter Enter the sub page marked with "*" to view the detailed help information
u Enter the previous level information (enter is to enter the next level information)
n Go to the next section
p Go to the previous section
? View help information
q Exit info

help command
Help can only get help from Shell built-in commands
The basic information of the help command is as follows:

  • Command name: help
  • English original meaning: help
  • Path: Shell built-in command
  • Execution Authority: all users

**Function Description: * * displays the help of Shell built-in commands. You can use the type command to distinguish built-in commands from external commands

shell is the command interpreter of Linux

– help option
Most commands can use the "– help" option to view help, which is also a way to get help. For example:

[root@localhost ~] # ls --help

This method is very simple. The output help information is basically a brief version of the man command

Search command

1. whereis command
Whereis is a command to search the system (like a tongue twister). That is, the whereis command can't search ordinary files, but can only search system commands. The basic information of the whereis command is as follows:

  • Command name: whereis
  • locate the binary, source, and manual page files for a command
  • Path: / usr/bin/whereis
  • Execution Authority: all users
  • Function Description: find binary commands, source files and help documents

2. which command
Which is also a command for searching system commands. The difference between which and whereis is:

  • The whereis command can find the location of the help document while finding the binary command
  • While the which command finds the binary command, if the command has an alias, it can also find the alias command

3. locate command
The locate command is a command that can search for ordinary files by file name

  • Advantages: according to the database search, the search speed is fast and the trumpet resources are small. Database location / var / lib / mlocate / mlocate db
  • Disadvantages: you can only search files by file name, but cannot perform more complex searches, such as searching files by permission, size, modification time, etc

The basic information of the locate command is as follows:

  • Command name: locate
  • find files by name
  • Path: / usr/bin/locate
  • Execution Authority: all users
  • Function Description: search for files by file name

configuration file

[root@localhost ~]# vi /etc/updatedb.conf
PRUNE_BIND_MOUNTS = "yes"
# Turn on search restrictions, that is, make this configuration file effective
PRUNEFS = "9p afs anon_inodefs auto autofs bdev binfmt_misc cgroup cifs coda configfs cpuset debugfs devpts ecryptfs exofs fuse fuse.sshfs fusectl gfs gfs2 gpfs hugetlbfs inotifyfs iso9660 jffs2 lustre mqueue ncpfs nfs nfs4 nfsd pipefs proc ramfs rootfs rpc_pipefs securityfs selinuxfs sfs sockfs sysfs tmpfs ubifs udf usbfs"
# These file system types are not allowed to be searched when the search is performed in locate
PRUNENAMES = ".git .hg .svn"
# When you perform a search in locate, disable the search for files with these extensions
PRUNEPATHS = "/afs /media /mnt /net /sfs /tmp /udev /var/cache/ccache /var/lib/yum/yumdb /var/spool/cups /var/spool/squid /var/tmp"
# When you perform a search in locate, you are prohibited from searching these system directories

4. find command

The basic information of the find command is as follows

  • Command name: find
  • search for files in a directory
  • Path: / bin/find
  • Execution Authority: user
  • Function Description: search for files in the directory

Search by file name

[root@localhost ~]# find search path [options] search content
 Options:
		-name: Search by file name
		-iname: Search by file name, case insensitive
		-inum: according to inode Number search

Search by file size

[root@localhost ~]# find search path [options] search content
 Options:
		-size [+ | -]Size: searches for files according to the specified size

"+" here means to search for files larger than the specified size, and "-" means to search for files smaller than the specified size

The unit of the find command

[root@localhost ~]# man find
 -size n[cwbkMG]
              File uses n units of space.  The following suffixes can be used:

              `b'    for 512-byte blocks (this is the default if no suffix is used)
					# This is the default unit. If the unit is b or not written, search by 512 Byte
              `c'    for bytes
					# The search unit is c, which is searched by bytes
              `w'    for two-byte words
					# The search unit is w, and the search is based on double byte (Chinese)
              `k'    for Kilobytes (units of 1024 bytes)
					# Search in KB units, which must be lowercase k
              `M'    for Megabytes (units of 1048576 bytes)
					# Search by MB, must be in uppercase M
              `G'    for Gigabytes (units of 1073741824 bytes)
              		# Search in GB units, which must be a capital G

Search by modification time
Files in Linux include access time (atime), data modification time (mtime) and status modification time (ctime). We can also search files according to time

[root@localhost ~]# find search path [options] search content
 Options:
		-atime [+ | -]Time: search by file access time
		-mtime [+ | -]Time: search according to the modification time of file data
		-ctime [+ | -]Time: modify the time search according to the file status

We have explained the difference between these three times in the stat command. Here we use mtime data modification time as an example to focus on the meaning of "[+ -]" time

  • -5: Represents documents modified within 5 days
  • 5: Represents the documents modified on the previous 5-6 days
  • +5: Represents the document modified 6 days ago
    Let's draw a timeline to explain, as shown in Figure 4-6

Search by permissions

Command format

[root@localhost ~]# find search path [options] search content
 Options:
		-perm Permission mode: find the file whose permission is just equal to "permission mode"
		-perm -Permission mode: find files whose permissions all include "permission mode"
		-perm +Permission mode: find the file whose permission contains any permission of "permission mode"

Search by owner and group

[root@localhost ~]# find search path [options] search content
 Options:
		-uid user ID: By user ID Find owner is specified ID Documents
		-gid group ID: By user group ID Find the group to which you belong ID Documents
		-user User name: find the file whose owner is the specified user according to the user name
		-group Group name: find the files belonging to the specified user group according to the group name
		

When searching by owner and group, the "- nouser" option is commonly used to find garbage files
There is only one exception, that is, external documents. For example, if the files on CD-ROM and U SB flash disk are copied by Windows, the files without owner are viewed in Linux; Another example is that the files installed by manual source package may not have an owner

Search by file type

[root@localhost ~]# find search path [options] search content
 Options:
		-type d: View directory
		-type f: Find common files
		-type l: Find soft link files

Logical operator

[root@localhost ~]# find search path [options] search content
 Options:
		-a: and Logic and
		-o: or Logical or
		-not: not Logical non

1) - a: and logic and
The find command also supports the logical operator option, where - a represents logic and operation, that is, the result of the find search is valid only if both conditions of - a are true. for instance:

[root@localhost ~]# find . -size +2k -a -type f
# Search for files larger than 2KB in the current directory and the file type is ordinary files

2) - o: or logical or
-The o option represents a logical or operation, that is, as long as one of the two conditions of - O is true, the find command can find the result. For example:

[root@localhost ~]# find . -name cangls -o -name bols
./cangls
./bols
# Search the current directory for files with names of either cangls or bols

3) - not: not logical

-not is a logical non, which means to go against. for instance:

[root@localhost ~]# find . -not -name cangls
# Search for files whose file name is not cangls in the current directory

Other options

1) - exec option
Here we mainly explain the two options "- exec" and "- ok". The basic functions of these two options are very similar. Let's first look at the format of the "- exec" option

[root@localhost ~]# find search path [options] search content - exec Command 2 {} \;

Secondly, the function of this option is to give the result of the find command to the command 2 called by "- exec" for processing. "{}" represents the search result of the find command

2) - ok option
The functions of the "- ok" option and the "- exec" option are basically the same. The difference is that the command 2 of "- exec" will be processed directly without asking: "ok" Command 2 will ask the user whether to handle it in this way before processing, and will be executed only after receiving the confirmation command

grep command: supplementary command

grep is used to extract and match the qualified serial characters in the file. The command format is as follows:

[root@localhost ~]# grep [options] "search content" file name
 Options:
		-i: ignore case
		-v: Reverse lookup
		--color=auto: The searched keywords are displayed in color

Find is also a search command. What's the difference between find and grep?

1) find command
The find command is used to search for qualified file names in the system. If fuzzy query is required, wildcards are used for matching. When searching, the file names match exactly (the find command can convert the matching rules into regular expression rules through the - regex option, but this is not recommended)

2) grep command
grep command is used to search for qualified strings in the file. If fuzzy query is needed, regular expression is used for matching. When searching, the string contains matches.

3) The difference between wildcards and regular expressions

Wildcard: used to match file names, exact match

wildcard effect
? Match any character
* Match 0 or any number of any characters, that is, you can match any content
[] Match any character in brackets. For example, [abc] means that it must match a character, either a, b, or c,
[-] Match any character in brackets, - represents a range. For example, [a-z] means matching a lowercase letter
[^] Logical non, indicating that the match is not a character in square brackets. For example, [^ 0-9] represents matching a character that is not a number

Regular expression: used to match strings, including matching

Regular character effect
? Match the previous character, repeat 0 times, or 1 times
* Match the previous character, repeat 0 times, or any number of times
[] Match any character in brackets. For example, [abc] means that it must match a character, either a, b, or c
[-] Match any character in brackets, - represents a range, for example, [a-z] represents matching a lowercase letter
[^] Logical non, indicating that the match is not a character in square brackets. For example, [^ 0-9] represents matching a character that is not a number
^ Match first line
$ Match end of line

Pipe symbols: supplementary commands

Command format: Command 1 command 2
The correct output of command 1 is the operation object of Command 2

1) Example 1:
For example, we often need to use the "ll" command to view the long format of files. However, there are many files in some directories, such as the / etc / directory. Using the "ll" command will display a lot of content. We can only see the last content, not the previous output. At this time, we immediately think of the more command to display the file content in separate screens, but how to make the more command display the output of the command in separate screens?

[root@localhost ~]# ll -a /etc/ > /root/testfile
# Using output redirection, save the output of the ll command to the / root/testfile file file
[root@localhost ~]# more /root/testfile
# Since testfile is a file, you can use the more command to split the screen
 Total consumption 1784
drwxr-xr-x. 105 root root 12288 10 December 21:49 .
...Omit partial output...
--More--(7%)

However, this operation is really inconvenient. At this time, the pipe symbol can be used. The command is as follows:

[root@localhost ~]# ll -a /etc/ | more

2) Example 2:
I want to search for the file name of yum in the result of command II /etc /. Should I use the find command? Or grep command?

[root@localhost ~]# ll -a /etc/ | grep yum

3) Example 3:
There are two commands in the x86.net-64-u.net-7 system (x86-tools.net) that need to be installed automatically:

[root@localhost ~]# netstat [options]
Options:
		-a: List all network status, including Socket program
		-c Seconds: Specifies that the network status is refreshed every few seconds
		-n: use IP Address and port number display, domain name and service name are not used
		-p: display PID And program name
		-t: Display use TCP Connection status of protocol port
		-u: Display use UDP Connection status of protocol port
		-l: Show only connections in listening status
		-r: Show routing table
[root@localhost ~]# netstat -an | grep "ESTABLISHED" | wc -l
# If you want to know the specific number of network connections, you can use the wc command to count the number of lines

Count the number of network connections being connected

Alias of command: supplementary command

The alias of the command is the nickname of the command, which is mainly used to take care of the usage habits of the administrator

Command format:
[root@localhost ~]# alias
# Query command alias
[root@localhost ~]# Alias alias = 'original command'
# Set command alias
 For example:
[root@localhost ~]# alias ser='service network restart'
# Use the ser alias instead of the service network restart command

The alias defined by the command takes effect temporarily. To take effect permanently, you need to write to the environment variable configuration file ~ / bashrc

Common shortcut keys: supplementary commands

Shortcut key effect
Tab key Command or file completion
ctrl + A Move the cursor to the beginning of the command line. If the command we entered is too long, it is used when we want to move the cursor to the beginning of the command line
ctrl + E Move the cursor to the end of the command line
ctrl + C Force termination of the current command
ctrl + L Clear screen, equivalent to clear command
ctrl + U Delete or cut the command before the cursor. I entered a long line of commands. I don't need to use the backspace key to delete characters one by one. It will be more convenient to use this shortcut key
ctrl + Y Paste the contents cut by ctrl + U

Compression and decompression commands

There are more than ten common compression formats that can be recognized in Linux, such as ". zip" ". gz" ". bz2" ". tar" ". tar.gz" ". tar.bz2"

1. "zip" format
". zip" is the most commonly used compression format in windows, and Linux can correctly recognize the ". Zip" format, which can easily compress files in common with Windows system

  • Compression command in ". zip" format
    The compression command is zip. Its basic information is as follows:
    -Command name: zip
    -package and compress (archive) files
    -Path: / usr/bin/zip
    -Execution Authority: all users
    -Function Description: compressed file or directory
    The command format is as follows:
[root@localhost ~]# Zip [options] zip package name source file or source directory
 Options:
		-r: Compressed directory
 For example:
[root@localhost ~]# zip ana.zip anaconda-ks.cfg
  • Unzip command in ". zip" format
    The decompression command in ". zip" format is unzip, and its basic information is as follows
    -Command name: unzip
    -list,test and extract compressed files in a ZIP archive
    -Path: / usr/bin/unzip
    -Execution Authority: all users
    -Function Description: list, test and extract files in compressed files
    The command format is as follows:
[root@localhost ~]# unzip [options] zip package name
 Options:
		-d: Specify the decompression location
 For example:
[root@localhost ~]# unzip -d /tmp/ ana.zip
# Unzip the compressed package to the specified location

2. "gz" format

  • Compression command in ". gz" format

". gz" format is the most commonly used compression format in Linux. Use gzip command for compression. Its basic information is as follows:

  • Command name: gzip
  • Compress or express files
  • Path: / bin/gzip
  • Execution Authority: all users
  • Function Description: compressed file or directory

The format of this command is as follows:

[root@localhost ~]# gzip [options] source file
 Options:
		-c: Exports compressed data to standard output, which can be used to preserve source files
		-d: decompression 
		-r: Compressed directory
 For example:
[root@localhost ~]# gzip -c anaconda-ks.cfg > anaconda-ks.cfg.gz
# Use the - c option, but instead of having the compressed data output to the screen, redirect it to a compressed file
# This allows you to compress the file without deleting the source file
  • Decompression command in ". gz" format

If you want to decompress ". gz" format, you can use "gzip -d compressed package" and "gunzip compressed package" commands. Let's first look at the basic information of the gunzip command
-Command name: gunzip
-Compress or express files
-Path: / bin/gunzip
-Execution Authority: all users
-Function Description: extract files or directories

For example:
[root@localhost ~]# gunzip install.log.gz
[root@localhost ~]# gzip -d anaconda-ks.cfg.gz

Both commands can decompress ". gz" format

3. Format of ". bz2"

  • "Compressed. ZB2" command
    ". bz2" format is another compression format of Linux. Theoretically speaking, the algorithm of ". Bz2" format is more advanced and the compression ratio is better; The ". gz" format has relatively faster compression time
    The compression command in ". bz2" format is bzip2. Let's take a look at the basic information of this command
    -Command name: bzip2
    -A block sorting file compressor
    -Path: / bzipr / bin
    -Execution Authority: all users
    -Function Description: Compression command in bz2 format
    Take a look at the format of the bzip2 command:
[root@localhost ~]# bzip2 [options] source file
 Options:
		-d: decompression 
		-k: Keep source files when compressing
		-v: Show details of compression
 For example:
[root@localhost ~]# bzip2 anaconda-ks.cfg
# Compress into bz2 format
[root@localhost ~]# bzip2 -k install.log.syslog
# Preserve source file compression
  • Decompression command in ". bz2" format

The ". bz2" format can be decompressed by using the "bzip2 -d compressed package" command, or by using the "bunzip2 compressed package" command. Let's first look at the basic information of bunzip2 command

  • Command name: bunzip2
  • A block sorting file compressor
  • Path: / usr/bin/bunzip2
  • Execution Authority: all users
  • Function Description: Decompression command in bz2 format
[root@localhost ~]# bunzip2 anaconda-ks.cfg.bz2
[root@localhost ~]# bzip2 -d install.log.syslog.bz2
# Both commands can be decompressed

4. "tar" format

  • Package command in ". tar" format

The ". Tar" format is packaged and unpacked with the tar command, except for different options. Let's first look at the basic information of the tar command.

  • Command name: tar
  • English original meaning: tar
  • Path: / bin/tar
  • Execution Authority: all users
  • Function Description: packing and unpacking commands

The basic format of the command is as follows:

[root@localhost ~]# tar [options] [- f package name] source file or directory
 Options:
		-c: pack
		-f: Specifies the file name of the compressed package. The extension of the compressed package is used to identify the format for the administrator, so be sure to specify the extension correctly
		-v: Displays the process of packaging files
[root@localhost ~]# tar -cvf anaconda-ks.cfg.tar anaconda-ks.cfg
# Packed, not compressed
  • Unpacking command in ". tar" format
    Unpacking in ". Tar" format also requires tar command, but the options are different. The command format is as follows:
[root@localhost ~]# tar [options] compressed package
 Options:
		-x: Unpacking
		-f: Specifies the file name of the compressed package
		-v: Show unpacking file process
		-t: Testing is just to see what files are in the package
		-C(large) Directories: specifying unpacking locations
for example
[root@localhost ~]# tar -xvf anaconda-ks.cfg.tar
# Unpack to current directory

5. "tar.gz" and ". tar.bz2" formats
Use the tar command to pack and compress directly. The command format is as follows:

[root@localhost ~]# tar [options] compressed package source file or directory
 Options:
		-z: Compression and decompression“.tar.gz"format
		-j: Compression and decompression“.tar.bz2"format
For example:.tar.gz format
[root@localhost ~]# tar -zxvd tmp.tar.gz /tmp/
# Package and compress the / tmp / directory directly into ". tar.gz" format
[root@localhost ~]# tar -zxvf tmp.tar.gz
# Decompress and unpack ". tar.gz" format
For example:.tar.bz format
[root@localhost ~]# tar -jcvf tmp.tar.bz2 /tmp/
# Package and compress to ". tar.bz2" format. Pay attention to the file name of the compressed package
[root@localhost ~]# tar -jxvf tmp.tar.bz2
# Decompress and unpack ". tar.bz2" format

A few more examples:

[root@localhost ~]# mkdir test
[root@localhost ~]# touch test/abc
[root@localhost ~]# touch test/bcd
[root@localhost ~]# touch test/cde
# Establish test directory and test files

[root@localhost ~]# tar -zxvf test.tar.gz test/
# compress
[root@localhost ~]# tar -zxvf test.tar.gz
# View only, no decompression
[root@localhost ~]# tar -zxvf test.tar.gz -C /tmp
# Extract to the specified location
[root@localhost ~]# tar -zxvf test.tar.gz -C /tmp test/cde
# Directly press the specific files in the compressed package to the specified location

Shutdown and restart commands

  1. sync data synchronization

The basic information of sync command is as follows:

  • Command name: sync
  • flush files system buffers
  • Path: / bin/sync
  • Execution Authority: all users
  • Function Description: refresh file system buffer
  1. shutdown command
    The basic information of the shutdown command is as follows:
  • Command name: shutdown
  • bring the system down
  • Path: / sbin/shutdown
  • Execution Authority: super user
  • Function Description: shutdown and restart

The basic format of the command is as follows:

[root@localhost ~]# shutdown [options] time [warning]
Options:
		-c: Cancel already executed shutdown command
		-h: Shut down
		-r: restart
  1. reboot command
    In the current system, the reboot command is also safe, and there is no need to add too many options
[root@localhost ~]# reboot
# restart
  1. halt and poweroff commands
    Both are shutdown commands, which can be executed directly. These two commands will not completely shut down and save the system services and are not recommended
[root@localhost ~]# halt
# Shut down
[root@localhost ~]# poweroff
# Shut down

5 init command

init is a command to modify the Linux operation level. It can also be used for shutdown and restart. This command is not safe and is not recommended

[root@localhost ~]# init 0
# Shut down, that is, call the 0 level of the system
[root@localhost ~]# init 6
# Restart, that is, call the system level 6

Common network commands

  1. Configure IP address
  • Configure IP address
    IP address is the only address code of a computer on the Internet. If each computer needs to access the network for data communication with other computers, it must be configured with a unique public network IP address
    There are two ways to configure IP addresses:

1) setup tool
2)vi /etc/sysconfig/network-scripts/ifcfg-eth0
Manually modify the configuration file

  • service network restart
[root@localhost ~]# service network restart
# service network restart 
  • The virtual machine needs to bridge to the wired network card and restart the network service

  • Copying an image may require resetting the UUID (unique identifier)

[root@localhost ~]# vi /etc/sysconfig/network-scripts/ifcg-eth0
# Delete MAC address line

[root@localhost ~]# rm -rf ,etc/udev/rules.d/70-persistent-net.rules
# Delete MAC address and UUID binding file

[root@localhost ~]# reboot
# Restart Linux
  1. ifconfig command
  • Command name: ifconfig
  • configure a network interface
  • Path: / sbin/ifconfig
  • Execution Authority: super user
  • Function Description: configure network interface

The main function of ifconfig command is to check the information of IP address. Just enter ifconfig command directly

[root@localhost ~]# ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
			# sign 																				 Maximum transmission unit
        inet 192.168.88.136  netmask 255.255.255.0  broadcast 192.168.88.255
        # IP address 						 Subnet mask 						 Broadcast address
        inet6 fe80::8476:8b32:797b:4fda  prefixlen 64  scopeid 0x20<link>
        # IPv6 address (currently not in effect)
        ether 00:0c:29:e1:93:84  txqueuelen 1000  (Ethernet)
        # MAC address
        RX packets 25935  bytes 2231846 (2.1 MiB)
        # Received packets
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 9680  bytes 2747065 (2.6 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        # Packet sent
        
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
# Local loopback network card
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0        
  1. ping command
    Ping is a common network command. It mainly detects the network through ICMP Protocol and tests the communication of hosts in the network. The basic information of the ping command is as follows:
  • Command name: ping
  • send ICMP ECHO_REQUEST to network hosts
  • Path: / bin/ping
  • Execution Authority: all users
  • Function Description: send ICMP request to network host

The basic format of the command is as follows:

[root@localhost ~]# ping [options] IP
 Options:
		-b: The broadcast address is added later to detect the whole network segment
		-c Times: used to specify ping Number of
		-s Byte: Specifies the size of the probe packet

Example: probe available hosts in a network segment

In the ping command, you can use the "- b" option, followed by a broadcast address to detect the entire network segment. We can use this option to know how many hosts in the whole network can communicate with us without detecting one IP address. For example:

[root@localhost ~]# ping -b -c 3 192.168.88.255
WARNING: pinging broadcast address
PING 192.168.88.255 (192.168.88.255) 56(84) bytes of data.
64 bytes from 192.168.88.2: icmp_seq=1 ttl=128 time=0.215 ms
64 bytes from 192.168.88.2: icmp_seq=2 ttl=128 time=0.221 ms
64 bytes from 192.168.88.2: icmp_seq=3 ttl=128 time=0.256 ms
64 bytes from 192.168.88.2: icmp_seq=4 ttl=128 time=0.263 ms
64 bytes from 192.168.88.2: icmp_seq=5 ttl=128 time=0.280 ms
64 bytes from 192.168.88.2: icmp_seq=6 ttl=128 time=0.265 ms
# How many hosts can be detected in the 192.0/24 communication segment
  1. netstat command
    netstat is a command to view the status of the network segment. You can view the ports opened locally and the client connections.
    In CentOS 7 The netstat command in X is not installed by default. If you need to use it, you need to install net SNMP and net tools packages

The basic information of netstat command is as follows:

  • Command name: netstat
  • Print network connections, routing tables, interface statistics, masquerade connections, and multicast membership
  • Path: / bin/netstat
  • Execution Authority: all users
  • Function Description: output network connection, routing table, interface statistics, camouflage connection and multicast members

The command format is as follows:

[root@localhost ~]# netstat [options]
Options:
		-a: List all network status, including Socket program
		-c Seconds: Specifies that the network status is refreshed every few seconds
		-n: use IP Address and port number display, domain name and service name are not used
		-p: display PID And program name
		-t: Display use TCP Connection status of protocol port
		-u: Display use UDP Connection status of protocol port
		-l: Show only connections in listening status
		-r: Show routing table

Example 1: view the port opened by this machine
This is the most commonly used method on this machine. Use the option "- tuln". Because the "- l" option is used, you can only see the connection in listening status, but not the connection in established status. For example:

[root@localhost ~]# netstat -tuln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN
tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN
tcp6       0      0 :::111                  :::*                    LISTEN
tcp6       0      0 :::22                   :::*                    LISTEN
tcp6       0      0 ::1:631                 :::*                    LISTEN
tcp6       0      0 ::1:25                  :::*                    LISTEN
udp        0      0 0.0.0.0:44987           0.0.0.0:*
udp        0      0 0.0.0.0:24010           0.0.0.0:*
udp        0      0 192.168.122.1:53        0.0.0.0:*
udp        0      0 0.0.0.0:67              0.0.0.0:*
udp        0      0 0.0.0.0:68              0.0.0.0:*
udp        0      0 0.0.0.0:5353            0.0.0.0:*
udp        0      0 127.0.0.1:323           0.0.0.0:*
udp6       0      0 ::1:323                 :::*
udp6       0      0 :::54123                :::*
# IP address and port number of the protocol receiving queue and sending queue 			 IP address and port number of remote host 	 state

This command has more output

  • Proto: the protocol of network connection, generally TCP protocol or UDP protocol
  • Recv-Q: indicates that the received data has been in the local buffer, but has not been taken away by the process
  • Send-Q: indicates that the data sent from the local machine but not received by the other party is still in the local buffer. Generally, it is a data packet without ACK flag
  • Local Address: the IP address and port number of this machine
  • Foreign Address: the IP address and port number of the remote host
  • State: state. The common states are as follows:
    -LISTEN: listening status. Only TCP protocol needs to LISTEN, but UDP protocol doesn't
    -ESTABLISHED: the status of the ESTABLISHED connection. If you use the "- l" option, you will not see the status of the ESTABLISHED connection.
    - SYN_SENT: syn initiated packets are packets that initiate connections actively
    - SYN_RECV: received data packet of active connection
    - FIN_WAIT1: disconnecting
    - FIN_WAIT2: the connection has been interrupted, but is waiting for the other host to confirm
    - TIME_WAIT: the connection has been interrupted, but the socket is still waiting for the end in the network
    -CLOSED: the socket is not in use
    Among these States, the most commonly used are the LISTEN and ESTABLISHED states. One represents listening and the other represents ESTABLISHED connection

Example 2: check the ports opened by the programs on this machine
If you use the "- p" option, you can see which program occupies the port and guide the PID of the program. For example:

[root@localhost ~]# netstat -tulnp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd
tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN      1148/dnsmasq
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      967/sshd
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      963/cupsd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1139/master
tcp6       0      0 :::111                  :::*                    LISTEN      1/systemd
tcp6       0      0 :::22                   :::*                    LISTEN      967/sshd
tcp6       0      0 ::1:631                 :::*                    LISTEN      963/cupsd
tcp6       0      0 ::1:25                  :::*                    LISTEN      1139/master
udp        0      0 0.0.0.0:44987           0.0.0.0:*                           591/avahi-daemon: r
udp        0      0 0.0.0.0:24010           0.0.0.0:*                           124716/dhclient
udp        0      0 192.168.122.1:53        0.0.0.0:*                           1148/dnsmasq
udp        0      0 0.0.0.0:67              0.0.0.0:*                           1148/dnsmasq
udp        0      0 0.0.0.0:68              0.0.0.0:*                           124716/dhclient
udp        0      0 0.0.0.0:5353            0.0.0.0:*                           591/avahi-daemon: r
udp        0      0 127.0.0.1:323           0.0.0.0:*                           555/chronyd
udp6       0      0 ::1:323                 :::*                                555/chronyd
udp6       0      0 :::54123                :::*                                124716/dhclient
# There is one more "- p" option than the previous command, and the result is "PID / program name". You can know which program occupies the port

Example 3: view all connections
Use the "- an" option to view all connections, including those in listening status (LISTEN), those in ESTABLISHED status (ESTABLISHED), Socket program connections, etc. Because there are many connections, there are many output contents. For example:

[root@localhost ~]# netstat -an
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN
tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN
tcp        0     36 192.168.88.136:22       192.168.88.1:64457      ESTABLISHED

Starting from "Active UNIX domain sockets", the following content is the connection generated by the Socket program. The previous content is the connection generated by the network service. We can see various network connection states in the output of "- an" option, while the previous "- tuln" option can only see the listening state

  1. write command
    The basic information of the write command is as follows
  • Command name: write
  • send a message to another user
  • Path: / usr/bin/write
  • Execution Authority: all users
  • Function Description: send information to other users
[root@localhost ~]# write userl pts/1
hello
# Send data to the remote login terminal by pressing Ctrl / 1 (PTL + users)
  1. wall command
    The write command is used to send information to specified users, while the wall command is used to send information to all logged in users, including yourself. When executing, add the information to be sent after the wall command, for example:
[root@localhost ~]# wall "I will be in 5 minutes to restart, please save your data"
  1. mail command
    Mail is a Linux mail client command, which can be used to send mail to other users. The basic information of the mail command is as follows:
  • Command name: mail
  • send and receive Internet mail
  • Path: / bin/mail
  • Execution Authority: all users
  • Function Description: send and receive e-mail

Example 1: send mail

If we want to send mail to other users, we can execute the following command:

[root@localhost ~]# mail userl
Subject: hello				<-		Mail title
Nice to meet you!		<- 	Email details
.									<-		Use“."To end the mail entry
# Send email to userl user

The emails we receive are saved in "/ var/spool/mail / user name", and each user has an email named after his own user name

Example 2: send file content

If we want to send the contents of a file to the specified user, we can execute the following command:

[root@localhost ~]# mail -s "test mail" root < /root/anaconda-ks.cfg
 Options:
		-s: Specify message title
# Put / root / Anaconda KS The contents of the cfg file are sent to the root user

When we write a script, sometimes we need the script to automatically send some information to the designated user. It is a very good choice to write the information to be sent to the file in advance.

Example 3: View received mail
"We can directly execute the mail command in the command, enter the interactive command of mail, and view the received mail here. For example:

[root@localhost ~]# mail
Heirloom Mail version 12.5 7/5/10.  Type ? for help.
"/var/spool/mail/liuyong": 2 messages 1 new
    1 root                  Thu Sep  3 18:13  22/655   "111111111" <- Previously received mail
>N  2 root                  Thu Sep  3 19:44  18/626   "hello"
#Unread number sender 		 time 									 title
																							<- Wait for user input command

You can see the received mail list, "N" represents unread mail. If it is a read mail, there will be no "N" in front of it; The next number is the number of the mail. We mainly use this number to operate the mail. If we want to view the first email, just enter the email number "1".
Execute "?" in the interactive command, You can view the commands supported by this interactive interface. For example:

& ?										<- Enter command
               mail commands
type <message list>             type messages
next                            goto and type next message
from <message list>             give head lines of messages
headers                         print out active message headers
delete <message list>           delete messages
undelete <message list>         undelete messages
save <message list> folder      append messages to folder and mark as saved
copy <message list> folder      append messages to folder without marking them
write <message list> file       append message texts to file, save attachments
preserve <message list>         keep incoming messages in mailbox even if saved
Reply <message list>            reply to message senders
reply <message list>            reply to message senders and all recipients
mail addresses                  mail to specific recipients
file folder                     change to another folder
quit                            quit and apply changes to folder
xit                             quit and discard changes made to folder
!                               shell escape
cd <directory>                  chdir to directory or home if none given
list

These interactive commands can simplify input. For example, "headers" command, you can directly enter "h", which is the command to list mail headers. Let's explain the common interactive commands

  • Headers: list the mail headers, and directly enter the "h" command
  • Delete: deletes the specified message. For example, if you want to delete the second email, you can enter "d 2"
  • Save: save the message. You can save the specified mail as a file, such as "s 2 /tmp/test.mail"
  • quit: exit and save the mail that has been operated, such as removing deleted mail, saving read mail, etc
  • Exit: exit without saving any operations

System trace command

There are some important trace log files in the system, such as: / var/log/wtmp, / var/run/utmp, / var/log/btmp
/var/log/lastlog and other log files. If you open these files with vim, you will find that these files are binary garbled. This is because these logs store important login traces of the system, including important system information such as when a user logged in to the system, when he exited the system, wrong login and so on. If this information can be opened through vim, it can be edited, so the trace information is inaccurate. Therefore, these important trace logs can only be viewed through the corresponding commands

  1. w command
    The w command is a command to display the login user information in the system. The trace log viewed by this command is / var/run/utmp. The basic information of this command is as follows:
  • Command name: w
  • Show who is logged on and what they are doing
  • Path: / usr/bin/w
  • Execution Authority: all users
  • Function Description: displays the logged in user and what he is doing

For example:

[root@localhost ~]# w
 20:13:38 up 4 days, 33 min,  2 users,  load average: 0.00, 0.01, 0.05
 #system time 	 Continuous startup time 		 log on user 			 Average load of the system before 1 minute, 5 minutes and 15 minutes
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    192.168.88.1     19:27   17:38   0.03s  0.00s mail
liuyong  pts/1    192.168.88.1     19:27    2.00s  0.04s  0.02s w

The first line of information is as follows:

content explain
12:26: 46 Current system time
up 1 day,13:32 The running time of the system, the machine has been running for 13 hours and 32 minutes a day
2 users Two users are currently logged in
load average: 0.00,0.00,0.00 The average load of the system in the previous 1 minute, 5 minutes and 15 minutes. If the CPU is single core, if the value exceeds 1, it is high load; If the CPU is quad core, the value above 4 is a high load (the average load is judged entirely based on personal experience, and it is generally believed that it should not exceed the number of cores of the server CPU)

The second line of information is as follows:

content explain
USER Currently logged in user
TTY Login terminal: tty1-6: local character terminal (alt+F1-6 switching); tty7: local graphic terminal (for ctrl+alt+F7 switching, the startup graphic interface must be installed); pts/0-255: remote terminal
FROM The login IP address is empty if it is a local terminal
LOGIN@ login time
IDLE User idle time
JCPU CPU time occupied by all processes
PCPU CPU time occupied by the current process
WHAT User's operation in progress
  1. who command
    The who command is similar to the w command. It is used to view the user logging in, but the content displayed is simpler. It is also used to view the / var/run/utmp log
[root@localhost ~]# who
root     pts/0        2020-09-03 19:27 (192.168.88.1)
liuyong  pts/1        2020-09-03 19:27 (192.168.88.1)
#User name login terminal login time
  1. last command
    The last command is to view the information of all users who have logged in the system, including the users who are logging in and the users who logged in before. This command looks at the / var/log/wtmp trace log file
[root@localhost ~]# last
liuyong  pts/1        192.168.88.1     Thu Sep  3 19:27   still logged in
root     pts/0        192.168.88.1     Thu Sep  3 19:27   still logged in
#User name and terminal number 	 Source IP address 		 Landing time 		 Exit time
liuyong  pts/0        :0               Mon Aug 24 20:07 - 19:55 (1+23:47)
liuyong  :0           :0               Sun Apr 26 23:59 - crash (121+19:56)
reboot   system boot  3.10.0-693.el7.x Sun Apr 26 23:57 - 22:42 (129+22:44)
#System restart information record
  1. lastlog command
    The lastlog command is to view the last login time of all users in the system. The log he views is the / var/log/lastlog file
[root@localhost ~]# lastlog
Username         Port     From             Latest
root             pts/0    192.168.88.1     Thu Sep  3 19:27:05 -0700 2020
bin                                        **Never logged in**
daemon                                     **Never logged in**
adm                                        **Never logged in**
lp                                         **Never logged in**
sync                                       **Never logged in**
...Omitted part...
#user name 		 Terminal number 		  Source IP 			 Landing time
  1. lastb command

The lastb command is used to view the error login information. It is used to view the / var/log/btmp trace log:

[root@localhost ~]# lastb
root     ssh:notty    192.168.88.1     Thu Sep  3 22:52 - 22:52  (00:00)
#Wrong login user 	 terminal 							 Time of attempt to log in

Mount command

  1. Basic format of mount command

All storage devices in linux must be mounted and used, including hard disk

  • Command name: mount
  • Command path: / bin/mount
  • Execution Authority: all users

The command format is as follows:

[root@localhost ~]# mount [-l]
# Query the mounted devices in the system, -l and the volume label name will be displayed
[root@localhost ~]# mount -a
#Mount automatically according to the contents of the configuration file / etc/fstab
[root@localhost ~]# mount [-t file system] [- L volume label] [- o special options]\
Device file name mount point
#\It means that this line is not finished, and the line breaks
 Options:
		-t File system: add file system type to specify the type of mount. You can ext3,ext4,iso9660 And other file systems. Refer to 9 for details-1
		-L Volume label name: mount the partition of the specified volume label instead of the file name of the installation device
		-o Special options: you can specify additional options for mounting, such as read-write permission, synchronous asynchronous, etc. if not specified, the default value will take effect. See table for specific special options
parameter explain
atime/noatime Update access time / do not update access time. Whether to update the access time of the file when accessing the partition file. The default is update
async/sync Asynchronous / synchronous, asynchronous by default
auto/noauto Automatic / Manual: whether the contents of the / etc/fstab file will be mounted automatically when the mount -a command is executed. The default is automatic
defaults Define default values, equivalent to rw, suid, dev, exec, auto, nouser and async
exec/noexec Execute / not execute: set whether to allow executable files to be executed in the file system. The default is exec allow
remount Remount a mounted file system. It is generally used to specify special permissions for modification
rw/ro Read write / read-only: whether the file system has read-write permission when it is mounted. The default is rw
suid/nosuid With / without SUID permission, set whether the file system has SUID and SGID permission. The default is yes
usrquota Write represents that the file system supports user disk quota, which is not supported by default
grpquota Write represents the disk quota of the file system support group, which is not supported by default

give an example:

Example 1:
[root@localhost ~]# mount
#Check the mounted file system in the system and note that there is a virtual file system
sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime,seclabel)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
devtmpfs on /dev type devtmpfs (rw,nosuid,seclabel,size=485156k,nr_inodes=121289,mode=755)
securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime)
tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev,seclabel)
devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,seclabel,gid=5,mode=620,ptmxmode=000)
# The result of the command is that the: / dev/sda3 partition is mounted to the / directory, the file system is ext4, and the permissions are read and write

Example 2: modify special permissions
[root@localhost ~]# mount
#If we see that the / boot partition has been mounted and the defaults option is used, we will remount the partition and use noexec
#The permission system executes the file to see what happens (be careful not to use it)/Test in different areas,#Otherwise, the system command cannot be executed)
---Omit partial output...
/dev/sda1 on /boot type ext4(rw)
...Omit partial output...
[root@localhost ~]# mount -o remount,noexec /boot
#Remount the / boot partition and use the noexec permission
[root@localhost sh]# cd /boot/
[root@localhost boot]# vi hello.sh
#Write a shell
#!/bin/bash
echo"hello!!"
[root@localhost boot]# chmod 755 hello.sh
[root@localhost boot]# ./hello.sh
-bash: ./hello.sh: Permission not checked
#Although it gives hello SH execute permission, but it still cannot be executed
[root@localhost boot]# mount -o remount,exec /boot
#Remember to change it back, if it doesn't affect the system startup

If we do experiments and modify special options, we must remember and make sure that we need to modify them, otherwise we are very prone to system problems, and we can't find out where the problems are

Example 3: Mount partition
[root@localhost ~]# mkdir /mnt/disk1
#Create mount point directory
[root@localhost ~]# mount /dev/sdb1 /mnt/disk1
#Mount partition
  1. CD mount
    The premise of CD mounting is still to specify the device file name of the CD. The device file names are different for different versions of Linux:
  • CentOS 5.x previous system, the file name of the optical device is dev/hdc
  • CentOS 6. For systems after X, the file name of the optical device is / dev/sr0
    No matter which system has a soft connection / dev/cdrom, and the device file name that can be used as a CD
[root@localhost ~]# mount -t iso9660 /dev/cdrom /mnt/cdrom/
#Mount CD

Remember to uninstall after use:

[root@localhost ~]# umount /dev/sr0
[root@localhost ~]# umount /mnt/cdrom
#Because the device file name and mount point are connected together, you can uninstall either one

Note: when uninstalling, you need to exit the CD directory to uninstall normally

33 mount U SB flash disk

USB flash disk and hard disk share the same device file name, so the device file name of USB flash disk is not fixed and needs to be queried manually. Query command:

[root@localhost ~]# fdisk -l
# Query hard disk

Then mount. The mount command is as follows:

[root@localhost ~]# mount -t vfat /dev/sdb1 /mnt/usb/
# Mount the U SB flash disk. Because it is a Windows partition, it is in vfat file system format

If there is Chinese on the U SB flash drive, you will find that Chinese is garbled. Linux needs two conditions to display Chinese normally:

  • Chinese code and Chinese font are installed
  • The operating terminal needs to support Chinese display (pure character terminal does not support Chinese coding)
    Our current system is equipped with Chinese code and font, and xshell remote terminal is a program under Windows, which of course supports Chinese display. The reason why the U SB flash disk is still garbled is that the Chinese code needs to be manually specified during mounting, for example:
[root@localhost ~]# mount -t vfat -o iocharset=utf8 /dev/sdb1 /mnt/usb/
#Mount the USB flash disk and specify the Chinese coding format as UTF-8

If you need to uninstall, you can execute the following commands:

[root@localhost ~]# umount /mnt/usb/
  1. Mount NTFS partition
  • Linux driver loading sequence
    -The driver is directly put into the system kernel. This kind of driver is mainly the driver necessary for system startup and loading, and the number is small
    -The driver is put into the hard disk in the form of module. Most drivers have been saved in this way in / lib / modules / 3.10.0-693 el7. x86_ In 64 / kernel /
    -The driver can be recognized by Linux, but the system believes that this driver is generally not commonly used and is not loaded by default. If you need to load this driver, you need to recompile the kernel, which is the case with NTFS file system drivers
    -The hardware cannot be recognized by the Linux kernel and the driver needs to be installed manually. Of course, the premise is that the manufacturer provides the hardware driver for Linux, otherwise you need to develop the driver yourself

  • Install NTFS file system module using NTFS-3G
    -Download NTFS-3G plug-in
    We from the website http://www.tuxera.com/community/ntfs-3g-download/ Download NTFS-3G plug-in to Linux server
    -Install NTFS-3G plug-in
    Before compiling and installing NTFS-3G plug-in, ensure that gcc compiler is installed. The specific installation commands are as follows:

[root@localhost ~]# tar -zxvf ntfs-3g_ntfsprogs-2013.1.13.tgz
#decompression
[root@localhost ~]# cd ntfs-3g_ntfsprogs-2013.1.13
#Enter the decompression directory
[root@localhost ntfs-3g_ntfsprogs-2013.1.13]# ./configure
#Compiler preparation. The installation directory is not specified. It is installed in the default location
[root@localhost ntfs-3g_ntfsprogs-2013.1.13]# make
# compile
[root@localhost ntfs-3g_ntfsprogs-2013.1.13]# make install
# Compile and install

The installation is complete. You can mount and use the NTFS partition of Windows. However, it should be noted that the file system when mounting the partition is not NTFS, but ntfs-3g. The mount command is as follows:

[root@localhost ~]# mount -t ntfs-3g partition device file name mount point

For example:
[root@localhost ~]# mount -t ntfs-3g /dev/sdb1 /mnt/win

Tags: Linux

Posted by itpvision on Mon, 16 May 2022 10:32:50 +0300