Welcome to DOFBOT-Ultra repository
14.Linux command usage
Linux command usage
Linux command usage1. apt2. dmesg3. dpkg-deb4. dpkg5. find6. grep command7. ifconfig8. ip9. mount10. netstat11. nohup12. ps13. route14. rsync15. scp16. ssh17. tar18. topGrammar explanationOption DescriptionTop interaction commandDisplay informationCommon commands19. zip
1. apt
apt (Advanced Packaging Tool) is a shell frontend package manager in Debian and Ubuntu.
apt command provides commands for finding, installing, upgrading, and deleting a single, a group, or even all software packages, and the commands are concise and easy to remember.
The execution of the apt command requires super-administrator privileges (root).
Grammar explanation
xxxxxxxxxxapt [options] [command] [package ...]- options: Optional, options include - h (Help), - y (When prompted to select all as "yes" during installation), - q (Do not display installation process), and so on.
- command:The operation to be performed.
- package: The name of the installed package.
Common commands
Update the apt software source database:sudo apt update
Update installed software packages:sudo apt upgrade
List upgradable software packages and version information:apt list --upgradeable
Upgrade software package, delete the package that needs to be updated before upgrading:sudo apt full-upgrade
Install the specified software command:sudo apt install <package_name>
Install multiple software packages:sudo apt install <package_1> <package_2> <package_3>
Display specific information about the software package, such as version number, installation size, dependencies, etc:sudo apt show <package_name>
Delete package command:sudo apt remove <package_name>
Clean up dependencies and library files that are no longer in use: sudo apt autoremove
Remove software packages and configuration files: sudo apt purge <package_name>
Find software package command: sudo apt search <package_name>
List all installed packages:apt list --installed
List the version information of all installed packages:apt list --all-versions
2. dmesg
The dmesg command is used to view or control the kernel ring buffer.
The kernel will store the kernel startup log in the ring buffer. If you don't have time to view the information when turning on the computer, you can use dmesg to check.
Grammar explanation
xdmesg [options]dmesg -C / dmesg --cleardmesg -c / dmesg --read-clear [options]- Option description
- -c, --read-clear After displaying the information, clear the contents of the ring buffer.
- -C, --clear Clear the contents of the ring buffer.
Common commands
Display the kernel log contents of all ring buffers
xxxxxxxxxxdmesgSave kernel logs to a file
xxxxxxxxxxdmesg > kernel.logClearing cache logs can reduce log content during driver debugging
xxxxxxxxxxdmesg -C
3. dpkg-deb
dpkg deb command is a package management tool under Debian Linux, which can perform packaging and unpacking operations on software packages and provide package information.
Grammar explanation
xxxxxxxxxx dpkg-deb [<option> ...] <command>Command description
dpkg-deb command not only has options to set, but also requires commands to perform different functions.
- -b:Create a debian software package;
- -c:Display the file list in the software package;
- -e:Decompress the main control information;
- -f:Print the field content to standard output;
- -x:Release the files in the software package to the specified directory;
- -X:Release the files in the software package to the specified directory and display the detailed process of releasing the files;
- -w:Display information about software packages;
- -l:Display detailed information of the software package;
- -R:Extract control information and archive inventory files;
- -b: Create a debian package.
- -c: Display the file list in the software package.
- -e: Decompress the main control information.
- -f: Print the field content to standard output.
- -x: Release files from the software package to the specified directory.
- -X: Release the files in the software package to the specified directory and display the detailed process of releasing the files.
- -w: Display information about the software package.
- -l: Display detailed information of the software package.
- -R: Extract control information and archive inventory files.
Option description
-v, --verbose:Enable detailed output.-D, --debug:Enable debugging output.--showformat=<format>:Use alternative formats for--show。--deb-format=<format>:Select the archive format. The allowed values are 0.939000 and 2.0 (default values).--nocheck:Prohibit controlling file checks (building malicious software packages).--root-owner-group:Force the owner and group of the file to be root.--[no-]uniform-compression:Use compression parameters on all members. If specified, uniform compression parameters will be used.
-z#:Set the compression level during construction.-Z<type>:Set the compression type used during construction. The allowed types are gzip, xz, zstd, and none.-S<strategy>:Set compression strategy during construction. The allowed values are none, extreme (xz), filtered, Huffman, rle, fixed (gzip).
Common commands
Extract program files
xxxxxxxxxxdpkg-deb -x hobot-configs_2.2.0-20231030133209_arm64.debExtract control file
xxxxxxxxxxdpkg-deb -e hobot-configs_2.2.0-20231030133209_arm64.deb hobot-configs/DEBIANQuery the file contents in the deb package
xxxxxxxxxxdpkg-deb -c hobot-configs_2.2.0-20231030133209_arm64.deb
4. dpkg
Install, create, and manage software packages on a Debian Linux system.
dpkg command is a utility used by Debian Linux systems to install, create, and manage software packages.
Grammar explanation
xxxxxxxxxxdpkg [<option> ...] <command>Command description
dpkg command not only has options to set, but also requires commands to perform different functions.
- -i:Install software packages.
- -r:Delete software packages.
- -P:Delete software packages while deleting their configuration files.
- -L:List files belonging to the specified software package.
- -l:Briefly list the status of the software package.
- -S:Search for software packages containing specified files.
- --unpack: Unpack the software package.
- -c:Display the file list within the software package.
- --confiugre: Configure software packages.
Option description
- --admindir=
Use instead of/var/lib/dpkg. - --root=
Install to another root directory. - -- instdir=
Change the installation directory while keeping the management directory unchanged. - -- path exclude=
Do not install paths that match Shell expressions. - --path include=
After excluding a pattern, include another pattern. - -O | -- selected only ignores software packages that have not been selected for installation or upgrade.
- -E | -- skip same version ignores packages with the same version as the installed software version.
- -G | -- reuse downgrade ignores packages with versions earlier than the installed software version.
- -B | -- Auto configure needs to be installed even if it affects other software packages.
- --[no-]triggers Skip or force trigger handling that occurs with it.
- -- verify format=
Check the output format ('rpm 'is supported). - --no-debsig does not attempt to verify the signature of the software package.
- -D | -- debug=
Enable debugging (see - DHelp or -- debug=help). - --status logger=
sends status updates to the standard input of . - --log=
Update status and operation information to . - --ignore pending=
Ignore all dependencies related to . - --force-... Ignore the problems encountered (see -- force help).
- --no-force-...|-- Pause when encountering problems.
- --abort-after encountering
errors cumulatively.
- --admindir=
Common commands
- Installation package
xxxxxxxxxxdpkg -i package.deb- Delete package
xxxxxxxxxxdpkg -r package- Delete packages (including configuration files)
xxxxxxxxxxdpkg -P package- List the files associated with the package
xxxxxxxxxxdpkg -L package- Display the version of the package
xxxxxxxxxxdpkg -l package- Unzip the contents of the deb package
xxxxxxxxxxdpkg --unpack package.deb- Search for the content of the package to which it belongs
xxxxxxxxxxdpkg -S keyword- List the currently installed packages
xxxxxxxxxxdpkg -l- List the contents of the deb package
xxxxxxxxxxdpkg -c package.deb- Configuration package
xxxxxxxxxxdpkg --configure package
5. find
The find command is used to search for files and directories in a specified directory.
It can use different options to filter and restrict the search results. Any string before the parameter will be considered as the directory name to be searched for. If no parameters are set when using this command, the find command will search for subdirectories and files in the current directory. And display all the subdirectories and files found.
Grammar explanation
xxxxxxxxxxfind [-H] [-L] [-P] [-Olevel] [-D debugopts] [path...] [expression]Option description
path The directory path to be searched can be a single directory or file name, or multiple paths separated by spaces. If no path is specified, it defaults to the current directory.
expression It is an optional parameter used to specify the search criteria, which can include file name, file type, file size, and so on.
There are many options available in the expression, and the most commonly used ones are listed below.
-name pattern:Search by file name, supporting the use of wildcard characters*and?.-iname pattern:The effect of this parameter is similar to specifying the- nameparameter, but ignores the difference in character case;-type type:Search by file type, which can bef(regular file),d(directory),l(symbolic link), etc.-size [+-]size[cwbkMG]:Search by file size, supporting the use of+or-to indicate larger or smaller than a specified size. The units can bec(bytes),w(word count),b(block count),k(KB),M(MB), orG(GB).-mtime days:Search by modification time, supports using+or-to indicate before or after a specified number of days, days is an integer representing the number of days.-user username:Search by file owner.-group groupname:Search by file group.
The parameters used for time in the find command are as follows.
-amin n:Search for files that have been accessed within n minutes.-atime n:Search for files that have been accessed within n*24 hours.-cmin n:Search for files with status changes (such as permissions) within n minutes.-ctime n:Search for files with status changes (such as permissions) within n*24 hours.-mmin n:Search for files that have been modified within n minutes.-mtime n:Search for files that have been modified within n*24 hours.
Among these parameters, n can be a positive, negative, or zero number.
Positive numbers indicate files that have been modified or accessed within a specified time.
Negative numbers indicate files that have been modified or accessed before the specified time.
Zero indicates files that have been modified or accessed at the current time point.
For example, - mtime 0 indicates searching for files modified today, and - mtime -7indicates searching for files modified a week ago.
Explanation on the parameter of time n:
- +n:Search for files or directories that are older than n days ago.
- -n:Search for files or directories that have changed their properties within n days.
- n:Find files or directories whose properties have been changed n days ago (specify the day).
Common commands
List all files and folders in the current directory and subdirectories
xxxxxxxxxxfind .Search for a file named 'file. txt' in the current directory
xxxxxxxxxxfind . -name file.txtList all files with the suffix . c in the current directory and its subdirectories
xxxxxxxxxxfind . -name "*.c"Same as above, but ignoring capitalization
xxxxxxxxxxfind . -iname "*.c"List all files in the current directory and its subdirectories
xxxxxxxxxxfind . -type fSearch for files larger than 1MB in the/home directory
xxxxxxxxxxfind . -size +1MSearch for files smaller than 10KB
xxxxxxxxxxfind . -type f -size -10kSearch for files equal to 10KB
xxxxxxxxxxfind . -type f -size 10kFile size unit:
- b —— Block (512 bytes)
- c —— Byte
- w —— Word(2 bytes)
- k —— kilobyte
- M —— megabyte
- G —— Gigabyte
Search for files in/var/log directory that were modified 7 days ago.
xxxxxxxxxxfind /var/log -mtime +7List all files in the current directory and its subdirectories that have been updated in the last 20 days.
xxxxxxxxxxfind . -ctime 20List all files updated 20 days ago or earlier in the previous directory and its subdirectories.
xxxxxxxxxxfind . -ctime +20List all files updated within the last 20 days in the current directory and its subdirectories.
xxxxxxxxxxfind . -ctime 20Search for regular files in the/var/log directory that have been changed before the 7th, and ask them before deleting them.
xxxxxxxxxxfind /var/log -type f -mtime +7 -ok rm {} \;Find files in the current directory that belong to the owner with read and write permissions, and whose group users and other users have read permissions.
xxxxxxxxxxfind . -type f -perm 644 -exec ls -l {} \;Find all regular files with a length of 0 in the system and list their complete paths.
xxxxxxxxxxfind / -type f -size 0 -exec ls -l {} \;Search for all files ending in. txt and. pdf in the current directory and subdirectories.
xxxxxxxxxxfind . \( -name "*.txt" -o -name "*.pdf" \)Orfind . -name "*.txt" -o -name "*.pdf"Match file path or file.
xxxxxxxxxxfind /usr/ -path "*local*"Matching file paths based on regular expressions.
xxxxxxxxxxfind . -regex ".*\(\.txt\|\.pdf\)$"Same as above, but ignoring capitalization.
xxxxxxxxxxfind . -iregex ".*\(\.txt\|\.pdf\)$"Negative parameter, find files under/home that do not end in. txt.
xxxxxxxxxxfind /home ! -name "*.txt"Search by file type.
xxxxxxxxxxfind . -type Type parameterType parameter list
- f Regular file
- l Symbol connection
- d Directory
- c Character device
- b Block device
- s Socket
- p Fifo
Based on directory depth search, the maximum downward depth limit is 3
xxxxxxxxxxfind . -maxdepth 3 -type fSearch for all files with a depth distance of at least 2 subdirectories from the current directory
xxxxxxxxxxfind . -mindepth 2 -type fDelete all
.logfiles in the current directory.xxxxxxxxxxfind . -type f -name "*.log" -deleteSearch for a file with permission 777 in the current directory
xxxxxxxxxxfind . -type f -perm 777Find the
. conffile in the current directory with permissions other than 644xxxxxxxxxxfind . -type f -name "*.conf" ! -perm 644Find all files owned by the current directory user
sunrisexxxxxxxxxxfind . -type f -user sunriseFind all files owned by the current directory user group
sunrisexxxxxxxxxxfind . -type f -group sunriseFind all
rootfiles in the current directory and change the ownership to usersunrisexxxxxxxxxxfind .-type f -user root -exec chown sunrise {} \;In the example above, {} is used in combination with the -exec option to match all files, which are then replaced with the appropriate file name.
Find all the
.txtfiles in thehomedirectory and delete them.xxxxxxxxxxfind $HOME/. -name "*.txt" -ok rm {} \;In the above example, the behavior of - ok and - executive is the same, but it will give a prompt whether to perform the corresponding operation.
Search for all
. txtfiles in the current directory and concatenate them to write them into theall. txtfilexxxxxxxxxxfind . -type f -name "*.txt" -exec cat {} \;> /all.txtSearch for all. txt files in the current directory or subdirectories, but skip subdirectories sk
xxxxxxxxxxfind . -path "./sk" -prune -o -name "*.txt" -print⚠️ ./sk cannot be written as./sk/; otherwise, it has no effect.
Ignore two directories
xxxxxxxxxxfind . \( -path ./sk -o -path ./st \) -prune -o -name "*.txt" -print⚠️ If writing relative path must add
./To list all files of zero length.
xxxxxxxxxxfind . -emptyCount lines of code
xxxxxxxxxxfind . -name "*.c"|xargs cat|grep -v ^$|wc -l # Code line count, excluding empty lines
6. grep command
Powerful text search tool.
Grep (global search regular expression (RE) and print out the line) is a powerful text search tool that can use regular expressions to search for text and print out matching lines. Specific characters used for filtering/searching. Regular expressions can be used in conjunction with various commands, making them very flexible to use.
Similar commands include egrep, fgrep, and rgrep.
Grammar specification
xxxxxxxxxxgrep [OPTION]... PATTERNS [FILE]...grep [OPTION...] PATTERNS [FILE...]grep [OPTION...] -e PATTERNS ... [FILE...]grep [OPTION...] -f PATTERN_FILE ... [FILE...]- PATTERNS - Indicates the string or regular expression to look for.
- FILE - Indicates the FILE name to be searched. Multiple files can be searched at the same time. If the 'file' parameter is omitted, the data is read from the standard input by default.
Option description
Common options description:
-i:Ignore case for matching.-v:Reverse lookup, printing only rows that do not match.-n:Displays the line number of the matching row.-r:Find files in subdirectories recursively.-l:Only matching filenames are printed.-c:Only the number of matching lines is printed.
More Parameter Description
- -a or -- text : Do not ignore binary data.
- -A
or -- after context= : In addition to displaying the column that conforms to the template style, display the content after that row. - - b or -- byte off set : Before displaying the line that conforms to the style, indicate the number of the first character of that line.
- -B
or -- before content= : Display the content before the line, in addition to the line that matches the style. - -c or -- count: Calculate the number of columns that match the style.
- -C
or -- context= : In addition to displaying the line that conforms to the style, display the content before and after that line.or - - -d
or -- directories= : This parameter must be used when specifying that the search is for a directory rather than a file, otherwise the grep directive will report information and stop the action. - -eor -- regexp= : Specify a string as the style for finding file content.
- -E or--extended-regexp : Use regular expressions with extended styles.
- -f
或 --file= : Specify a rule file that contains one or more rule styles, allowing grep to search for file content that meets the rule criteria, in the format of one rule style per line.- -F or --fixed-regexp : Treat styles as a list of fixed strings.
- -G or --basic-regexp : Use styles as ordinary representations.
- -h or --no-filename : Do not indicate the file name to which the line belongs before displaying the line that matches the style.
- -H or --with-filename : Before displaying the line that matches the style, indicate the file name to which the line belongs.
- -i or --ignore-case : Ignore the difference in character case.
- -l or --file-with-matches : List file names whose content conforms to the specified style.
- -L or --files-without-match :List file names whose content does not conform to the specified style.
- -n or --line-number : Before displaying the row that matches the style, indicate the column number of that row.
- -o or --only-matching : Only display the matching PATTERN part.
- -q or --quiet或--silent : Do not display any information.
- -r or --recursive : The effect of this parameter is the same as specifying the '- d recurrence' parameter.
- -s or --no-messages : Do not display error messages.
- -v or --invert-match : Display all lines that do not contain matching text.
- -V or --version : Display version information.
- -w or --word-regexp : Only display columns that match the entire character.
- -x --line-regexp : Only display columns that match all columns.
- -y : The effect of this parameter is the same as specifying the '- i' parameter.
Rule expression:
xxxxxxxxxx^ # The beginning of the anchor row is: '^ grep' matches all rows starting with grep.$ # The end of the anchor line, such as' grep $', matches all lines ending in grep.. # Match a non newline character, such as' gr. p '. Match' gr 'followed by any character, then' p '.* # Match zero or more previous characters, such as' * grep '. Match all lines immediately following grep after one or more spaces..* # Use together to represent any character.[] # Match characters within a specified range, such as' [Gg] rep 'matching Grep and grep.[^] # Match a character that is not within the specified range, such as' [^ A-Z] rep. 'Match the line that does not contain the letter beginning in A-Z, immediately following rep\(..\) # Tag matching characters, such as' \ (love \) ', where' love 'is marked as 1.\< # Anchor the beginning of a word, such as' \<grep 'matching lines containing words starting with grep.\> # Anchor the end of a word, such as' grep \>'matching lines containing words ending in grep.x\{m\} # Repeat the character x, m times, for example: '0 \ {5 \}' matches a line containing 5 o.x\{m,\} # Repeat the character x at least m times, for example: 'o \ {5, \}' matches lines with at least 5 o.x\{m,n\} # Repeat the character x at least m times and no more than n times, for example: 'o \ {5,10 \}' matches 5-10 rows of o.\w # Match text and numeric characters, i.e. [A-Za-Z0-9], for example: 'G \ w * p' matches G followed by zero or more text or numeric characters, then p.\W # \The reverse form of 'w' matches one or more non word characters, such as dots, periods, etc.\b # Word lock, such as' \ grep \ b 'only matches grep.Common commands
Search for a word in a file, and the command will return a line of text containing match_mattern
xxxxxxxxxxgrep match_pattern file_namegrep "match_pattern" file_nameSearch for multiple files
xxxxxxxxxxgrep "match_pattern" file_1 file_2 file_3 ...Recursively search for lines in the folder dir that match the regular expression
patternin all files, and print the file name and line number where the matching line is located.xxxxxxxxxxgrep -r -n pattern dir/Search for the string
worldin standard input and only print the matching linesxxxxxxxxxxecho "hello world" | grep -c worldIn the current directory, search for files with the suffix
filethat contain theteststring, and print the line of the string. At this point, the following command can be used.xxxxxxxxxxgrep test *fileSearch for files that meet the criteria recursively.
For example, to search for files containing the string
updatein all files under the specified directory/etc/and its subdirectories (if subdirectories exist), and print out the content of the line containing the string, the command used is.xxxxxxxxxxgrep -r update /etcReverse search, using the
- vparameter to print out content that does not meet the criteria.To search for files containing
confin the file name but nottestin the line, the command used is.xxxxxxxxxxgrep -v test *conf*Tag matching color -- color=auto option.
xxxxxxxxxxgrep "match_pattern" file_name --color=autoUse regular expression - E option
xxxxxxxxxxgrep -E "[1-9]+"# oregrep "[1-9]+"Use regular expression - P option
xxxxxxxxxxgrep -P "(\d{3}\-){2}\d{4}" file_nameOnly output the matching parts in the file - o options.
xxxxxxxxxxecho this is a test line. | grep -o -E "[a-z]+\."line.echo this is a test line. | egrep -o "[a-z]+\."line.Count the number of lines containing matching strings in a file or text - c option.
xxxxxxxxxxgrep -c "text" file_nameSearch for records in the command line history where the
gitcommand has been entered.xxxxxxxxxxhistory | grep gitOutput the number of lines containing the matching string - n option.
xxxxxxxxxxgrep "text" -n file_name# orcat file_name | grep "text" -n#multiple filesgrep "text" -n file_1 file_2The character or byte offset at which the print style matches
xxxxxxxxxxecho gun is not unix | grep -b -o "not"#The character offset of a string in a line is calculated from the first character of the line, starting at 0. The options * * - b - o * * are usually used in conjunction.Search multiple files and find matching text in which files.
xxxxxxxxxxgrep -l "text" file1 file2 file3...7. ifconfig
Ifconfig is a command used to configure and manage network interfaces.
It allows users to view and modify the configuration of network interfaces, including IP addresses, subnet masks, MAC addresses, MTU, broadcast addresses, point-to-point addresses, etc.
Grammar explanation
xxxxxxxxxxifconfig [-a] [-v] [-s] <interface> [[<AF>] <address>][add <address>[/<prefixlen>]][del <address>[/<prefixlen>]][[-]broadcast [<address>]] [[-]pointopoint [<address>]][netmask <address>] [dstaddr <address>] [tunnel <address>][outfill <NN>] [keepalive <NN>][hw <HW> <address>] [mtu <NN>][[-]trailers] [[-]arp] [[-]allmulti][multicast] [[-]promisc][mem_start <NN>] [io_addr <NN>] [irq <NN>] [media <type>][txqueuelen <NN>][[-]dynamic][up|down] ...Option description
ifconfig:Display all configured and activated network interfaces and their status.ifconfig -a:Display all network interfaces, including those that are not activated.ifconfig <interface>:Display the configuration of the specified network interface.ifconfig <interface> up:Activate the specified network interface.ifconfig <interface> down:Disable the specified network interface.ifconfig <interface> add <address>:Add an IP address for the specified network interface.ifconfig <interface> del <address>:Remove the IP address from the specified network interface.ifconfig <interface> netmask <address>:Set the subnet mask for the specified network interface.ifconfig <interface> broadcast <address>:Set the broadcast address.ifconfig <interface> pointopoint <address>:Set point-to-point address.ifconfig <interface> hw <HW> <address>:Set MAC address.ifconfig <interface> mtu <NN>:Set MTU (Maximum Transmission Unit).ifconfig <interface> arp:Enable ARP (Address Resolution Protocol).ifconfig <interface> promisc:Enable hybrid mode to receive all packets flowing through the network interface.ifconfig <interface> multicast:Enable multicast mode.ifconfig <interface> dynamic:Enable dynamic configuration.ifconfig -s:Display network interface information in a concise format.ifconfig -v:Display detailed information.
Common commands
Common commands
xxxxxxxxxxifconfig #Active network interfaceifconfig -a #All configured network interfaces, whether activated or notifconfig eth0 #Display the network card information of eth0Activate and deactivate the designated network card
xxxxxxxxxxifconfig eth0 upifconfig eth0 downConfigure IP address
xxxxxxxxxxifconfig eth0 192.168.1.10ifconfig eth0 192.168.1.10 netmask 255.255.255.0ifconfig eth0 192.168.1.10 netmask 255.255.255.0 broadcast 192.168.1.255
8. ip
ip command is similar to the
ifconfigcommand, but more powerful than the ifconfig command. Its main function is to display or set network devices.ip command is a network configuration tool for Linux Enhanced, used to replace the ifconfig command.
Grammar explanation
xxxxxxxxxxip [ OPTIONS ] OBJECT { COMMAND | help }ip [ -force ] -batch filenameOBJECT:
xxxxxxxxxxOBJECT := { link | address | addrlabel | route | rule | neigh | ntable |tunnel | tuntap | maddress | mroute | mrule | monitor | xfrm |netns | l2tp | macsec | tcp_metrics | token }-V: Display instruction version information;-s: Output more detailed information;-f: Enforce the use of specified protocol families;-4: The designated network layer protocol used is IPv4 protocol;-6: The designated network layer protocol to be used is IPv6 protocol;-0: Output information: Each record outputs one line, even if there is a lot of content, it will not be displayed as a new line;-r: When displaying the host, do not use the IP address, but use the host's domain name.OPTIONS:
xxxxxxxxxxOPTIONS := { -V[ersion] | -s[tatistics] | -d[etails] | -r[esolve] |-h[uman-readable] | -iec |-f[amily] { inet | inet6 | ipx | dnet | bridge | link } |-4 | -6 | -I | -D | -B | -0 |-l[oops] { maximum-addr-flush-attempts } |-o[neline] | -t[imestamp] | -ts[hort] | -b[atch] [filename] |-rc[vbuf] [size] | -n[etns] name | -a[ll] }Network Objects: Specify the network objects to be managed;Specific operation: Complete specific operations on the specified network object;Help: Display help information for operation commands supported by network objects.
Common commands
xxxxxxxxxxiP link show # Display network interface informationiP link set eth0 up # Enable network cardiP link set eth0 down # Close network cardiP link set eth0 prompt on # Enable mixed mode of network cardiP link set eth0 promisc off # Disable mixed mode of network cardiP link set eth0 txqueuelen 1200 # Set network card queue lengthiP link set eth0 mtu 1400 # Set the maximum transmission unit of the network cardiP Address Show # Display Network Card IP InformationiP Address Add 192.168.0.1/24 dev eth0 # Set eth0 network card IP address 192.168.0.1iP Address del 192.168.0.1/24 dev eth0 # Delete eth0 network card IP addressiP route show # Display system routeiP route add default via 192.168.1.254 # Set system default routeiP route list # View route informationiP route add 192.168.1.0/24 via 192.168.0.254 dev eth0 # Set the gateway for the 192.168.4.0 network segment to 192.168.0.254 and use eth0 interface for dataiP route add default via 192.168.0.254 dev eth0 # Set default gateway to 192.168.0.254iP route del 192.168.1.0/24 # Delete gateway for 192.168.4.0 network segmentiP route del default # Delete default routeiP route delete 192.168.1.0/24 dev eth0 # Delete routeGot all network interfaces of the host
xxxxxxxxxxip link | grep -E '^[0-9]' | awk -F: '{print $2}'
9. mount
Mount is a command used to mount a file system.
Grammar explanation
xxxxxxxxxxmount [-l|-h|-V]mount -a [-fFnrsvw] [-t fstype] [-O optlist]mount [-fnrsvw] [-o options] device|dirmount [-fnrsvw] [-t fstype] [-o options] device dirOption description
xxxxxxxxxx-V: Display program version-h: Display auxiliary messages-v: Display more information, usually used in conjunction with - f for debugging.-a: Hang all file systems defined in/etc/fstab.-F: This command is usually used with - a, which generates a trip for each mount action to be executed. When the system needs to hang a large number of NFS file systems, the hanging process can be accelerated.-f: Usually used for debugging purposes. It will cause the mount to not perform the actual hanging action, but simulate the entire hanging process. Usually used together with - v.-n: Generally speaking, after mounting, a data entry will be written in/etc/mtab. But in the absence of a writable file system in the system, this option can be used to cancel this action.-S-r: equal to - o ro-w: Equivalent to - o rw-L: Split and hang hard drives with specific labels.-U: Hang the file system with the file partition number- L and - U are only meaningful when files such as/doc/partition exist.-t: It is usually not necessary to specify the type of file system. Mount will automatically select the correct type.-O Asynchronous: Open asynchronous mode, and all file read and write actions will be executed in asynchronous mode.-O Sync: Execute in synchronous mode.-O atime, - o noatime: When atime is opened, the system updates the 'last call time' of the file every time it is read. When we use the Flash file system, we may choose to turn off this option to reduce the number of writes.-O auto, - o noauto: Turn on/off automatic hanging mode.-O defaults: Use the preset option rw, suid, dev, exec, auto, nouser, and async.-O dev, - o nodev-o exec, - o noexec allow executable files to be executed.-O suid, - o nosuid: Allow executable files to be executed with root privileges.-O user, - o nouser: Users can perform mount/mount actions.-O remount: reattach an already suspended file system in a different way. For example, a system that was originally read-only is now being re installed in read-write mode.-O ro: Hang up in read-only mode.-RW: Hang it in read-write mode.-O loop=: Use loop mode to split a file as a hard drive and hang it on the system.Common commands
Hang/dev/hda1 under/mnt
xxxxxxxxxxmount /dev/hda1 /mntHang/dev/hda1 in read-only mode under/mnt
xxxxxxxxxxmount -o ro /dev/hda1 /mntRe mount/root directory in read-write mode
xxxxxxxxxxmount -o remount,rw /Mount NFS network file system
xxxxxxxxxxmount -t nfs -o nolock 192.168.1.20:/home/ /tmp/nfs
10. netstat
Netstat command is used to print the status information of the network system in Linux, which allows you to know the network situation of the entire system.
Grammar explanation
xxxxxxxxxxnetstat [-vWeenNcCF] [<Af>] -rnetstat {-V|--version|-h|--help}netstat [-vWnNcaeol] [<Socket> ...]netstat { [-vWeenNac] -i | [-cnNe] -M | -s [-6tuw] }Option description
-A:List the relevant addresses in the network type connections.-r, --route:Display routing table, listing the routing information of the system.-i, --interfaces:Display network interface information, including interface name, IP address, and other related information.-g, --groups:Display multicast group member information, including which network group members are in the multicast group.-s, --statistics:Display network statistics information, similar to SNMP (Simple Network Management Protocol), providing detailed statistics on network activity.-M, --masquerade:Display masquerade connection information, typically used in Network Address Translation (NAT) networks.-v, --verbose:Display detailed information and provide more information to help diagnose network issues.-W, --wide:Do not truncate the IP address to display complete IP address information.-n, --numeric:Do not parse host or port names to display numeric IP addresses, port numbers, and user information.--numeric-hosts:Do not resolve the host name.--numeric-ports:Do not resolve port names.--numeric-users:Do not resolve user names.-N, --symbolic:Resolve hardware names and display the symbolic names of hardware devices.-e, --extend:Display additional information. Use this option twice to obtain the maximum detailed information.-p, --programs:Display PID (Process Identifier) and program name to display process information related to sockets.-o, --timers:Display timer information, including the timer status of the socket.-c, --continuous:Make 'Netstat' continuously print the selected information once per second for continuous monitoring.-l, --listening:Only display server sockets that are currently listening.-a, --all:Display all sockets, including connected and unconnected ones.-F, --fib:Display Forwarding Information Table (FIB).-C, --cache:Display routing cache instead of forwarding information table.-Z, --context:Display SELLinux security context, used to display SELLinux security information for sockets.-v, --verbose:Enable detailed output to provide users with more information about the ongoing operation. Especially when dealing with unconfigured address families, provide some useful information.-o, --timers:Including information related to network timers.-p, --program:Display the PID and name of the program to which each socket belongs.-l, --listening:Only display sockets that are currently listening. By default, these are omitted.-a, --all:Display listening and non listening sockets. When using the-- interfacesoption, display inactive interfaces.-F:Print routing information from FIB (default).-C:Print routing information from the routing cache.
Common commands
Display detailed network status
xxxxxxxxxxnetstat -a # List all portsnetstat at # List all TCP portsnetstat au # List all UDP portsDisplay the current UDP connection status of registered residence
xxxxxxxxxxnetstat -nuDisplay the usage of UDP port numbers
xxxxxxxxxxnetstat -apuDisplay network card list
xxxxxxxxxxnetstat -iDisplay the relationship of multicast groups
xxxxxxxxxxnetstat -gDisplay network statistics information
xxxxxxxxxxnetstat -s Display statistical information for all portsnetstat -st Display statistical information of TCP portsnetstat -su Display statistical information of UDP portsDisplay the listening socket
xxxxxxxxxxnetstat -l #only displays listening portsnetstat -lt #only lists all listening TCP portsnetstat -lu #only lists all UDP listening portsnetstat -lx #only lists all listening UNIX portsDisplay PID and process name in Netstat output
xxxxxxxxxxnetstat -ptNetstat - pcan be used with other switches to add' PID/process name 'to the output of Netstat.Continuously output Netstat information.
xxxxxxxxxxnetstat -c #Output network information every secondDisplay core routing information.
xxxxxxxxxxnetstat -rUse
netstat - rnto display numerical format without querying the host name.Identify the port where the program is running.
Not all processes can be found, and those without permissions will not be displayed. Use root privileges to view all information.
xxxxxxxxxxnetstat -ap | grep sshFind the process running on the specified port
xxxxxxxxxxnetstat -an | grep ':80'Find process ID through port
xxxxxxxxxxnetstat -anp|grep 8081 | grep LISTEN|awk '{printf $7}'|cut -d/ -f1
11. nohup
Nohup also known as' no hang up 'in English, is used to run commands in the system background without hanging up. Exiting the terminal will not affect the program's operation.
By default (when not redirected), a file named nohup.out will be output to the current directory. If the nohup.out file in the current directory is not writable, redirect the output to the '$HOME/nohop. out' file. If there is no file to create or open for append, the command specified by the command parameter cannot be called. If the standard error is a terminal, then writing the specified command to all outputs of the standard error as standard output redirects to the same file descriptor.
Grammar explanation
xxxxxxxxxxnohup COMMAND [ARG]... [ & ]nohup OPTIONCommand: The command to be executed.
ARG: Some parameters that can specify the output file.
&Make the command execute in the background, and the command will still execute after the terminal exits
Option description
--help:Display help information.--version:Display version information.
Common commands
The following command executes the runoob.sh script in the root directory in the background
xxxxxxxxxxnohup /root/runoob.sh &If you want to stop running, you need to use the following command to find nohup, run the script to PID, and then use the kill command to delete it
xxxxxxxxxxps -aux | grep "runoob.sh"The following command executes the runoob.sh script in the root directory in the background and redirects the input to the runoob.log file.
xxxxxxxxxxnohup /root/runoob.sh > runoob.log 2>&1 &2>&1 Explanation.
Redirects standard error 2 to standard output&1, which is then redirected as input to the runoob.log file.
- 0 – stdin (standard input)
- 1 – stdout (standard output)
- 2 – stderr (standard error output)
12. ps
ps command is used to display the current process status of the system.
The ps command is the most basic and powerful process viewing command, which can be used to determine which processes are running and their running status, whether the processes have ended, whether the processes have died, which processes are consuming too many resources, and so on.
Grammar explanation
xxxxxxxxxxps [options]Option description
Basic options:
-A, -e: Including all processes.-a: Includes all processes with terminals (tty), but does not include session leaders.a: Including all processes with terminals (tty), including processes of other users.-d: Including all processes except for the conversation leader.-N, --deselect: Deselect (reselect) the process.r: Only display running processes.T: Display all processes related to the current terminal.x: Display processes that do not control the terminal.
Selection by list:
-C <command>: Select the process based on the command name.-G, --Group <GID>: Select a process based on the real group ID or group name.-g, --group <group>: Select a process based on the session or valid group name.-p, p, --pid <PID>: Select a process based on its process ID.--ppid <PID>: Select a process based on the parent process ID.-q, q, --quick-pid <PID>: In fast mode, select a process based on its ID.-s, --sid <session>: Select the process based on the session ID.-t, t, --tty <tty>: Select the process based on the terminal.-u, U, --user <UID>: Select a process based on a valid user ID or username.-U, --User <UID>: Select a process based on the real user ID or username.
Output formats:
-F: Display additional detailed information.-f: Complete format, including command line.f, --forest: Display the process tree in ASCII art format.-H: Displays the process hierarchy.-j: Job format.j: BSD job control format.-l: Long format.l: BSD Long format.-M, Z: Add security data (for SELinux).-O <format>: Preload with default columns.O <format>: Preload columns in BSD style.-o, o, --format <format>: User-defined format.s: signal format.u: User-oriented format.v: Virtual memory format.X: Register format.-y: Instead of flags, RSS and address (used with -l) are displayed.--context: Displays the security context (for SELinux).--headers: Repeat the header line on each page.--no-headers: Do not print the title at all.--cols, --columns, --width <num>: Set the screen width.--rows, --lines <num>: Set the screen height.
Show threads:
H: Show threads as if they were processes.-L: This may include LWP and NLWP columns.-m, m: Displays threads after the process.-T: This may include SPID columns.
Miscellaneous options:
-c: Displays scheduling categories under the -l option.c: The real command name is displayed.e: Displays the environment after the command.k, --sort: Specify the sorting order, for example,[+|-]key[, [+|-]key[,...]].L: Displays a format specifier.n: Display the digital user ID and wchan.S, --cumulative: Includes some terminated child process data.-y: Instead of flags, RSS is displayed (used only with -l).-V, V, --version: Displays the version information and exits.-w, w: Unlimited output width.
Help options:
--help <simple|list|output|threads|misc|all>: Show help and exit. Different help modes can be selected.
Common commands
List the PID and related information that currently belongs to you for this login.
xxxxxxxxxxsunrise@ubuntu:~$ ps -lF S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD4 S 1000 4295 4294 8 80 0 - 3304 do_wai pts/0 00:00:00 bash0 R 1000 4304 4295 0 80 0 - 3504 - pts/0 00:00:00 psF:flag for this program, 4 means the user is super userS:Represents the status (STAT) of the program. The meaning of each STAT is described in this articleS:The process is running(Sleeping)R:The process is running or preparing to run(Running)D:Process uninterruptible(Uninterruptible Sleep)T:The process has stopped(Stopped)Z:zombie process(Zombie)t:The process is tracked or stopped(Traced or stopped)P:The process is tracked or stopped, but is waiting(Parked)
UID:User ID of the process, indicating the user who runs the process.PID:The process ID is a unique identifier assigned by the operating system to each process.PPID:Parent Process ID: indicates the ID of the parent process that starts the current process.C:CPU Usage percentage Indicates the percentage of CPU time occupied by a process.PRI:The priority of the process.NI:The nice value of a process, usually used to adjust the priority of a process.ADDR:The address space of the process. This is the kernel function, which indicates what part of memory the program is in. If it's a running program, it's usually "-".SZ:The virtual memory size of the process in pages.WCHAN:The event or lock that the process is currently waiting for. If -, the system is runningTTY:The terminal (if any) associated with the process.TIME:The CPU time the process has been running.CMD:The command line of the process.
Lists all programs currently in memory
xxxxxxxxxxsunrise@ubuntu:~$ ps auxUSER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDroot 1 0.4 0.4 167592 10076 ? Ss 10:16 0:02 /sbin/initroot 2 0.0 0.0 0 0 ? S 10:16 0:00 [kthreadd]root 4 0.0 0.0 0 0 ? I< 10:16 0:00 [kworker/0:0H]root 5 0.0 0.0 0 0 ? I 10:16 0:00 [kworker/u8:0]USER:Indicates the user that owns the process, that is, the user that runs the process.PID:Represents a process ID. It is a unique identifier that identifies each process.%CPU:Indicates the CPU usage of a process, that is, the percentage of the CPU time used by a process to the total CPU time.%MEM:Indicates the memory usage of a process, that is, the percentage of the physical memory used by a process in the total physical memory.VSZ:Represents the Virtual Set Size of the process, that is, the size of the virtual memory that the process can access, usually in kilobytes (KB).RSS:Indicates the Resident Set Size of the physical memory currently occupied by the process, usually in kilobytes (KB).TTY:Indicates the terminal associated with the process. If the process is not associated with a terminal,? .STAT:Indicates the state of the process, usually including the following states.R:RunningS:SleepingD:Uninterruptible SleepZ:ZombieT:Stopped- Other states may also exist, and their specific meanings may vary depending on the operating system.
START:Indicates the start time of a process, usually expressed in hours: minutes format.TIME:Indicates the CPU time that a process has used, usually in the format of hours: minutes: seconds.COMMAND:Indicates the command line of a process, that is, the commands and parameters executed by the process.
Lists a program display similar to the program tree.
xxxxxxxxxxsunrise@ubuntu:~$ ps -axjfPPID PID PGID SID TTY TPGID STAT UID TIME COMMAND1 2973 2973 2973 ? -1 Ss 0 0:00 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups2973 4067 4067 4067 ? -1 Ss 0 0:00 \_ sshd: root@pts/04067 4239 4239 4239 pts/0 4364 Ss 0 0:00 | \_ -bash4239 4294 4294 4239 pts/0 4364 S 0 0:00 | \_ su sunrise4294 4295 4295 4239 pts/0 4364 S 1000 0:00 | \_ bash4295 4364 4364 4239 pts/0 4364 R+ 1000 0:00 | \_ ps -axjf2973 4069 4069 4069 ? -1 Ss 0 0:00 \_ sshd: root@notty4069 4242 4242 4242 ? -1 Ss 0 0:00 \_ /usr/lib/openssh/sftp-serverOther commands
xxxxxxxxxxps axo pid,comm,pcpu #View the PID, name, and CPU usage of a processps aux | sort -rank 4 #Sort processes by memory resource usageps aux | sort -nk 3 #Sort processes by CPU resource usageps -A #Display all process informationps -u root #Display specified user informationps efL #View thread countps -e -o "% C:% p:% z:% a" | sort - k5- nr #View processes and arrange them by memory usage sizeps -ef #Display all process information along with the command lineps -ef | grep ssh #Common combination of ps and grep to find specific processesps -C nginx #Search for processes by name or commandps aux --sort=- pcpu,+pmem #sort by CPU or memory, - descending,+ascendingps -f --forest - C nginx #Display the hierarchical relationship of processes in a tree styleps -o PID, Uname, Comm-C nginx #Display child processes of a parent processps -e -o pid, uname=USERNAME, pcpu=CPU-USAGE, pmem, comm #Redefine tagsps -e -o pid, comm, etime #Display the running time of the processps -aux | grep named #View detailed information of named processesps -o command -p 91730 | sed -n 2p #Obtain service name through process id13. route
Using the route command, you can display and set the network routing table in the Linux kernel. The route command mainly sets static routes. To achieve communication between two different subnets, you need a router that connects two networks, or a gateway that is located in both networks.
Routing is usually set up in Linux systems to solve the following problems:
The Linux system is on a local area network (LAN), and there is a gateway in the LAN that allows the machine to access the Internet. Therefore, you need to set the ip address of the machine as the default route for the Linux machine. Note that you can run the route command on the CLI to add a route. The route is not saved permanently. After the network adapter restarts or the machine restarts, the route becomes invalid. You can add the route command to '/etc/rc.local' to ensure that this routing setting is permanent.
Grammar explanation
xxxxxxxxxxroute [-nNvee] [-FC] [<AF>] List kernel routing tablesroute [-v] [-FC] {add|del|flush} ... Modify routing table for AF.-A:Set the address type.-v, --verbose:The details are displayed.-n, --numeric:The DNS reverse lookup is not performed, and the IP address is displayed in numeric form.-e, --extend:The routing table is displayed in netstat format.-F, --fib:Displays the forwarding information base (default).-C, --cache:Display a routing cache, not a forwarding repository.-net:A routing table to a network.-host:Routing table to a host.
Option description
add:This command is used to add a route record to route the specified destination network or destination host to the specified network interface.del:This command is used to delete a specified route record.target:Specify the destination network or destination host.gw:This parameter is used to set the default gateway.mss:Set the maximum block length (MSS) of TCP.window:Specifies the TCP window size for TCP connections that pass through the routing table.dev:Specifies the network interface represented by the routing record.
Common commands
Show current route
xxxxxxxxxxroot@ubuntu:~# routeKernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Ifacedefault 192.168.0.1 0.0.0.0 UG 600 0 0 wlan0default 192.168.1.1 0.0.0.0 UG 700 0 0 eth0192.168.0.0 0.0.0.0 255.255.255.0 U 600 0 0 wlan0192.168.1.0 0.0.0.0 255.255.255.0 U 700 0 0 eth0root@ubuntu:~# route -nKernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface0.0.0.0 192.168.0.1 0.0.0.0 UG 600 0 0 wlan00.0.0.0 192.168.1.1 0.0.0.0 UG 700 0 0 eth0192.168.0.0 0.0.0.0 255.255.255.0 U 600 0 0 wlan0192.168.1.0 0.0.0.0 255.255.255.0 U 700 0 0 eth0Flags indicates the route flag that indicates the status of the current network node.
Flags can be described as follows.
U: Up Indicates that the current status of the route is enabled.H: Host, indicates that the gateway is a host.G:Gateway, indicates that the gateway is a router.R:Reinstate Route,Routes that are re-initialized using dynamic routes.D: Dynamically, this route is written dynamically.M: Modified,This route is dynamically modified by routing daemons or guides.!: Indicates that the route is currently closed.
Add a gateway/Set a gateway
xxxxxxxxxxroute add -net 192.168.2.0 netmask 255.255.255.0 dev eth0Mask a route
xxxxxxxxxxroute add -net 192.168.2.0 netmask 255.255.255.0 rejectDeleting a route record
xxxxxxxxxxroute del -net 192.168.2.0 netmask 255.255.255.0route del -net 192.168.2.0 netmask 255.255.255.0 rejectDelete and add default gateway settings
xxxxxxxxxxroute del default gw 192.168.2.1route add default gw 192.168.2.1
14. rsync
Rsync is a fast and powerful file copy tool. It can copy files locally, from another host via any remote shell, and with the remote rsync daemon. It provides a large number of options to control aspects of its behavior and allows for great flexibility in specifying the collection of files to be copied. Rsync is known for its incremental transfer algorithm, which reduces the amount of data sent over the network by sending only the difference between the source file and the existing file in the destination. Rsync is widely used for backup and mirroring operations, but also as an improved copy command for daily use.
Rsync finds files to transfer using the default "Quick Check" algorithm, which looks for files that have changed in size or when they were last modified. When a quick check shows that the file's data does not need to be updated, any changes to other reserved properties on the destination file (as requested by the option) are applied directly to the destination file.
Grammar explanation
xxxxxxxxxxUsage: rsync [OPTION]... SRC [SRC]... DESTor rsync [OPTION]... SRC [SRC]... [USER@]HOST:DESTor rsync [OPTION]... SRC [SRC]... [USER@]HOST::DESTor rsync [OPTION]... SRC [SRC]... rsync://[USER@]HOST[:PORT]/DESTor rsync [OPTION]... [USER@]HOST:SRC [DEST]or rsync [OPTION]... [USER@]HOST::SRC [DEST]or rsync [OPTION]... rsync://[USER@]HOST[:PORT]/SRC [DEST]The ':' usages connect via remote shell, while '::' & 'rsync://' usages connectto an rsync daemon, and require SRC or DEST to start with a module name.Simple writing
xxxxxxxxxxrsync [OPTION...] SRC... [DEST]Option description
-v, --verbose:Add detailed information output
- --info=FLAGS:Specifies the flag for detail output
- --debug=FLAGS:Specifies the flag for debugging details output
- --msgs2stderr:Special handling for debugging output
-q, --quiet:Suppress the output of non-error messages
- --no-motd:Suppress MOTD in daemon mode (see man page Notes)
-c, --checksum:Skip based on checksum instead of modification time and file size
-a, --archive:Archive mode; Equivalent to -rlptgoD (excluding -H, -A, -X)
- --no-OPTION:Turn off the implied OPTION (for example, --no-D)
-r, --recursive:Process directories recursively
-R, --relative:Use relative pathnames
- --no-implied-dirs:The implied directory is not sent with --relative
-b, --backup:Create backup files (see --suffix and --backup-dir)
- --backup-dir=DIR:Put backup files into a DIR based hierarchy
- --suffix=SUFFIX:Set the suffix of the backup file (default is ~, if not --backup-dir)
-u, --update:Skip updated files on the receiving end
- --inplace:Update the target file in place (see man page)
- --append: Attach data to a shorter file
- --append-verify:Similar to -- append, but the attached file has a file checksum of old data
-d, --dirs:Transfer directories without recursion
-l, --links:Copy symbolic link as symbolic link
-L, --copy-links:Convert symbolic links to the specified file/directory
- --copy-unsafe-links:Only convert 'unsafe' symbolic links
- --safe-links:Ignore symbolic links pointing outside the source tree
- --munge-links:Confuse symbolic links to make them safer (but not usable)
-k, --copy-dirlinks:Convert the symbolic link of the target directory to the specified directory
-K, --keep-dirlinks:Consider the symbol link directory on the receiving end as a directory
-H, --hard-links:Keep hard links
-p, --perms:Preserve permissions
-E, --executability:Preserving the executability of files
- --chmod=CHMOD:Affects the permissions of files and/or directories
-A, --acls:Keep ACL (implicit -- perms)
-X, --xattrs:Retain extended attributes
-o, --owner:Retain Owner (Super User Only)
-g, --group:Reserve group
- --devices:Keep device files (for super users only)
- --copy-devices:Copy device content as a regular file
- --specials:Keep special files
-D:Equivalent to--devices --specials
-t, --times:Reserve modification time
-O, --omit-dir-times:Omit the directory from -- times
-J, --omit-link-times: Omit symbolic links from -- times
- --super:Receiver attempts super user activity
- --fake-super:Use Xattrs to store/restore privileged attributes
-S, --sparse:Convert continuous empty blocks into sparse blocks
- --preallocate:Allocate target file before writing to file
-n, --dry-run:Perform a trial run without making any actual changes
-W, --whole-file:Whole file transfer (without using incremental transfer algorithm)
- --checksum-choice=STR:Select checksum algorithm
-x, --one-file-system:Not crossing file system boundaries
-B, --block-size=SIZE:Enforce a fixed parity block size
-e, --rsh=COMMAND: Specify the remote shell to use
- --rsync-path=PROGRAM:Specify rsync to run on the remote machine
- --existing:Skip creating a new file on the receiving end
- --ignore-existing:Skips updates to files that already exist on the receiving end
- --remove-source-files:Delete a synchronized file (not a directory) on the sending end
- --del:--delete-during
- --delete:Remove excess files from the target directory
- --delete-before:Deleted at the receiving end during transmission
- --delete-during:Deleted at the receiving end during transmission
- --delete-delay:Delete only after finding the delete operation
- --delete-after:Delete at the receiving end after transmission
- --delete-excluded:Also deletes excluded files from the target directory
- --ignore-missing-args:Missing source parameters are ignored without error
- --delete-missing-args:Removes missing source parameters from the target
- --ignore-errors:Delete even if I/O errors occur
- --force:Forcibly delete a directory even if it is not empty
- --max-delete=NUM:A maximum of NUM files can be deleted
- --max-size=SIZE: Do not transfer files larger than SIZE
- --min-size=SIZE:Do not transfer files smaller than SIZE
- --partial:Retain some of the transferred files
- --partial-dir=DIR:Place some of the transferred files into DIR
- --delay-updates:Place all updated files in the specified location at the end of the transfer
-m, --prune-empty-dirs:Cut an empty directory chain from the file list
- --numeric-ids:The uid/gid value is not mapped by the user name or group name
- --usermap=STRING:User-defined user name mapping
- --groupmap=STRING:User-defined group name mapping
- --chown=USER:GROUP:Simple username/group name mapping
- --timeout=SECONDS:Setting the I/O timeout period in seconds
- --contimeout=SECONDS:Set timeout for daemon connections in seconds
-I, --ignore-times:Files that match the size and modification time are not skipped
-M, --remote-option=OPTION:Send options only to the remote end
- --size-only:Skip files that match the size
@, --modify-window=NUM:Set the precision of the change time comparison
-T, --temp-dir=DIR:Create temporary files in the directory DIR
-y, --fuzzy:Find similar files as a benchmark when there is no target file
- --compare-dest=DIR:The object file is also compared to DIR
- --copy-dest=DIR:And includes a copy of the unchanged file
- --link-dest=DIR:Hardlink the file into DIR when unchanged
-z, --compress:Compress file data during transfer
- --compress-level=NUM:Clearly set the compression level
- --skip-compress=LIST:Skip compression of files with the LIST suffix
-C, --cvs-exclude:Automatically ignores files that are identical to CVS
-f, --filter=RULE:Add a file filtering rule
-F:与 --filter='dir-merge /.rsync-filter' same
- --exclude=PATTERN:Exclude files that match PATTERN
- --exclude-from=FILE:Read exclusion mode from FILE
- --include=PATTERN:Files that match PATTERN are not excluded
- --include-from=FILE:Read the contain pattern from FILE
- --files-from=FILE:Reads a list of source filenames from FILE
-0, --from0: All *-from/filter files are separated by 0
-s, --protect-args:Spaces are not split, only special wildcard characters are split
- --trust-sender:A list of files trusted by the remote sender
- --address=ADDRESS:Bind the outgoing socket to the address of the daemon
- --port=PORT:Specifies the alternate port number with a double colon
- --sockopts=OPTIONS:Specify custom TCP options
- --blocking-io:Use blocking I/O for remote shell operations
- --stats:Provides some file transfer statistics
-8, --8-bit-output: Retain high level characters in the output
-h, --human-readable:Output numbers in a human-readable format
- --progress:Displays progress during transfer
-P:and --partial --progress same
-i, --itemize-changes:Output a summary of all updated changes
- --out-format=FORMAT:Output updates in the specified format
- --log-file=FILE:Logs the operation to the specified file
- --log-file-format=FMT:Updates with the specified FMT record
- --password-file=FILE:Read the daemon access password from the file
- --list-only:List only the files, do not copy them
- --bwlimit=RATE:Limit socket I/O bandwidth
- --stop-at=y-m-dTh:m:Stop rsync at Thour:minute on year-month-day
- --time-limit=MINS:Stop rsync after MINS
- --outbuf=N|L|B:Sets the output buffer to none, line, or block
- --write-batch=FILE:Writes batch updates to a file
- --only-write-batch=FILE:It is similar to --write-batch, but does not update the target
- --read-batch=FILE:Read batch updates from a file
- --protocol=NUM:Enforce the old protocol version
- --iconv=CONVERT_SPEC:Request character set conversion of file name
- --checksum-seed=NUM:Set block/file checksum and seed (advanced option)
- --noatime:Does not change atime when the source file is opened
-4, --ipv4:Preferred IPv4
-6, --ipv6:Preferred IPv6
- --version:Display version number
(-h) --help:Display help information (only when -h is used alone --help)
Common commands
- Copy local files from the /app directory to the /userdata directory
xxxxxxxxxxrsync -avSH /app/ /userdata/- Copy the contents of the local machine to the remote machine
xxxxxxxxxxrsync -av /app 192.168.1.12:/app- Copy the contents of the remote machine to the local machine
xxxxxxxxxxrsync -av 192.168.1.12:/app /app- Copy files from the remote rsync server (running rsync as a daemon) to the local machine.
xxxxxxxxxxrsync -av root@192.168.1.12::www /userdata- Copy the local machine files to the remote rsync server (run rsync in daemon mode). This mode is enabled when the DST path information contains :: delimiters.
xxxxxxxxxxrsync -av /userdata root@192.168.1.12::www- Displays the file list for the remote machine. This is similar to the rsync transfer, but simply omit the local machine information from the command.
xxxxxxxxxxrsync -v rsync://192.168.1.12/app- Specify the password to save the file, and perform rsync transfer without entering the password
xxxxxxxxxxrsync -rvzP --password-file=/etc/rsync.password rsync@$192.168.1.12::app/ /app
15. scp
The Linux scp command is used to copy files and directories between Linux operating systems.
scp is an abbreviation of secure copy. scp is a secure remote file copy command based on ssh login in linux.
SCP is encrypted, RCP is not encrypted, SCP is the strengthening of the RCP version.
Grammar explanation
xxxxxxxxxxscp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file][-J destination] [-l limit] [-o ssh_option] [-P port][-S program] source ... targetSimple writing
xxxxxxxxxxscp [option] file_source file_target- file_source:Specify the source file to copy.
- file_target: The object file. The format is "user@host: filename" (filename is the name of the destination file)
Option description
- -3: Transfer files between two remote hosts through the local host. If this option is not used, data will be transmitted directly between two remote hosts. Please note that this option will disable the display of transmission progress.
- -4: Force SCP command to only use IPv4 addressing
- -6: Force SCP command to only use IPv6 addressing
- -B: Select batch processing mode (prevent asking for passwords or password phrases)
- -C: Allow compression. (Pass the - C flag to ssh to enable compression function)
- -p: Retain the modification time, access time, and access permissions of the original file.
- -q: Silent mode: Disable progress charts and warning and diagnostic messages from ssh (1).
- -r: recursively copies the entire directory. Please note that SCP will follow the symbolic links encountered during tree traversal.
- -T: Disable strict file name checking. By default, when copying files from a remote host to a local directory, SCP checks if the received file name matches the file name requested on the command line to prevent the remote end from sending unexpected or unwanted files. Due to the different ways in which file name wildcard characters are interpreted by different operating systems and shells, these checks may result in the rejection of desired files. This option disables these checks, but requires full trust that the server will not send unexpected file names.
- -v: Detailed mode. Causing SCP and SSH (1) to print debugging messages about their progress. This is very helpful when debugging connection, authentication, and configuration issues.
- -c cipher: Select the password used for encrypting data transmission. This option is passed directly to SSH (1).
- -F ssh_config: Specify an alternative per user configuration file for ssh. This option is passed directly to SSH (1).
- -- i identity file: Select the identity (private key) file used for public key authentication. This option is passed directly to SSH (1).
- -l limit: Limit the bandwidth usage in Kbit/s.
- -o ssh3 option: can be used to pass options to SSH in the format used in ssh3 config (5). This is very useful for specifying options without a separate scp command-line flag.
- -P port: Specify the port to connect to the remote host. Please note that this option uses uppercase 'P' because lowercase '- p' has been reserved to preserve the modification time and mode of the file.
- -S program: The name of the program used to encrypt connections. The program must understand the ssh (1) option.
Common commands
Copy from local to remote
Command format:
xxxxxxxxxxscp local_file remote_username@remote_ip:remote_folderorscp local_file remote_username@remote_ip:remote_fileorscp local_file remote_ip:remote_folderorscp local_file remote_ip:remote_file- The first and second ones specify the username, and after the command is executed, the password needs to be entered again. The first one only specifies the remote directory, and the file name remains unchanged. The second one specifies the file name;
- The third and fourth options do not specify a username, and after executing the command, a username and password are required. The third option only specifies a remote directory with the same file name, while the fourth option specifies a file name;
Application examples:
xxxxxxxxxxscp /home/sunrise/test.c root@192.168.1.10:/userdatascp /home/sunrise/test.c root@192.168.1.10:/userdata/test_01.cscp /home/sunrise/test.c 192.168.1.10:/userdatascp /home/sunrise/test.c 192.168.1.10:/userdata/test_01.cCopy directory command format:
xxxxxxxxxxscp -r local_folder remote_username@remote_ip:remote_folderorscp -r local_folder remote_ip:remote_folderThe first one specifies a username, and after the command is executed, a password needs to be entered;
The second one does not specify a username, and after executing the command, a username and password need to be entered;
Application examples:
xxxxxxxxxxscp -r /home/sunrise/app/ root@192.168.1.10:/userdata/app/scp -r /home/sunrise/app/ 192.168.1.10:/userdata/app/The above command copies the local
appdirectory to the remote/userdata/app/directory.Copy from remote to local
The scp command copied from remote to local is the same as the above command, just swap the order of the last two parameters of the command copied from local to remote.
Copy files from remote machine to local directory.
xxxxxxxxxxscp sunrise@192.168.1.10:/userdata/log.log /home/sunrise/Download the
log. logfile from the/userdata/directory on the 192.168.1.10 machine to the local/home/startup/directory.
16. ssh
ssh command is a client connection tool in the open ssh suite that can provide SSH encryption protocol for secure remote server login.
Grammar explanation
xxxxxxxxxxssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface][-b bind_address] [-c cipher_spec] [-D [bind_address:]port][-E log_file] [-e escape_char] [-F configfile] [-I pkcs11][-i identity_file] [-J [user@]host[:port]] [-L address][-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port][-Q query_option] [-R address] [-S ctl_path] [-W host:port][-w local_tun[:remote_tun]] destination [command]- destination:Specify the remote ssh server to connect to;
- command:Instructions to execute on the remote ssh server.
Option description
-4:Enforce the use of IPv4 addresses.-6:Enforce the use of IPv6 addresses.-A:Enable authentication proxy connection forwarding function.-a:Disable the authentication proxy connection forwarding function.-B:Bind to the address of bind_interface before attempting to connect to the target host. This is very useful on systems with multiple addresses.-b:Use the locally specified address as the source IP address for the corresponding connection.-C:Request compression of all data.-F:Specifies the configuration file for the SSH directive.-f:Execute SSH commands in the background.-g:Allows a remote host to connect to the host's forwarding port.-i:Specify the identity (private key) file.-l:Specifies the login user name to connect to the remote server.-N:Do not execute remote instructions.-o:Specify configuration options.-p:Specify the port on the remote server.-q:Silent mode.-X:Enable the X11 forwarding function.-x:Disable the X11 forwarding function.-y:Enable the trusted X11 forwarding function.
Common commands
xxxxxxxxxx#SSH username @ remote server addressssh sunrise@192.168.1.10#Specify portssh -p 2211 sunrise@192.168.1.10#SSH familyssh -p 22 user@ip #The default username is the current username, and the default port is 22Ssh keygen # Generate ssh public and private keys for the current userssh-keygen -f keyfile -i -m key_format -e -m key_format # key_format: RFC4716/SSH2(default) PKCS8 PEMssh-copy-id user@ip : port # Copy the current user's public key to~/. ssh/authorized_keys on the server that requires SSH, and then log in without passwordConnect to a remote server
xxxxxxxxxxssh username@remote_hostConnect to a remote server and specify the port
xxxxxxxxxxssh -p port username@remote_hostConnect to a remote server using a key file
xxxxxxxxxxssh -i path/to/private_key username@remote_hostExecute remote commands locally
xxxxxxxxxxssh username@remote_host "command"Forward on local port to remote server
xxxxxxxxxxssh -L local_port:remote_host:remote_port username@remote_hostForward from remote server port to local
xxxxxxxxxxssh -R remote_port:local_host:local_port username@remote_host
17. tar
tar command can create files and directories for Linux. Using tar, you can create a file (backup file) for a specific file, change the file in the file, or add a new file to the file. Tar was originally used to create files on magnetic tape, but now users can create files on any device. By using the tar command, a large number of files and directories can be packaged into one file, which is very useful for backing up files or combining several files into one file for network transmission.
Firstly, it is necessary to clarify two concepts: packaging and compression. Packaging refers to turning a large number of files or directories into a single file; Compression is the process of transforming a large file into a small file using various compression algorithms.
Why distinguish between these two concepts? This is due to the fact that many compression programs in Linux can only compress one file. Therefore, when you want to compress a large number of files, you first need to pack them into a package (tar command), and then use a compression program to compress them (gzip bzip2 command).
Grammar explanation
xxxxxxxxxxtar [OPTION...] [FILE]...Option description
xxxxxxxxxx-A, --catenate, --concatenate Add tar file to archive-c, --create Create a new archive-d, --diff, --compare Identify differences between the archive and file systems--delete From archive (non-tape!) Delete from-r, --append Append files to the end of the archive-t, --list List archive content--test-label Test the archive label and exit-u, --update Append only files that are newer than the copy in the archive-x, --extract, --get Extract the file from the archiveOperation modifier:--check-device Checking device numbers when creating incremental archives (default)-g, --listed-incremental=FILE Handle incremental backups in the new GNU format-G, --incremental Handle incremental backups in the old GNU format--ignore-failed-readDo not exit with a non-zero value when encountering an unreadable file--level=NUMBER The output level of the incremental list archive that was created-n, --seek Archival retrievability--no-check-device Do not check the device number when creating an incremental archive--no-seek Unsearchable file--occurrence[=NUMBER] Only process the NUMBER of each file in the archiveAn event; Only when combined with the following sub command - delete,--Diff, -- extract or -- listThis option is only effective when used in conjunction with one of the options. And regardless of whether the file list is provided in command-line form or through-T Optionally specified; The default value of NUMBER is 1--sparse-version=MAJOR[.MINOR]Set the discrete format version used (implied--sparse)-S, --sparse efficiently handles discrete filesOverride control:-k, --keep-old-files don't replace existing files when extracting,treat them as errors--keep-directory-symlink preserve existing symlinks to directories whenextracting--keep-newer-filesDo not replace existing files that are newer than the copy in the archive--no-overwrite-dir Retain metadata of existing directories--overwrite Overwrite existing files when unzipping--overwrite-dir Overwrite metadata of existing directories when unzipping (default)--recursive-unlink Clear the directory hierarchy before decompressing the directory--remove-files Delete files after adding them to the archive--skip-old-files don't replace existing files when extracting,silently skip over them-U, --unlink-first Delete the files you want to rewrite before unzipping them-W, --verify Try to validate the archive after writingSelect the output stream:--ignore-command-error Ignore the child process's exit code--no-ignore-command-errorTreat the nonzero exit code of the child process as an error-O, --to-stdout Extract the file to standard output--to-command=COMMANDPipe the extracted file to another programOperation file properties:--atime-preserve[=METHOD]Reserve access time on the output file, either by reading (defaultMETHOD= 'replace') restores the time, or do not set the time the first time (METHOD= 'system')--delay-directory-restoreDo not set the change time and permissions for the directory to be unzipped until the decompression is complete--group=名称 Enforces NAME as the group owner of the added file--mode=CHANGES Force the added file (symbol) to change to permission CHANGES--mtime=DATE-OR-FILE Set mtime for the added file from DATE-OR-FILE-m, --touch Do not unzip the file's modification time--no-delay-directory-restoreUneffect the --delay-directory-restore option--no-same-ownerUnzip the file to all you have (default for normal users)--no-same-permissionsUse the user's mask bit when extracting permissions from the archive (default is normal User service)--numeric-owner Always represent the user/group name with a number--owner=name Enforces NAME as the owner of the added file-p, --preserve-permissions, --same-permissionsExtract file permission information (default only for superusers)--preserve Same as -p and -s--same-ownerKeep the owner relationship consistent when trying to extract it (default for superusers)-s, --preserve-order, --same-ordermember arguments are listed in the same order asthe files in the archiveHandling of extended file attributes:--acls Enable the POSIX ACLs support--no-acls Disable the POSIX ACLs support--no-selinux Disable the SELinux context support--no-xattrs Disable extended attributes support--selinux Enable the SELinux context support--xattrs Enable extended attributes support--xattrs-exclude=MASK specify the exclude pattern for xattr keys--xattrs-include=MASK specify the include pattern for xattr keys设备选择和切换:-f, --file=ARCHIVE Use an ARCHIVE or archive device--force-localThe archive is considered a local archive even if it has a copy-F, --info-script= name, --new-volume-script= nameRun the script at the end of each tape (implicit -M)-L, --tape-length=NUMBER Replace the tape after the NUMBER x 1024 bytes is written-M, --multi-volume Create/list/decompress multi-volume archive files--rmt-command=COMMAND Use the specified rmt COMMAND instead of rmt--rsh-command=COMMAND Use remote COMMAND instead of rsh--volno-file=FILE Use/update the number of volumes in FILEEquipment partitioning:-b, --blocking-factor=BLOCKS BLOCKS x 512 bytes per record-B, --read-full-records Reblock when reading (valid for 4.2BSD pipe only)-i, --ignore-zeros Ignore zero-byte blocks in the archive (i.e., end of file)--record-size=NUMBER NUMBER of bytes per record, multiplied by 512Select an archive format:-H, --format=FORMAT Creates an archive in the specified formatFORMAT is one of the following formats:gnu GNU tar 1.13.x formatoldgnu GNU format as per tar <= 1.12pax POSIX 1003.1-2001 (pax) formatposix equate paxustar POSIX 1003.1-1988 (ustar) formatv7 old V7 tar 格式--old-archive, --portabilityequate --format=v7--pax-option= Keyword [[:]= value][, keyword [[:]= value]]...Control pax keywords--posix is equivalent to --format=posix-V, --label=TEXT Creates TEXT with the volume nameThe filing of; When listing/extracting, use TEXTThe pattern string used as the volume nameCompression options:-a. Auto compress uses archive suffixes to determine the compression program-I, --use-compress-program=PROGFilter through PROG (must be acceptable - d)Program for Options)-j. - bzip2 filters and archives through bzip2-J. -- xz filters and archives through xz--LZIP filters and archives through LZIP--LZMA filters and archives through LZMA--lzop--No auto compress does not use archive suffixes to determine the compression program-z. -- gzip, -- gunzip, -- ungzip Filter archive through gzip-Z. -- compress, -- uncompress Filter archive through compressLocal file selection:--add-file=FILE Add the specified FILE to the archive (if the name starts with -It'll be useful to start with)--backup[=CONTROL] Back up before deleting, select CONTROL version-C, --directory=DIR Change to directory DIR--exclude=PATTERN Excludes files specified in PATTERN--exclude-backups Exclude backup and lock files--exclude-caches Exclude inclusion except identifying the file itselfThe contents of the CACHEDIR.TAG directory--exclude-caches-all Exclude directories that contain CACHEDIR.TAG--exclude-caches-under Excludes everything in a directory that contains CACHEDIR.TAG--exclude-tag=FILE Excludes the contents of the directory containing FILE, except for FILE itself--exclude-tag-all=FILE Exclude directories that contain files--exclude-tag-under=FILE Exclude everything in the directory containing FILE--exclude-vcs Exclude the version control system directory-h, --dereferenceFollow symbolic links; File and output the files they point to--hard-dereferenceFollow hard links; File and output the files they point to-K, --starting-file=MEMBER-NAMEbegin at member MEMBER-NAME when reading thearchive--newer-mtime=DATE Compare data and time when only data changes--no-null Disable the last effect --null option--no-recursion Avoid automatic degradation in directories--no-unquote The file name that is not read by -T ends as a reference--null -T reads names terminated with null. -C is disabled-N, --newer=DATE-OR-FILE, --after-date=DATE-OR-FILESave only files that are newer than DATE-OR-FILE--one-file-system The archive is saved in the local file system when it is created-P, --absolute-names Do not clear the '/' from the file name--recursion Directory recursion (default)--suffix=STRING Backup before deletion, unless by environment variablesSIMPLE_BACKUP_SUFFIXOverwrite, otherwise overwrite common suffixes (")-T, --files-from=FILE Get the FILE name from file to extract or create the file--unquote -TRead file name as end of reference (default)-X, --exclude-from=FILE Excludes pattern strings listed in FILEFile name transformation:--strip-components=NUMBER Clear the NUMBER from the file name when extractingIndividual guide section--transform=EXPRESSION, --xform=EXPRESSIONUse sed instead of EXPRESSION To transform the file nameFile name matching options (affecting both exclusion and inclusion pattern strings):--anchored The pattern string matches the file name header--ignore-case ignore case--no-anchored The pattern string matches any character after '/' (default pair exclusion valid)--no-ignore-case Case matching (default)--no-wildcards Match the string word for word--no-wildcards-match-slash Wildcard mismatch '/'--wildcards use wildcards (default)--wildcards-match-slashWildcard matching '/' (default for exclusion operations)Suggestive output:--checkpoint[=NUMBER] NUMBER per intervalEach record displays progress information (default is 10)--checkpoint-action=ACTION The ACTION is executed at each checkpoint--full-time print file time to its full resolution--index-file=FILE Send detailed output to FILE-l, --check-linksPrint information as long as not all links are output--no-quote-chars=STRING Disable character references from STRING--quote-chars=STRING Additional reference characters from STRING--quoting-style=STYLE Set the name reference style; Effective STYLESee the following description for values-R, --block-number Each message shows the number of blocks in the archive--show-defaults Displays the tar default options--show-omitted-dirsWhen listing or extracting, list each directory that does not match the search criteria--show-transformed-names, --show-stored-namesDisplays the converted file name or archive name--totals[=SIGNAL] Print out the total number of bytes after processing the archive; Here and nowSIGNAL is triggered with parameter -Print the total number of bytes; The allowed signals are:SIGHUP, SIGQUIT, SIGINT, SIGUSR1 and SIGUSR2; No SIG is also acceptedPrefix of the signal name--utc Print the file modification time in UTC format-v, --verbose List the files processed in detail--warning=KEYWORD Warning control:-w, --interactive, --confirmationEach operation requires confirmation兼容性选项:-o When creating an archive, equivalent to--old-archive;When the archive is expanded, it is equivalent to--no-same-owner其它选项:-?, --help Display this help list--restrict Disable some potentially dangerous options--usage Display a short usage description--version Print program versionThe long option has the same mandatory or optional parameters as the corresponding short option.Except with --suffix or SIMPLE_BACKUP_SUFFIXSet the backup suffix. Otherwise, the backup suffix is ~.VERSION_CONTROL can be set with --backup or version_control, the possible values being:none, off Never make a backupt, numbered Numbering backupnil, existingA numbered backup is performed if a numbered backup exists, otherwise a simple backup is performednever, simple Always use a simple backup--quoting-style the valid parameterliteralshellshell-alwayscc-maybeescapelocaleclocaleThis tar defaults to:--format=gnu -f- -b20 --quoting-style=escape --rmt-command=/etc/rmt--rsh-command=/usr/bin/sshCommon commands
Extract file
xxxxxxxxxxtouch a.ctar -czvf test.tar.gz a.c //Compress the a.c file to test.tar.gz- z:gzip attribute
- j:bz2 attribute
- Z:compress attribute
- v:Display all processes
- O:Unzip the file to standard output
List the contents of compressed files
xxxxxxxxxxtar -tzvf test.tar.gz-rw-r--r-- root/root 0 2010-05-24 16:51:59 a.cUnzip
xxxxxxxxxxtar -xzvf test.tar.gza.c
18. top
top command can dynamically view the overall operation of the system in real time, and is a practical tool that integrates multi-party information monitoring system performance and operation information.
It provides a dynamic, interactive real-time view that displays overall system performance information as well as relevant information about running processes.
Grammar explanation
xxxxxxxxxxtop -hv | -bcEHiOSs1 -d secs -n max -u|U user -p pid(s) -o field -w [cols]Option Description
-b:Run in batch mode and output the results directly to a file.-c:Display the complete command line without truncation.-d <秒数>:Screen refresh interval time.-I:Ignore failed processes.-s:Confidentiality mode.-S:Accumulate the CPU usage time of the display process.-i:Do not display idle or useless processes.-u <User Name>:Specify the username.-p <Process number>:Specify the process.-n <Number of times>:The number of times it is displayed in a loop.-H:Display the resource usage status of all threads.
Top interaction command
Some interactive commands that can be used during the execution of the top command. These commands are all single letter, and some of them may be blocked if the - s option is used in the command line.
h:Display the help screen and provide a brief summary of the commands.k:Terminate a process.i:Ignore idle and dead processes (switch command).q:Exit the program.r:Reorder the priority level of a process.S:Switch to cumulative mode.s:Change the delay time between two refreshes, in seconds (or milliseconds if there are decimals). If a value of 0 is entered, the system will continuously refresh, with a default value of 5 seconds.forF:Add or remove items from the current display.oorO:Change the order of displayed items.l:Switch between displaying average load and startup time information.m:Switch to display memory information.t:Switch between displaying process and CPU status information.c:Switch between displaying command names and the complete command line.M:Sort based on the size of the resident memory.P:Sort by CPU usage percentage size.T:Sort by time/cumulative time.w:Write the current settings to the~/. toprc file.
Display information
xxxxxxxxxxtop - 14:55:57 up 1:03, 2 users, load average: 0.62, 0.55, 0.45Tasks: 158 total, 1 running, 157 sleeping, 0 stopped, 0 zombie%Cpu(s): 3.7 us, 9.3 sy, 0.0 ni, 86.0 id, 0.0 wa, 0.0 hi, 0.9 si, 0.0 stMiB Mem : 1982.2 total, 778.4 free, 645.6 used, 558.1 buff/cacheMiB Swap: 0.0 total, 0.0 free, 0.0 used. 1307.2 avail MemPID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND4496 root 20 0 14660 3092 2628 R 23.8 0.2 0:00.13 top3032 root 20 0 0 0 0 S 14.3 0.0 0:26.43 RTW_CMD_THREAD1 root 20 0 167580 10200 7216 S 0.0 0.5 0:03.09 systemd2 root 20 0 0 0 0 S 0.0 0.0 0:00.00 kthreadd4 root 0 -20 0 0 0 I 0.0 0.0 0:00.00 kworker/0:0H6 root 0 -20 0 0 0 I 0.0 0.0 0:00.00 mm_percpu_wq7 root 20 0 0 0 0 S 0.0 0.0 0:00.13 ksoftirqd/0Overall system information:
- Uptime: The running time and average load of the system.
- Tasks: The current number of running processes and threads.
- CPU: Overall CPU usage and usage of each core.
- Memory: Overall memory usage, available memory, and cache.
Process information:
- PID: The identifier of the process.
- User: The username of the running process.
- PR (Priority): The priority of a process.
- NI (Nice value): The priority adjustment value of the process.
- VIRT (Virtual Memory): The size of virtual memory used by a process.
- RES (Resident Memory): The actual physical memory size used by the process.
- SHR (Shared Memory): The size of memory shared by processes.
- % CPU: The usage rate of CPU occupied by processes.
- % MEM: The usage rate of memory occupied by processes.
- TIME+: The cumulative CPU time of the process.
Function and interactive operation:
- Key commands: When running on top, some key commands can be used for operations, such as pressing "k" to terminate a process, pressing "h" to display help information, etc.
- Sorting: Processes can be sorted by CPU usage, memory usage, process ID, etc.
- Refresh frequency: You can set the refresh frequency of top to dynamically view system information.
Common commands
Display process information
xxxxxxxxxxtopDisplay complete commands
xxxxxxxxxxtop -cDisplay program information in batch processing mode
xxxxxxxxxxtop -bDisplay program information in cumulative mode
xxxxxxxxxxtop -SSet the frequency of information updates
xxxxxxxxxxtop -n 2 # Terminate update display after two updatesSet information update time
xxxxxxxxxxtop -d 3 # Indicates an update cycle of 3 secondsDisplay specified process information
xxxxxxxxxxtop -p 139 # Display process information for process number 139, including CPU and memory usageExit after ten updates
xxxxxxxxxxtop -n 10Users will not be able to use conversational commands to issue commands for travel
xxxxxxxxxxtop -s19. zip
zip command can be used to decompress files or to package files.
Zip is a widely used compression program that produces compressed files with the extension . zip.
Grammar explanation
xxxxxxxxxxzip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list]- zipfile list:Specify the zip file to be created.
- File List: Specify the list of files to be compressed.
Option description
-0:Only store data without compression.-1:Faster compression speed.-9:Better compression quality.-<compression efficiency>:The compression efficiency is a value between 1-9.-@:Read file name from standard input.-A:Adjust the executable self extracting file.-b path:Specify the directory for temporarily storing files.-c:Add comments to each compressed file.-d:Delete entries from compressed files.-D:Do not add directory entries.-e:Encryption.-f:The effect of this parameter is similar to specifying the '- u' parameter, but it not only updates existing files, but also adds some files to the compressed file if they did not originally exist.-F:Attempt to repair the damaged compressed file (- FF attempts a more rigorous repair).-h2:Show more help.-i:Only compress files that meet the criteria.-j:Only save the file name and its contents, without storing any directory names.-J:Do not record compressed file prefixes (for self extracting files).-l:Convert LF to CR LF (- II represents CR LF to LF).-m:Move to compressed file (delete operating system files).-n:Do not compress these suffixes.-o:Make the compressed file date match the latest entry.-q:Quiet mode operation.-r:Recursive to the directory.-s:Change the delay time between two refreshes, in seconds (or milliseconds if there are decimals). If a value of 0 is entered, the system will continuously refresh, with a default value of 5 seconds.-T:Test the integrity of compressed files.-u:Update (only includes changed or new files).-v:Detailed operation, print version information.-X:Exclude additional file attributes.-y:Directly save the symbolic link, not the file pointed to by the link. This parameter is only valid on systems such as UNIX.-z:Add compressed file comments.
Common commands
Package all files and folders in the
/appdirectory asapp.zipin the current directory.xxxxxxxxxxzip -q -r app.zip /appIf we are in the
/appdirectory, we can execute the following command.xxxxxxxxxxzip -q -r app.zip *Delete
a.cfile from compressed filecp.zipzip -dv cp.zip a.c