This passage mainly introduces 30,000 words, 100 questions! Linux knowledge summary! As well as the relevant experience and skills, the article is about 160077 words, views 243, likes 7, worth reference!

The most recent Linux interview questions are about 30 thousand words and about 100 questions.

Overview of Linux

1. What is Linux

Linux is a unix-like operating system that is free to use and spread freely. It is a multi-user, multi-task, multi-threading and multi-CPU operating system based on POSIX and Unix. It can run major Unix tools, applications, and network protocols. It supports both 32-bit and 64-bit hardware. Linux inherits the design idea of Unix taking network as the core, and is a stable multi-user network operating system.

2. What is the difference between Unix and Linux?

Linux and Unix are both powerful operating systems and widely used server operating systems. There are many similarities, and some people even mistakenly believe that Unix and Linux are the same. However, this is not the case.

1. Open Source Linux is an open source operating system that can be used without payment. Unix is a traditional commercial software that protects the intellectual property of source code and requires a paid license.

2. Cross-platform Linux operating system has good cross-platform performance and can run on a variety of hardware platforms; Unix operating systems have poor cross-platform performance and must be used with hardware.

3. Visual interface Linux not only carries on the command line operation, but also has the window management system; Unix is just a command line system.

4. Hardware The Linux operating system has low requirements on hardware, and the installation method is easy to master. Unix has strict hardware requirements and is difficult to install.

Linux is widely used by individuals and businesses. Unix is used by a narrow group of users, mostly by large enterprises with high security requirements, such as banks and telecom departments, or by Unix hardware manufacturers, such as Sun.

Compared with the Unix operating system, The Linux operating system is more popular with computer enthusiasts, the main reason is that the Linux operating system has all the functions of the Unix operating system, and can realize all the Unix features on ordinary PC computers, open source free features, easier to use!

3. What is the Linux kernel?

The core of a Linux system is the kernel. The kernel controls all hardware and software on a computer system, allocating hardware when necessary, and executing software as needed. System memory management Application management hardware device management file system management

4. What are the basic components of Linux?

Just like any other typical operating system, Linux has all of these components: the kernel, the shell and the GUI, the system utilities and applications. What gives Linux an advantage over other operating systems is that every aspect comes with additional functionality, and all the code can be downloaded for free.

5. Linux architecture

On a large scale, the Linux architecture can be divided into two parts:

User Space: User Space includes User Applications and C Library.

Kernel Space: The Kernel Space includes System Call Interface, Kernel, and architecture-dependent Kernel Code.

Why is the Linux architecture divided into user space and kernel space?

1. Modern cpus have different working modes. In different modes, cpus can execute different instructions and access different registers. 2. From the perspective of CPU, Linux divides the system into two parts in order to protect the kernel security.

User space and kernel space are two different states of program execution. The transition from user space to kernel space can be accomplished in two ways: 1) system calls; 2) Hardware interruption.

6. What are the basic differences between BASH and DOS?

The main differences between BASH and the DOS console lie in three areas:

1. The BASH command is case-sensitive, while the DOS command is case-insensitive. 2. Under BASH, / character is the directory separator and \ is the escape character. Under DOS, / is used as a command parameter delimiter, \ is a directory delimiter. 3. OS follows the convention in named files, which is an 8-character filename followed by a dot and a 3-character extension. BASH does not follow such conventions.

7. Linux Boot process?

1. Power on the host and perform a self-check to load BIOS hardware information. 2. Read the boot file of the MBR (GRUB and LILO). 3. Boot the Linux kernel. 4. Run the first process init (process number is always 1). 5. Enter the corresponding run level. 6. Run the terminal and enter the user name and password.

8. What is the default running level for Linux?

To turn it off. Single-machine user mode. Character interface in multi-user mode (no network support). Character interface multi-user mode. Not allocated. Multi-user mode of graphical interface. Restart.

9. Interprocess communication methods used by Linux?

  • Pipes (PIPE), stream pipes (S_pipe), named pipes (FIFO).

  • Signal (signal).

  • Message queues.

  • Shared memory.

  • Semaphore.

  • A socket.

10. What system log files does Linux have?

More important is the /var/log/messages log file.

This log file is a summary of many process log files, from which any intrusion attempts or successful intrusions can be seen. In addition, if there is a centralized collection of ELK logs in your system, it will also be collected.

11. Is it helpful to install multiple desktop environments on Linux?

Usually, a desktop environment, such as KDE or Gnome, is sufficient to run without problems. Although the system allows switching from one environment to another, this is a priority for users. Some programs work in one environment but not in another, so it can also be considered a factor in choosing which environment to use.

12. What is swap space?

Swap space is a space used by Linux to temporarily hold programs that run concurrently. This happens when RAM does not have enough memory to hold all the programs being executed.

13. What is the root account

The root account is like a system administrator account, allowing you complete control of the system. You can create and maintain user accounts here, assigning different permissions to each account. This is the default account every time you install Linux.

14. What is LILO?

LILO is the boot loader for Linux. It is primarily used to load the Linux operating system into main memory so that it can start running.

15. What is BASH?

BASH is short for Bourne Again SHell. It was written by Steve Bourne as an alternative to the original Bourne Shell (represented by /bin/sh). It combines all the features of the original Bourne Shell, as well as other features, to make it easier to use. Since then, it has been adapted as the default shell for most systems running Linux.

16. What is CLI?

The command line interface (CLI) was the most widely used user interface before the popularity of graphical user interfaces. It usually did not support a mouse. Users input commands through the keyboard, and the computer executed the commands after receiving them. Some call it CUI (Character User interface).

A command line interface (CLI) is generally considered less user-friendly than a graphical user interface (GUI). Because, the command line interface software usually needs the user to memorize the command operation, but, because of its own characteristics, the command line interface should save the resources of the computer system compared with the graphical user interface. Using a command line interface is usually faster than using a graphical user interface (GUI), provided you have memorized commands. As a result, graphical user interface operating systems retain an optional command line interface.

17. What is a GUI?

Graphical User Interface (GUI) is a Graphical User Interface used for computer operations.

A graphical user interface is an interface display format for communication between a person and a computer that allows the user to use input devices such as a mouse to manipulate on-screen ICONS or menu options to select commands, invoke files, launch programs, or perform some other everyday tasks. Graphical user interfaces have many advantages over character interfaces that perform routine tasks by typing text or character commands on a keyboard.

**18. What are the advantages of open source? ** Open source allows you to distribute software (including source code) for free to anyone who is interested. One can then add features and even debug and correct errors in the source code. They can even make it work better, and then freely redistribute the enhanced source code again. This ultimately benefits everyone in the community.

19. What is the importance of the GNU project?

This so-called free software movement has many advantages, such as the freedom to run programs and learn and modify them as you see fit. It also allows you to redistribute copies of software to others, as well as the freedom to improve the software and distribute it to the public.

Disk, directory, file

1. Simple Linux file system?

In Linux, all resources managed by the operating system, such as network interface cards, disk drives, printers, I/O devices, common files, or directories, are treated as one file.

That said, there is an important concept in Linux: everything is a file. In fact, this is a reflection of the Unix philosophy, and Linux is a rewrite of Unix, so the concept has been passed on. On Unix systems, all resources are considered files, including hardware devices. UNIX systems treat each piece of hardware as a file, often called a device file, so that users can access the hardware by reading and writing files.

Linux supports five file types, as shown in the following figure

2. What is the directory structure of Linux?

That’s a question you don’t usually ask. More is needed when it comes to practical use.

Linux file systems have distinct hierarchies, like an upside-down tree, with their root directory at the top: the Linux directory structure

Common Directory description:

  • /bin: stores binary executable files (ls,cat,mkdir, etc.). Common commands are stored here.

  • /etc: stores system management and configuration files.

  • /home: the root directory for storing all user files. It is the base point of the user’s home directory. For example, the home directory of the user is /home/user, which can be expressed as ~user.

  • **/usr ** : used to store system applications /opt: where optional additional installed application packages are placed. Normally, we can install Tomcat and so on here;

  • /proc: virtual file system directory, which is a mapping of system memory. Access this directory directly for system information;

  • /root: home directory of the super user (system administrator) (privileged class O);

  • /sbin: stores binary executable files accessible only by root. The system commands and programs used by system administrators are stored here. Such as ifconfig, etc.;

  • /dev: stores device files.

  • / MNT: the installation point for the system administrator to install temporary file systems. The system provides this directory for users to mount other file systems temporarily.

  • /boot: stores various files used for system booting.

  • **/lib ** : store library files related to system operation;

  • / TMP: stores temporary files. It is the public storage point for temporary files.

  • /var: Used to store the files that need to change data during the runtime. It is also the overflow area of some large files, such as the log files of various services (system startup logs, etc.). And so on;

  • /lost+found: This directory is usually empty, and the system shuts down abnormally, leaving behind “homeless” files (called.chk under Windows).

3. What is an inode?

Typically, inode is not asked in interviews. But inodes are an important concept that is fundamental to understanding Unix/Linux file systems and hard disk storage.

To understand inodes, start with file storage.

Files are stored on a hard disk in a unit called a Sector. Each sector stores 512 bytes (equivalent to 0.5KB).

When the operating system reads disks, it does not read disks one sector at a time, which is inefficient. Instead, it reads disks consecutively, that is, one block at a time. This “block”, composed of multiple sectors, is the smallest unit of file access. The size of a “block” is 4KB, that is, eight consecutive sectors constitute a block.

The file data is stored in “chunks,” so obviously we have to find a place to store meta-information about the file, such as who created the file, the date it was created, the size of the file, and so on. The area where the meta information is stored is called an inode, or “index node” in Chinese.

Each file has an inode that contains information about the file.

How does the Linux file system convert the logical structure and physical structure of a file through the I node?

Generally speaking, this question is not asked by interviewers.

Linux uses inode node tables to transform the logical and physical structure of files.

· The inode node is a 64-byte long table that contains information about files, including file size, file owner, file access permission and file type. The most important element in the inode node table is the disk address table. There are 13 block numbers in the disk address table, and the file reads the corresponding blocks in the order in which they appear in the disk address table. · The Linux file system connects the inode node to the file name. When the file needs to be read, the file system searches for the item corresponding to the file name in the current directory table and obtains the inode node number corresponding to the file. The logical structure of the file is connected by the disk address table of the inode node.

4. What are hard and soft links?

1) Hard links

Since a file under Linux is identified by an inode, a hard link can be thought of as a pointer to a file inode, and the system does not reassign the inode to it. Each time you add a hard link, the number of links in the file increases by 1.

Disadvantages: 1) Cannot create links between files of different file systems; 2) Only superusers can create hard links for directories.

2) Soft links

Soft links overcome the disadvantages of hard links, there is no limitation of any file system, any user can create symbolic links pointing to directories. It is now more widely used and has greater flexibility, even linking files across different machines and networks.

Disadvantages: because the link file contains the path information of the original file, so when the original file is moved from a directory to other directories, and then access the link file, the system will not find, and the hard link does not have this defect, you want to move how to move; It also requires the system to allocate extra space to create new index nodes and save paths to original files.

In actual scenarios, soft links are used. The differences are summarized as follows:

· Hard links cannot cross partitions, but software chains can cross partitions. · Hard links point to an inode node, while soft links create a new inode node. · Deleting hard link files will not delete the original files, while deleting soft link files will delete the original files.

5. What is RAID?

RAID is called Redundant Array of Independent Disks (RAID). The basic idea of RAID is to combine multiple inexpensive hard Disks into a disk Array to achieve or exceed the performance of an expensive hard disk with a large capacity. RAID is typically used on server computers, using identical hard drives to form a logical sector, so the operating system treats it as a single hard drive.

RAID is classified into different levels. Each level has different trade-offs in data reliability and read/write performance. In actual applications, you can select different RAID solutions based on your actual requirements.

Of course, because many companies are using cloud services, it is difficult to contact the concept of RAID, more likely to be ordinary cloud disk, SSD cloud disk maozi concept.

Third, security

1. What security work should be done after a Linux system is initialized?

1. Add common user login, disable root user login, and change SSH port number.

Modifying an SSH port may not be absolute. Of course, if you want to be exposed to the Internet, it is recommended to change. l

2. The server uses the key to log in, but does not use the password.

3. Enable the firewall, disable SElinux, and set firewall rules based on service requirements.

4. Install fail2ban, which prevents VIOLENT SSH attacks.

5. Set only the export IP of the company’s office network to log in the server (depending on the actual needs of the company)

You can also install software such as VPN to connect only the VPN to the server.

6. Change the number of historical commands to 10.

7. Only servers that need access to the Internet are allowed.

8, do a good job of software protection. 8.1 Configuring the Nginx_WAf module to prevent SQL injection 8.2 Start the Web service as WWW user, change the owner and group of the website directory to WWW.

2. What is CC attack? What is a DDOS attack?

CC attacks, mainly used to attack the page, simulate multiple users to visit your page, so that your system resources are exhausted.

Distributed denial of Service (DDOS) attack refers to the use of server technology to unite multiple computers as an attack platform to launch DDOS attacks on one or more targets.

An attack is an attempt to paralyze the network by occupying a large number of network resources through a large number of legitimate requests.

How do I prevent CC and DDOS attacks?

To prevent CC and DDOS attacks, only hardware firewalls are used to clean traffic and divert attack traffic to black holes.

In terms of traffic cleaning, we can mainly buy anti-attack services from ISP service providers. Generally, there is free traffic in the computer room, so we usually buy services. After all, attacks will not last for a long time.

3. What is web database injection?

Due to the varying level and experience of programmers, most programmers do not judge the validity of user input data when writing code.

The application has security risks. Procedure The user can submit a piece of database query code, according to the results returned by the program, to obtain some of the data he wants to know, this is called SQL injection.

SQL injection, from the normal WWW port access, and the surface looks like the general Web page access is no different, if the administrator does not view the log habit, may be invaded for a long time will not be detected.

How to filter and prevent? Database web side injection of this, you can consider using nginx_WAF to do filtering and prevention.

Shell

1. What is a Shell script?

A Shell script is a text file that contains one or more commands. As system administrators, we often need to use multiple commands to complete a task, we can add all these commands in a text file (Shell script) to complete these daily work tasks.

– What is the default login Shell?

On Linux, “/bin/bash” is the default login Shell and is assigned when the user is created.

You can change the default Shell using the CHSH command. Here is an example:

## CHSH ThinkWon -s /bin/shCopy the code

– How do I write comments in Shell scripts?

Comments can be used to describe what a script can do and how it works. Each line of comments begins with a #. Examples are as follows:

#! /bin/bash ## This is a command echo "I am logged in as $USER"Copy the code

2. The grammatical level

– What types of variables can be used in Shell scripts?

In Shell scripts, we can use two types of variables:

System defined variables: System variables are created by the system itself. These variables are usually composed of uppercase letters and can be viewed with the set command.

User-defined variables: User variables are generated and defined by system users. You can run the “echo $< variable name >” command to view their values.

– Shell script $? What is the mark used for?

When writing a Shell script, if you want to check if the previous command executed successfully, use $? To check the end status of the previous command.

· If the end status is 0, the previous command is successfully executed. Such as:

 root@localhost:~## ls /usr/bin/shar
    /usr/bin/shar
    root@localhost:~## echo $?
    0 
Copy the code

· If the end status is not 0, the command fails to be executed. Such as:

 root@localhost:~## ls /usr/bin/share
    ls: cannot access /usr/bin/share: No such file or directory
    root@localhost:~## echo $?
    2 
Copy the code

– What are the special variables in the Bourne Shell(bash)? The following table lists the special variables that the Bourne Shell sets for the command line.

$1 The first command line argument $2 the second command line argument... . ... . $9 Ninth command line argument $## Number of command line arguments $* All command line arguments, separated by SpacesCopy the code

– How to cancel a variable or cancel a variable assignment? The unset command is used to cancel variable or variable assignment. The syntax is as follows:

# unset < variable name >Copy the code

– How to nest if syntax in Shell script?

If [condition] then command 1 command 2... . Else if [condition] then command 1 command 2... Else command 1 Command 2... . fi fiCopy the code

– How do I compare two numbers in a Shell script? Use test commands (-gt, etc.) in if-then to compare two numbers. Such as:

#! /bin/bash x=10 y=20 if [$x -gt $y] then echo "x is greater than y" else echo "y is greater than x" fiCopy the code

– Syntax of case statements in Shell scripts? Basic syntax is as follows:

Case variable in value 1) Command 1 Command 2... . Final order!! Value 2) Command 1 Command 2...... Final command; esacCopy the code

Syntax for loop in Shell script? The basic syntax is: –

For variable in loop list do command 1 Command 2... . The final command is doneCopy the code

While loop syntax in Shell scripts?

· Like the for loop, the while loop repeats its command block whenever the condition is true. · Unlike a for loop, a while loop iterates until its condition is not true.

Basic grammar:

While [condition] do command... doneCopy the code

– The basic format of the do-while statement?

A do-while statement is similar to a while statement, but the LCTT command is executed before the condition statement is checked. . Here is the syntax for using a do-while statement:

Do {command} while (condition) 1 2 3 4Copy the code

– What is the function of the break command in Shell script?

A simple use of the break command is to exit the loop in execution. We can break out of the while and until loops using the break command.

– What is the function of the continue command in Shell script?

The continue command differs from the break command in that it only breaks out of the current iteration of the loop, not the entire loop. The continue command is useful in many cases, such as when an error has occurred, but we still want to continue executing a large loop.

– How to make the script executable?

Use the chmod command to make the script executable. For example, chmod a+x myscript.sh.

#! What does /bin/bash do? #! /bin/bash is the first line of the Shell script and is called the shebang line. Here the # sign is called hash, and! Is called a bang. It means that the command is executed through /bin/bash.Copy the code

– How to debug Shell scripts?

Shell scripts can be debugged using the -x’ number (sh -x myscript.sh). Another way is to use the -nv argument (sh-nv myscript.sh).

– How do I redirect standard output and error output to the same location?

## ls /usr/share/doc > out.txt 2>&1 ## ls /usr/share/doc &> out.txt

– How do I test files in Shell scripts?

The test command can be used to test files. The basic usage is as follows:

-d file name True -e file name if the file exists and is a directory true -f file name If the file exists and is a normal file true -r file name If the file exists and is readable, Return true -s file name True if the file exists and is not empty -w file name True if the file exists and is writable -x file name True if the file exists and is executableCopy the code

– How does a Shell script define a function?

A function is a block of code with a name. When we define a code block, we can call the function name in our script and the block will be executed. Here is an example:

$ diskusage () { df -h ; [function] function name [()] {command; [return int;] }Copy the code

How do I get the Shell to get input from a terminal for a script?

The read command reads data from a terminal (using a keyboard). The read command takes the user’s input and places it in the variables you give it. Examples are as follows:

## vi /tmp/test.sh
#!/bin/bash
echo ‘Please enter your name’
read name
echo “My Name is $name”
## ./test.sh
Please enter your name
ThinkWon
My Name is ThinkWon 
Copy the code

– How to perform arithmetic operations?

There are two ways to perform arithmetic operations:

## expr 5 + 2 Use a dollar sign and square brackets (\[expression \]) : test=[16 + 4]; Test = $16 + [4].

4. Programming questions

1. Check whether a file is a character device file. If yes, copy it to /dev.

#!/bin/bash
read -p "Input file name: " FILENAME
if [ -c "$FILENAME" ];then
  cp $FILENAME /dev
fi 
Copy the code

2. Add a new group named class1, and add 30 users to this group with names of the form STDXX, xx from 01 to 30?

#! /bin/bash groupadd class1 for((i=1; i<31; i++)) do if [ $i -le 10 ]; then useradd -g class1 std0$i else useradd -g class1 std$i fi doneCopy the code

3. Write Shell program to automatically delete 50 accounts with the names stud1 to stud50?

#! /bin/bash for((i=1; i<51; i++)) do userdel -r stud$i doneCopy the code

4. Run the sed command to modify the contents of/TMP /input. TXT.

Requirements: · Delete all blank lines. · If a row contains 11111, insert AAA before 11111 and BBB after 11111. For example, change the line with 0000111112222 to 0000AAA11111BBB2222.

[root@~]## cat -n /tmp/input.txt 1 000011111222 2 3 000011111222222 4 11111000000222 5 6 7 111111111111122222222222 8 [root@~]## sed '/^$/d'/TMP /input. TXT 000011111222 000011111222222 [root@~]## sed '#\(11111\)#AAA\1BBB#g' [root@~]## sed' #\(11111\)#AAA\1BBB#g' /tmp/input.txt 0000AAA11111BBB222 0000AAA11111BBB222222 AAA11111BBB000000222 AAA11111BBBAAA11111BBB11122222222222 22AAA11111BBB111 112222222 1122Copy the code

Five, combat combat

1. How do I select a Linux OS version?

In general, desktop users prefer Ubuntu; RHEL or CentOS is preferred for the server. CentOS is preferred.

According to specific requirements:

· Select Debian or FreeBSD if security requirements are high.

· Users who need advanced database services and email network applications can choose SUSE.

· Feddora is a beta and pre-release version of RHEL and CentOS for new technologies and features.

· [Key point] According to the current situation, most Internet companies choose CentOS. Now more commonly used is the 6 series, now accounts for about half of the market. Another reason is that CentOS is more server oriented and has no copyright restrictions.

CentOS 7 series, also slowly used will be more.

2. How to plan a Linux host?

1. Determine what the machine is for, such as WEB, DB, or game server.

The configuration of the machine will be different for different purposes.

2, after determining, it is necessary to determine how the system needs to be installed, which system is installed by default, how to do partitions.

3. Which parameters of the system need to be optimized, which users need to be created, and so on.

**3. How to deal with the feedback from users about slow access to the website? ** – What are some of the factors that cause slow access to a website?

1. The egress bandwidth of the server is insufficient

The egress bandwidth purchased by the server is relatively small. Once the concurrency is large, the egress bandwidth allocated to each user will be small, and the access speed will naturally be slow. Cross-carrier networks reduce bandwidth. For example, the company’s website is placed on the telecom network, so the customer side is connected to the Great Wall broadband or Unicom, which may also lead to the reduction of bandwidth.

2. The server is overloaded and fails to respond

You can analyze the system load from two aspects: analyze the system load and use the W command or uptime command to check the system load. If the load is high, run the top command to check the CPU usage, MEM usage, etc. Either the CPU is busy or the memory is insufficient. If both are normal, use the SAR command to analyze network adapter traffic and determine whether the network adapter is attacked. Once the cause of the problem is identified, take appropriate actions to resolve it, such as deciding whether to kill some processes or disable some access.

3. Database bottlenecks

If the slow query is more. Then it is up to the developer or DBA to help tune the SQL statements. If the database is slow to respond, consider adding a database cache, such as Redis. Then, you can set up a MySQL master/slave database, with one MySQL server responsible for writing and several secondary databases responsible for reading.

4, the website development code is not optimized

For example, SQL statements are not optimized, resulting in time-consuming database reads and writes.

– For slow website access, how to check?

1. First determine whether the problem is on the client side or the server side. When receiving user feedback that access is slow, the other side immediately visit the website to have a look, if their access is fast, basically concluded that the user side of the problem, you need to be patient with the customer to explain, to help customers solve the problem.

Don’t start with the server side. Be sure to start at the source and work your way down.

2, if access is also slow, then you can use the browser’s debugging function to see which data takes too long to load, is the image load slow, or some data load slow.

3. For server load. Check the hardware consumption (network, CPU, and memory) of the server. If the cloud host is purchased, such as Ali Cloud, you can log in to Ali Cloud platform to provide monitoring of various aspects, such as CPU, memory and bandwidth usage.

4. If you find that hardware resource consumption is not high, you need to check the log, for example, check the log of MySQL slow query to see whether a CERTAIN SQL statement query is slow, resulting in slow website access.

– How?

1, if the export bandwidth problem, so long to apply for increasing the export bandwidth. 2. If there are a lot of slow queries, then the developer or DBA is required to assist in SQL statement optimization. 3, if the database is slow to respond, consider adding a database cache, such as Redis, etc. You can also set up a MySQL master/slave database, with one MySQL server responsible for writing and several secondary databases responsible for reading. 4. Apply for purchasing CDN service and load user access. 5. If the access is still slow, you need to optimize the overall architecture. To achieve a dedicated role, multiple servers to provide the same service.

4. What are the methods of Linux performance tuning?

Disabling daemons 1. Shutting down the GUI. 3, Changing the kernel parameters 4, Kernel parameters. 4, Tuning the processor subsystem 6, Tuning the memory subsystem 4, Tuning the file system 8, Tuning the network subsystem

File management commands

1. The cat command

The cat command is used to connect files and print them to the standard output device.

Cat has three main functions:

1. Display the entire file at once:

cat filename 
Copy the code

2. Create a file from keyboard:

cat > filename 
Copy the code

You can only create new files, not edit existing files.

3. Merge several files into a single file:

cat file1 file2 > file 
Copy the code

-b Displays non-empty line numbers. -n Displays all line numbers

– the instance:

(1) Add a line number to the log2012.log file and enter it in the log2013.log file

cat -n log2012.log log2013.log 
Copy the code

(2) Append the contents of log2012.log and log2013.log files to log.log by adding line numbers (blank lines are not added)

cat -b log2012.log log2013.log log.log 
Copy the code

(3) Use here Doc to generate a new file

cat >log.txt <<EOF
>Hello
>World
>PWD=$(pwd)
>EOF
ls -l log.txt
cat log.txt
Hello
World
PWD=/opt/soft/test 
Copy the code

(4) Reverse listing

tac log.txt
PWD=/opt/soft/test
World
Hello 
Copy the code

2. The chmod command

In Linux/Unix, file invocation permissions are divided into three levels: file owner, file group, and others. Chmod allows you to control how files are called by others.

Change the access permission of a file or directory in the Linux system. Use it to control access to files or directories. This command can be used in two ways. One is a literal setting method that contains letters and operator expressions. The other is the number setting method with numbers.

Each file or directory has three groups of access permissions. Each group is the read, write, and execute permissions of the file owner. Read, write, and execute permissions of users in the same group as the owner; Read, write, and execute permissions of other users in the system. You can use ls -l test.txt to find.

The following uses the log2012.log file as an example:

-rw-r--r-- 1 root root 296K 11-13 06:03 log2012.log 
Copy the code

There are 10 positions in the first column, with the first character specifying the file type. In a general sense, a directory is also a file. If the first character is a dash, it is a file that is not a directory. If the value is D, it is a directory. Nine characters from the second character to the tenth character, a group of three characters, respectively representing the permissions of three groups of users on files or directories. Permission characters are underlined for empty permission, r for read-only, W for write, and x for executable.

Common parameters:

-c Reports processing information when changes occur. -r processes all files in the specified directory and its subdirectoryCopy the code

Scope of Authority:

U: current users of a directory or file G: current groups of a directory or file O: users or groups except the current users or groups of a directory or file A: all users or groupsCopy the code

Permission Code:

R: read permission (4) W: write permission (2) X: execute permission (1) - : delete permission (0) S: special permissionCopy the code

– Example: (1) Add the execute permission to all users of file t.log

chmod a+x t.log 
Copy the code

(2) Revoke all the original permissions, and then make the owner has readable permissions, and output processing information

chmod u=r t.log -c 
Copy the code

(3) Assign permissions to read, write, and execute (7) to the owner of file, to read and execute (5) to the group where file resides, and to execute (1) to other users

Chmod 751 t.log-c (或 chmod u= RWX,g=rx,o=x t.log-c)Copy the code

(4) Add read permission to all files in the test directory and its subdirectories

chmod u+r,g+r,o+r -R text/ -c 
Copy the code

3. The chown command

Chown Changes the owner of a specified file to a specified user or group. The user can be a user name or user ID. A group can be a group name or a group ID. Files are a list of files whose permissions are to be changed separated by Spaces. Wildcard characters are supported.

-c Displays information about the changed part. -r processes the specified directory and subdirectoriesCopy the code

– the instance:

(1) Change the owner and group and display the change information

chown -c mail:mail log2012.log 
Copy the code

(2) Change the file group

chown -c :mail t.log 
Copy the code

(3) Change the owner and owner group of folders and subfiles to Mail

chown -cR mail: test/ 
Copy the code

4. The cp command

Copies a source file to a destination file, or copies multiple source files to a destination directory.

Note: command line copy, if the target file already exists will prompt whether to overwrite, but in shell script, if not add -i argument, will not prompt, but directly overwrite!

-i Prompt -r Copy the directory and all items in the directory -a The time of the file to be copied is the same as that of the original fileCopy the code

– the instance:

(1) copy a.txt to the test directory, keep the original file time, if the original file exists, prompting whether to overwrite.

cp -ai a.txt test 
Copy the code

(2) Suggest a link (shortcut) for A.txt

cp -s a.txt link_a.txt 
Copy the code

5. The find command

Used to find files in the file tree, and make the corresponding processing.

Command format:

find pathname -options [-print -exec -ok ...] 
Copy the code

Command parameters:

Pathname: Path of the directory searched by the find command. For example, a dot represents the current directory and a slash represents the system root directory. -print: find prints the matched files to standard output. -exec: find Executes the shell command given by this parameter on the matched files. The corresponding command is of the form 'command' {} \; , note {} and \; The space between. -ok: Serves the same purpose as -exec, except that the shell commands given by this parameter are executed in a more secure mode. Before each command is executed, a prompt is given for the user to determine whether to execute.Copy the code

Command options:

-name Searches for files by file name -perm Searches for files by file permission -user Searches for files by file owner -group Searches for files by file group. -type Searches for files of a certain type, such as B - Block device file D - Directory C - Character device file L - Symbolic link file P - Pipe file F - Common fileCopy the code

– the instance:

(1) Search for files that have been modified within 48 hours

find -atime -2 
Copy the code

(2) Find files ending in.log in the current directory. . Indicates the current directory

find ./ -name '*.log' 
Copy the code

(3) Search for files whose permission is 777 in /opt

find /opt -perm 777 
Copy the code

(4) Search for files larger than 1K

find -size +1000c 
Copy the code

(5) Find files equal to 1000 characters

find -size 1000c 
Copy the code

The -exec argument is followed by the command command, which terminates with; The semicolon is the end of the command, so the semicolon after this command is indispensable. Considering that the semicolon can have different meanings in different systems, so the backslash is added. The {} curly braces represent the name of the file found earlier by find.

6. The head command

Head is used to display the beginning of the file to standard output. The default head command prints the first 10 lines of the corresponding file.

Common parameters:

-n< number of rows > Number of rows to display (the number of rows is plural if the number is from last forward)Copy the code

Example:

(1) Display the first 20 lines in the 1.log file

head 1.log -n 20 
Copy the code

(2) Display the first 20 bytes of the 1.log file

head -c 20 log2014.log 
Copy the code

(3) Display the last 10 lines of t.log

head -n -10 t.log 
Copy the code

7. Use less

Less is similar to more, but you can browse files at will. More can only move forward, not backward, and less does not load the entire file before viewing it.

Common command parameters:

-i ignores case when searching -n displays the line number of each line -o < file name > saves the output of less in the specified file -s displays consecutive empty behavior line/string: The function of searching down for "string"? String: Function to search up for "string" n: Repeat previous search (and/or? N: Repeat the previous search in reverse (with/or? About) -x < number > display "TAB" key as specified number space B backward scroll a page D backward scroll half a page H display help interface Q Exit less command U forward scroll half a page Y Forward scroll a line space bar forward scroll a line enter key forward scroll a page [pageDown] : Page down [pageUp] : To turn up a pageCopy the code

Example:

(1) ps Displays process information in less pages

ps -aux | less -N 
Copy the code

(2) View multiple files

less 1.log 2.log 
Copy the code

You can use n to view the next one and p to view the previous one.

**8. The ln command is used to create a synchronous link for a file in another location. If this problem is needed in different directories, it is not necessary to create the same file for each directory.

Link classification: software link and hard link

Soft links:

1. Soft links exist in the form of paths. Similar to shortcuts in Windows 2. Soft links can cross file systems, but hard links cannot. 3. Soft links can link to a file name that does not exist. 4. Soft links can link to directories

Hard links:

1. Hard links exist in the form of file copies. But it doesn’t take up real space. Hard links cannot be created for directories. 3. Hard links can be created only in the same file system

Note:

First, the ln command keeps all linked files synchronized, meaning that no matter where you change them, all the other files will change the same. The second: Ln links and points of soft and hard links two kinds, soft links is ln -s source file object files, it will only be in the position of your selected to generate a file of the mirror, not take up disk space, hard links the target file ln source files, no parameters – s, it will be in the position of your selected to generate a file with the same size and source files, Files change synchronously, whether soft or hard. Third, the ln command is used to link files or directories. If more than two files or directories are specified at the same time and the last destination is an existing directory, all the files or directories specified above will be copied to this directory. If multiple files or directories are specified at the same time and the final destination is not an existing directory, an error message is displayed.

Common parameters:

-b Deletes and overwrites previously established links. -s soft links (symbolic links) -v Displays the detailed processing processCopy the code

Example:

(1) Create soft links for files and display operation information

ln -sv source.log link.log 
Copy the code

(2) Create a hard link for the file and display the operation information

ln -v source.log link1.log 
Copy the code

(3) Create soft links for directories

ln -sv /opt/soft/test/test3 /opt/soft/test/test5 
Copy the code

9. The locate command

Locate finds files quickly by searching the system’s built-in document database, which is updated by the UpdatedB program, which is called periodically by the Cron Daemon. By default, the locate command searches the database faster than the entire hard drive database, but worse is that the files locate finds may not be found if they were recently created or renamed. In intrinsic values, updatedb runs once a day. The Settings can be updated by modifying crontab (etc/crontab).

The locate command is similar to the find command and can be used with commands such as *,? And so on for regular match search

Common parameters:

-l num (number of lines to display) -f excludes specific file systems, such as proc. -r uses regular expressions as search criteriaCopy the code

Example:

(1) Find all files related to PWD (including PWD in filename)

locate pwd 
Copy the code

(2) Search for all files starting with sh in the etc directory

locate /etc/sh 
Copy the code

(3) Find files in the /var directory that end with reason

Locate -r '^/var.*reason$' (where * indicates multiple tasks. .* stands for any number of characters.Copy the code

**10. The function of more command ** is similar to cat. More can be displayed page by page to facilitate users to read page by page.

Command parameters:

-n Sets the screen size to n lines. +/pattern searches for the pattern before each file display, then displays it from the first two lines. -C clears the screen from the top, then displays -d prompt "Press space to continue," 'q' to quit (press spacebar to continue, press Q to quit) ", disable the ring function -l Ignore Ctrl+ L (page feed) character -p To page feed the file by clearing the window instead of scrolling, similar to the -c option -s displays successive blank lines as one line. -u removes the underline in the file contentCopy the code

Common operation commands:

Enter goes down n rows and needs to be defined. Default: 1 line Ctrl+F Scroll down one screen Space bar Scroll down one screen Ctrl+B Return to the previous screen = Output line number of the current line: F Output file name and line number of the current line V Invoke the vi editor! Command to invoke the Shell and run the q command to exit moreCopy the code

Example:

(1) Display the contents of the file from line 3 onwards

more +3 text.txt 
Copy the code

(2) In the list of file directory details, with the help of the pipeline to display 5 lines each time

ls -l | more -5 
Copy the code

Press space to display the next 5 lines.

11. The mv command

Move the file or change the file name according to the second parameter type (such as directory, move the file; Recommand the file if it is a file).

When the second argument is a directory, the first argument can be multiple space-separated files or directories, and then move multiple files specified by the first argument to the directory specified by the second argument.

Example:

(1) Rename the test.log file to test1.txt

mv test.log test1.txt 
Copy the code

(2) the file log1. TXT, log2. TXT, log3. TXT moved to the root of the test3 directory

mv llog1.txt log2.txt log3.txt /test3 
Copy the code

(3) rename file file1 to file2. If file2 already exists, ask whether to overwrite

mv -i log1.txt log2.txt 
Copy the code

(4) Move all files in the current folder to the upper directory

mv * .. /Copy the code

12. The rm command

Delete one or more files or directories in a directory. If the -r option is not used, rm will not delete the directory. If you use RM to delete a file, you can usually still restore the file.

Rm [options] file...Copy the code

Example: (1) Delete any.log files and ask for confirmation before deleting them:

rm -i *.log 
Copy the code

(2) delete subdirectory test and delete all files in subdirectory test.

rm -rf test 
Copy the code

(3) Delete files that start with -f

rm -- -f* 
Copy the code

13. The tail command

Displays the content at the end of a specified file. If no file is specified, the file is processed as input information. View log files frequently.

Common parameters:

-f loop read (often used to view incrementing log files) -n< number of lines > Display number of lines (from back to front)Copy the code

(1) Loop reading gradually increasing file content

Ping 127.0.0.1 > ping.log &Copy the code

Background running: it can be viewed using JOBS -L or moved to the foreground running using FG.

tail -f ping.log 
Copy the code

(View logs)

14. Touch command

The Linux touch command is used to modify the time attributes of a file or directory, including the access time and change time. If the file does not exist, the system creates a new file.

Ls -l can display the time record of the file.

grammar

Touch [- delivered acfm per input horsepower] [-d < date/time >] [-r < > reference file or directory] t < date/time > [-] [-- help] [-- version] [...] file or directoryCopy the code

Parameter description: a Changes the file read time record. M Changes the modification time record of the file. C If the destination file does not exist, no new file will be created. The same effect as –no-create. F Is reserved for compatibility with other Unix systems. R uses the time record of the reference file, which has the same effect as –file. D Set time and date, you can use a variety of formats. T Sets the time record of the file in the same format as the date command. – no-create No new file is created. – help lists the command format. – version Lists the version information.

The instance

Use the command “touch” to change the time attribute of file” testfile” to the current system time. Enter the following command:

$touch testFile # Change the time attribute of the fileCopy the code

First, use the ls command to view the properties of the testFile file as follows:

$ls -l testfile $ls -l testfile $ls -l testfile $ls -l testfileCopy the code

After executing the command “touch” to modify the file properties, check the time properties of the file again, as shown below:

$ls -l testFile $ls -l testfile $ls -r--r-- 1 HDD HDD 55 2011-08-22 19:53 testfileCopy the code

When using the instruction “touch”, if the specified file does not exist, a new blank file is created. For example, using this command to create a blank file” file” in the current directory, type the following command:

$touch file # Create a new blank file named "file"Copy the code

15. Vim command

Vim is a text editor developed from VI. Code completion, compilation, error jump and other convenient programming functions are particularly rich, widely used in programmers.

Open the file and skip to line 10: vim +10 filename.txt. Open the file and jump to the first matching line: vim +/search-term filename.txt. Open the file in read-only mode: vim -r /etc/passwd.

Basically, VI/VIM can be divided into three modes, namely Command mode, Insert mode and Last line mode.

In simple terms, we can think of these three patterns as ICONS below:

The whereis command can only be used to search for program names, and only for binary files (parameter -b), man description files (parameter -m), and source code files (parameter -s). If the argument is omitted, all information is returned. Whereis and Locate are efficient searches based on built-in databases, while Find traverses hard drives to find files.

Common parameters:

-b Locates the executable file. -m Locate help files. -s Locates the source code file. -u Searches for all files except executable files, source files, and help files in the default path.Copy the code

Example:

(1) Find the files related to the Locate program

whereis locate 
Copy the code

(2) Locate the source file

whereis -s locate 
Copy the code

(3) Find the help file of LCOate

whereis -m locate 
Copy the code

17. Which command

If you want to find a file on Linux and don’t know where it is, you can use the following commands to search for it:

Which looks at the location of the executable. Whereis views the location of a file. Locate works with the database to view the file location. Find Actual search disk query file name.Copy the code

Which is the location of a system command in the specified PATH and returns the first search result. Using the which command, you can see whether a system command exists and which location of the command was executed.

Common parameters:

-n Specifies the length of the file name. The specified length must be longer than or equal to the longest file name in all files.Copy the code

Example: (1) Check whether the ls command exists and which command to run

which ls 
Copy the code

(2) Which

which which 
Copy the code

3) Check the CD

Which CD (display does not exist because CD is a built-in command and the which lookup display is a command in PATH)Copy the code

View the current PATH configuration:

echo $PATH 
Copy the code

Or use env to view all environment variables and their corresponding values

7. Document editing commands

1. The grep command

Powerful text search command, grep(Global Regular Expression Print) Global Regular Expression search.

Grep works like this: it searches for string templates in one or more files. If the template includes Spaces, it must be referenced, and all strings after the template are treated as filenames. The results of the search are sent to standard output without affecting the content of the original file.

Command format:

grep [option] pattern file|dir 
Copy the code

Common parameters:

-A n --after-context Displays n lines after matching characters. -b n --before-context Displays n lines before and after matching characters. -C n --context Displays n lines before and after matching characters -f Reads keywords from the file. -n Displays the number of lines in the file where the matching content resides. -r Recursively searches for foldersCopy the code

Grep regular expression:

^ # Anchor line start like '^grep' matches all lines starting with grep. 'grep$' matches all lines ending with grep. # matches a non-newline character such as 'gr.p' matches GR followed by any character, then p. * # matches zero or more previous characters such as '*grep' matches all lines followed by one or more Spaces. Use.* # together to represent any character. [] # match a specified range of characters, such as '[Gg]rep' match Grep and Grep. [^] # matches A character that is not in the specified range, for example: '[^ a-fh-z]rep' matches the beginning of A letter that does not contain a-r and t-z, following the line of rep. \ [.. \) # marks a match character, such as '\(love)', where love is marked as 1. \< # Anchors the beginning of a word, such as :'\<grep' matches lines that contain words starting with grep. \> # Anchor the end of a word, such as 'grep\>' matches a line that contains a word ending with grep. X \{m\} # repeats the character x, m times, such as: '0\{5\}' matches a line containing five O's. X \{m,\} # repeats the character x at least m times, such as: 'o\{5,\}' matches lines with at least five O's. X \{m,n\} # repeats the character x at least m times, but not more than n times, e.g. 'o\{5,10\}' matches lines with 5--10 o's. \w # matches literal and numeric characters, that is, [A-za-z0-9], as in: 'G\w*p' matches G followed by zero or more literal or numeric characters, followed by p. The inverted form of \W #\ W matches one or more non-word characters, such as periods, etc. \b # word lock, such as '\bgrep\b' matches only grep.Copy the code

Example:

(1) Find the specified process

ps -ef | grep svn 
Copy the code

(2) Find the specified number of processes

ps -ef | grep svn -c 
Copy the code

(3) Read keywords from files

cat test1.txt | grep -f key.log 
Copy the code

(4) Recursively search for lines starting with grep from folders and list only files

grep -lR '^grep' /tmp 
Copy the code

(5) Find the line content of the non-X switch

grep '^[^x]' test.txt 
Copy the code

(6) Display the content line containing Ed or AT characters

grep -E 'ed|at' test.txt 
Copy the code

2. Wc command

Word count (WC) counts the number of bytes, words, and lines in a specified file and outputs the statistics result

Command format:

wc [option] file.. 
Copy the code

Command parameters:

-c Number of bytes -L Number of lines -m Number of characters -w Number of words. A word is defined as a character string separated by blank, TAB, or newline charactersCopy the code

Example: (1) Find file line number of words number of bytes file name

wc text.txt 
Copy the code

Results:

7     8     70     test.txt 
Copy the code

(2) Count the number of lines of output results

cat test.txt | wc -l 
Copy the code

Disk management commands

CD command ** changeDirectory (CD) syntax:

CD [Directory name]Copy the code

Switch the current directory to dirName.

Example: (1) Go to the desired directory

cd / 
Copy the code

(2) Go to the Home directory

cd ~ 
Copy the code

(3) Enter the last working path

cd - 
Copy the code

(4) Use the parameters of the previous command as CD parameters.

cd ! $Copy the code

2. The df command

Display disk space usage. If no file name is specified, the available space of all currently mounted file systems will be displayed. By default, disk space will be displayed in 1KB, unless the environment variable POSIXLY_CORRECT is specified, which will be displayed in 512 bytes:

-a List of all file systems -h Displays information in a readable way -i Displays inode information -k blocks are 1024 bytes -l Displays only local disks -t Lists file system typesCopy the code

Example: (1) Display disk usage

df -l 
Copy the code

(2) List all file systems and their types in a readable manner

df -haT 
Copy the code

3. The du command

The du command also displays the space used, but unlike the df command, the Linux du command displays the space used by files and directory disks:

Command format:

Du [options] [file]Copy the code

Common parameters:

-a Displays the size of all files in a directory -k Displays the file size in KB -m Displays the file size in MB -g Displays the file size in GB -h Displays the file size in readable mode -s Displays the total. -C or --total Displays the size of individual directories or files. It also displays the total of all directories or filesCopy the code

Example: (1) display the size of folders and subfolders in a readable way

du -h scf/ 
Copy the code

(2) display all file sizes in the folder in a readable way

du -ah scf/ 
Copy the code

(3) display the size of the disk space occupied by several files or directories, and also statistics their total

du -hc test/ scf/ 
Copy the code

(4) Output the space used by each subdirectory in the current directory

du -hc --max-depth=1 scf/ 
Copy the code

4. The ls command

Is the abbreviation of list, through the ls command can not only view the files contained in the Linux folder, but also view the file permissions (including directories, folders, file permissions) view directory information and so on.

Common parameter collocation:

Ls -a lists all files in the directory, including the. Start hidden file ls -A listed except. And.. Ls -t Sort by file modification time ls -s Sort by file size ls -h Display by readable size LS -l In addition to file names, file permissions, owners, and file sizes are listed in detailCopy the code

Example: (1) Sort the file in reverse chronological order by easy to read, and display the file details

ls -lhrt 
Copy the code

(2) Display file details in reverse order by size

ls -lrS 
Copy the code

(3) List the details of all directories starting with “t” in the current directory

ls -l t* 
Copy the code

(4) List the absolute path of files (not including hidden files)

ls | sed "s:^:`pwd`/:" 
Copy the code

(5) List the absolute path of files (including hidden files)

find $pwd -maxdepth 1 | xargs ls -ld 
Copy the code

5. The mkdir command

The mkdir command is used to create a folder.

Options are as follows: -m: Sets the access permission for a new directory. You can also run the chmod command to set the access permission. -p: indicates a path name. If some directories in a path do not exist, the system automatically creates those directories. That is, multiple directories can be created at a time.

Example: (1) Create a folder named t under the current working directory

mkdir t 
Copy the code

Create a TMP directory whose path is test/t1/t.

mkdir -p /tmp/test/t1/t 
Copy the code

6. The PWD command

The PWD command is used to view the current working directory.

Example: (1) View the current path

pwd 
Copy the code

(2) View the actual path of the soft link

pwd -P 
Copy the code

**7. The rmdir command ** deletes one or more subdirectory entries from a directory. When deleting a directory, you must have write permission on its parent directory. Note: You cannot delete a non-empty directory

(1) If the parent subdirectory is deleted and it becomes an empty directory, delete it as well:

rmdir -p parent/child/child11 
Copy the code

Network communication command

1. The ifconfig command

Ifconfig is used to view and configure network interfaces in the Linux operating system. Run the ifconfig -a command to view all network interfaces and their statuses. Run the up and down commands to start or stop an interface: ifconfig eth0 up and ifconfig eth0 down.

2. The iptables command

Iptables is a command line tool for configuring Linux kernel firewalls. Function is very powerful, for our development, the main master how to open the port. Such as:

Iptables -i INPUT -s 192.168.1.101 -p TCP –dport 80 -j REJECT REJECT packets whose source IP address is 192.168.1.101.

Enable port 80, because this port is used by the Web

 iptables -A INPUT -p tcp --dport 80 -j ACCEP 
Copy the code

Also, be careful to use the iptables save command to save. Otherwise, the configured rules will be lost after the server restarts.

3. The netstat command

The Linux netstat command is used to display network status.

The netstat directive lets you know the network condition of the entire Linux system.

grammar

Netstat [-accefghilMnNoprSTUVVwx][-a < Network type >][-- IP]Copy the code

Parameter Description: -a or -all Displays all sockets. -A< Network type > or – < Network type > lists the related addresses in the connection of the network type. -c or -continuous Lists the network status continuously. -c or – cache Displays the cache information configured by the router. -e or -extend Displays other network information. -f or -fib Displays the FIB. -g or -groups Displays the member list of multiple broadcast groups. -h or -help Online help. -i or -interfaces Displays the network interface information form. -l or – listening Displays the Socket of the monitored server. -m or -masquerade displays disguised network connections. -n or -numeric uses the IP address directly, not through the DNS. -n or -netlink or -symbolic Indicates the symbolic connection name of the network hardware peripheral device. -o or – timers Displays timers. -p or -programs displays the identifiers and names of the programs using the Socket. -r or -route Displays the Routing Table. -s or -statistice Displays network work information statistics. -t or -tcp Displays the connection status of TCP. -u or – udp Displays the connection status of udp transport protocol. -v or – verbose Displays the command execution process. -v or -version Displays the version information. -w or – raw Displays the connection status of the RAW transmission protocol. -x or -unix This parameter has the same effect as specifying the “-a Unix” parameter. – IP or – inet This parameter has the same effect as “-a inet”.

The instance

How to check which ports are enabled in the system?

[root@centos6 ~ 13:20 #55]# netstat -lnp 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:22 0.0.0.0:* LISTEN 1035/ SSHD TCP 0 0: ::22 ::* LISTEN 1035/ SSHD Udp 0 0 0.0.0.00:68 0.0.0.0:* 931/ DHClient Active UNIX Domain Sockets (only Servers) Proto RefCnt Flags Type State I-Node PID/Program name Path unix 2 [ ACC ] STREAM LISTENING 6825 1/init @/com/ubuntu/upstart unix 2 [ ACC ] STREAM LISTENING 8429 1003/dbus-daemon /var/run/dbus/system_bus_socketCopy the code

How do I check the network connection status?

[root@centos6 ~ 13:22 #58]# 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:22 0.0.0.0:* LISTEN TCP 0 0 192.168.147.130:22 192.168.147.1:23893 ESTABLISHED TCP 0 0: ::22 ::* LISTEN UDP 0 0 0.0.0.0:68 0.0.0.0:*Copy the code

How do I count the number of current process connections in the system?

Type the command netstat – an | grep ESTABLISHED | wc -l. The output is 177. There are 177 connections.

Run the netstat command along with other commands to count the number of ESTABLISHED connections to port 80 based on the source IP address.

Strictly speaking, this topic tests the use of AWK.

First of all, using netstat – an | grep ESTABLISHED command. The results are as follows:

TCP 0 0 120.27.146.122:80 113.65.18.33:62721 ESTABLISHED TCP 0 0 120.27.146.122:80 27.43.83.115:47148 ESTABLISHED TCP 0 0 120.27.146.122:58838 106.39.162.96:443 ESTABLISHED TCP 0 120.27.146.122:52304 203.208.40.121:443 ESTABLISHED TCP 0 0 120.27.146.122:33194 203.208.40.122:443 ESTABLISHED TCP 0 120.27.146.122:53758 101.37.183.144:443 ESTABLISHED TCP 0 0 ESTABLISHED 23.105.193.30 120.27.146.122:27017:50556Copy the code

4. The ping command

The Linux ping command is used to check hosts.

After the ping command is executed, ICMP is used to send a message requesting a response. If the remote host is running properly, the remote host responds to the message.

Specifies the number of times packets are received

ping -c 2 www.baidu.com 
Copy the code

5. Telnet command

The Linux Telnet command is used to log in remotely.

Run the Telnet command to start the terminal phase and log in to the remote host.

grammar

8 acdeffklrx Telnet [-] [- b < > host alias] [-e < out > characters] [- k < domain name >] [-l < user name >] [-n > < log file] [-s < service type >] [-x < > certification form] [host name or IP address < > communication port]Copy the code

Parameter Description: -8 Allows 8-bit character data, including input and output. -a Attempts to automatically log in to the remote system. -b< Host alias > Specifies the name of the remote host using the alias. -c does not read. Telnetrc files in the user’s exclusive directory. -d Enables the debugging mode. -e< Detach character > Sets detach character. -e Filters out detached characters. -f This parameter has the same effect as the “-f” parameter. -f When Kerberos V5 authentication is used, the authentication data of the local host can be uploaded to the remote host if this parameter is added. -k< domain name > When Kerberos authentication is used, this parameter is added to make the remote host adopt the specified domain name instead of the host domain name. -k Does not automatically log in to the remote host. -l< User name > Specifies the user name to log in to the remote host. -l Allows the output of 8-bit character data. -n< Record file > Specifies the file record information. -r Uses a user interface similar to the rlogin directive. -s < service type > Sets the TOS information required for Telnet connections. -x Indicates that the host supports data encryption. -x < Authentication Mode > Disables the specified authentication mode.

Example Log in to the remote host

Telnet 192.168.0.5Copy the code

** system management command **

1. The date command

Displays or sets the system date and time.

Command parameters:

-d< string > Displays the date and time indicated in the string. The string must be surrounded by double quotation marks. -s< string > Sets the date and time according to the string. The string must be surrounded by double quotation marks. -u Displays GMT. %H hours (00-23) %I hours (00-12) %M minutes (00-59) %s Total seconds. The starting time is 1970-01-01 00:00:00 UTC. %S seconds (in local usage) %a week. %A Full name of the week. %d Date (01-31). %D Date (including year, month and day). %m months (expressed as 01-12). %y The year (00-99). %Y Year (represented by four digits).Copy the code

Example: (1) Display the next day

Date +%Y%m%d --date="+1 day" // Displays the date of the next dayCopy the code

(2) Use the -d parameter

Date -d "Nov 22" This year November 22 is Wednesday date -d '2 weeks' Date -d 'Next Monday' date -d next-day +%Y%m%d date -d tomorrow +%Y%m%d date -d last-day +%Y%m%d Date -d yesterday +%Y%m%d date -d last-month +%Y%m Date -d next-month +%Y%mCopy the code

2. The free command

Displays system memory usage, including physical memory, interactive area memory (SWAP), and kernel buffer memory.

Command parameters:

-b Displays the memory usage in Byte. -k Displays the memory usage in KB. -m Displays the memory usage in MB. -g Displays the memory usage in GBCopy the code

Example: (1) Display memory usage

free
free -k
free -m 
Copy the code

(2) Display memory usage information in the form of summation

free -t 
Copy the code

(3) Periodically query the memory usage

free -s 10 
Copy the code

3. Kill command

Sends the specified signal to the corresponding process. Not specifying a model will send SIGTERM (15) to terminate the specified process. If the program cannot be terminated, the “-kill” parameter can be used, and the signal it sends is SIGKILL(9), which will force the process to end. You can use the ps command or the jobs command to view the process number. The root user can affect user processes. Non-root users can only affect their own processes.

Common parameters:

If no signal number parameter is added, the -l parameter lists all signal names. -A When processing the current process, the relationship between the command name and the process number is not restricted. -p Specifies that the kill command prints only the process number of the process, but does not send any signalCopy the code

Example: (1) use ps to find pro1, and then kill it

kill -9 $(ps -ef | grep pro1) 
Copy the code

4. The ps command

Ps is used to view the status of the current running process at a time. To obtain dynamic and continuous results, use top

On Linux, processes can be in five states: 1. Running (running or waiting in a run queue) 2. Interrupt (dormant, blocked, waiting for a condition to form or receive a signal) Non-interruptible (receive signal does not wake up and cannot run, process must wait until interrupt occurs) 4. Rigor mortis (the process has terminated, but the process descriptor exists until the parent releases the wait4() system call) 5. Stop (the process stops running after receiving SIGSTOP, SIGSTP, SIGTIN, and SIGTOU signals)

The ps tool identifies five status codes for processes:

D Uninterruptible sleep (usually IO) R Running runnable (on run queue) S Interrupting sleeping T Stopped or stopped Z Died a Defunct (" zombie ") in the processCopy the code

Command parameters:

-A Displays all processes. -A Displays all processes on the same terminal. C Displays process names. E Displays environment variablesCopy the code

Example: (1) Display all current process environment variables and relationships between processes

ps -ef 
Copy the code

(2) All processes are displayed

ps -A 
Copy the code

(3) Search a process with grep

ps -aux | grep apache 
Copy the code

(4) Find out the PID numbers associated with cron and Syslog services

ps aux | grep '(cron|syslog)' 
Copy the code

5. The RPM command

The Linux RPM command is used to manage a suite.

Redhat Package Manager (RPM) is a program used by Red Hat Linux distributions to manage various Linux packages. It is popular because it complies with GPL rules and has powerful and convenient functions. Gradually adopted by other distributions. The appearance of RPM suite management makes Linux easy to install and upgrade, which indirectly improves the applicability of Linux.

# to check the system comes with the JDK RPM - qa | grep JDK system at # delete JDK RPM -e -- nodeps view the JDK display RPM data # JDK installation - the ivh JDK 7 u80 - Linux - x64. RPMCopy the code

6. The top command

This section describes how to view information about processes that are running, including process IDS, memory usage, and CPU usage

Common parameters:

-c Displays the complete process command. -s Confidential mode -p < process number > Displays the specified process. -n < times > Displays the number of cyclesCopy the code

Example:

Top-14:06:23 Up 70 days, 16:44, 2 Users, Load Average: 1.25, 1.32, 1.35 Tasks: 206 total, 1 running, 205 sleeping, 0 stopped, 0 zombie Cpu(s): Sy us 5.9%, 3.4%, 0.0% ni, 90.4% id, wa, 0.0%, 0.0% hi 0.2% si, 0.0% st Mem: 32949016k total, 14411180k used, 18537836k free, 169884k buffers Swap: 32764556k total, 0k used, 32764556k free, 3612636k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 28894 root 22 0 1501m 405m 10m S 52.2 1.3 2534:16 javaCopy the code

The first five lines are the overall statistics area of the current system.

The first line contains the task queue information, which is the same as the result of the uptime command. The specific parameters are described as follows:

14:06:23 – The current system time

Up 70 days, 16:44 – The system has been running for 70 days, 16 hours and 44 minutes (well, I must shout that the system has not been restarted during this period!)

2 users – Currently, two users log in to the system

Load Average: 1.15, 1.42, 1.44 – The next three numbers of load Average are 1 minute, 5 minutes, and 15 minutes respectively.

The Load Average data is the number of active processes checked every five seconds and calculated by a specific algorithm. If this number is divided by the number of logical cpus, anything above 5 indicates that the system is overloaded.

The second line, Tasks – task (process), is described as follows:

The system currently has 206 processes, including 1 running, 205 sleeping, 0 stoped, and 0 zombie.

The third line, CPU status information, specific attributes are described as follows:

5.9% US - The percentage of CPU occupied by user space. 3.4% SY - The percentage of CPU occupied by kernel space. 0.0% NI - Percentage of CPU usage by processes whose priorities have changed 90.4% ID - Percentage of idle CPU 0.0% WA - Percentage of CPU usage by I/O wait 0.0% HI - Percentage of CPU usage by hard Interrupts (Hardware IRQ) 0.2% SI - Percentage of the CPU used by Software InterruptsCopy the code

Note: the CPU usage ratio is different from that of Windows. You need to understand the user space and kernel space of Linux system.

The fourth line, memory status, specific information is as follows:

32949016k total - total physical memory (32GB) 14411180k used - total memory in use (14GB) 18537836k free - total free memory (18GB) 169884k buffers - memory size of the cache (169 m)Copy the code

In line 5, swap swaps partition information. The details are described as follows:

32764556k total - total number of swap areas (32GB) 0k used - total number of used swap areas (0k) 32764556k free - total number of free swap areas (32GB) 3612636k cached - total number of cached swap areas (3.6GB)Copy the code

Sixth line, blank line.

The seventh line is below: The status monitoring of each process (task), and the item column information is described as follows:

PID - Process ID USER - Process owner PR - Process priority NI - Nice value. A negative value indicates a high priority. A positive value indicates a low priority. VIRT - Total virtual memory used by a process, in KB. VIRT=SWAP+RES RES - Size of the physical memory used by the process that has not been swapped out, in KB. RES=CODE+DATA SHR - Shared memory size (unit: KB) S - Process status. D= Uninterruptable sleep R= Running S= sleep T= Trace/Stop Z= zombie process %CPU - CPU TIME occupied since last update %MEM - Percentage of physical memory used by process TIME+ - Total CPU TIME used by process, Unit 1/100 second COMMAND - Process name (COMMAND name/COMMAND line)Copy the code

Top Interactive command

H Displays the help information about the top interactive command c Switches the command name and complete command line m Sorts by memory usage P Sorts by CPU usage percentage T Sorts by time/cumulative time W Writes the current Settings to the ~/. Toprc file o or O changes the display order of itemsCopy the code

7. Yum command

Yum (Yellow Dog Updater, Modified) is a Shell front-end package manager in Fedora and RedHat as well as SUSE.

Based on RPM package management, RPM packages can be automatically downloaded and installed from a specified server, and dependencies can be automatically handled. In addition, all dependent software packages can be installed at one time without tedious downloading and installation.

Yum provides concise and easy to remember commands for finding, installing, and removing one, a group, or even all packages.

Yum check-update 2 yum check-update 2 3. Run the yum install 4 command to install the specified software. Update only the specified software command: yum update 5. Run the yum list command to list all installable software packages. 6. Yum clean packages: clear the cache. Yum clean headers: clear the headers in the cache directory. Yum clean oldheaders: Headers yum clean, yum clean all (= yum clean packages; Yum clean oldheaders) : clears packages and oldheaders in the cache directory

Example Install PAM-devel

[root@www ~]# yum install pam-devel 
Copy the code

Backup compression command

1. Bzip2 command

Create *.bz2 zip file: bzip2 test.txt. Unzip the *.bz2 file: bzip2 -d test.txt.bz2

2. The gzip command

Create a *. Gz compressed file: gzip test.txt. Gz file: gzip -d test.txt.gz. Display the compression ratio: gzip -l *.gz.

3. The tar command

Used to compress and decompress files. Tar itself does not have compression function, only packaging function, about compression and decompression is to call other functions to complete.

Understand two concepts: packaging and compression. Packaging is to make a large number of files or directories into a total file; Compression is the process of turning a large file into a small file using some compression algorithms

Common parameters:

-u Adds changed and existing files to the compressed package. -x Extracts files from the compressed package. -t Displays the contents of the compressed file The compress decompression file -v displays the operation processCopy the code

For gZIP and Bzip2 compression:

Gz and. TGZ: gunzip filename.gz or gzip -d filename.gz Gz tar ZXVF filename.tar.gz bz2 Example: Decompress bzip2-z filename.tar. bz2: Bz2 or bzip -d filename.bz2: tar JCVF filename.tar.gz: tar JXVF filename.tar.bz2 bunzip filename.bz2 bunzip filename.bz2 bunzip -d filename.bz2Copy the code

Example: (1) Package all files into a tar package

Tar -cvf log.tar 1.log,2.log or tar -cvf log.*Copy the code

(2) Package all files and directories in /etc to a specified directory and use gz compression

tar -zcvf /tmp/etc.tar.gz /etc 
Copy the code

(3) Check the contents of the newly packed file (must add Z, because it is compressed using gzip)

tar -ztvf /tmp/etc.tar.gz 
Copy the code

/home/ etc, but not /home/dmtsai

tar --exclude /home/dmtsai -zcvf myfile.tar.gz /home/* /etc 
Copy the code

4. Unzip command

· Unzip the *. Zip file: unzip test.zip. · View the contents of the *. Zip file: unzip -l jasper. Zip.

Author: eet –

Link: ttps://www.eet-china.com/mp/a34260.h… Source: eet-china.com

supplement

How to learn Java, share two universal learning repositories:

1. Books:

codeGoogler/ProgramBooks

2: Video tutorial:

SpringBoot, Spring, Mybatis, Redis, RabbitMQ, SpringCloud, high concurrency (continuous update)

After brushing 200 questions and reaching the headlines, I was floating!