C language and CPP programming

Share C language /C++, data structures and algorithms, computer fundamentals, operating systems, etc

49 original content

The public,

This article consists of 2W+ words, respectively from the Linux overview, disk, directory, file, security, syntax level, actual, file management commands, document editing commands, disk management commands, network communication commands, system management commands, backup and compression commands and other aspects of the Linux common interview questions. Bookmark it and read it slowly.

1

Linux overview

1.1

What is a 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.

1.2

What’s 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. Linux is an open source operating system, you do not need to pay, you can use; 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 in addition to command line operation, there is a 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.

  5. 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!

1.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

1.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.

1.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. We can accomplish the transition from user space to kernel space in two ways:

1) System call;

2) Hardware interruption.

1.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 not.

  2. Under BASH, / character is the directory separator and \ is the escape character. Under DOS, / is used as the command parameter separator, and \ is the directory separator

  3. The 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.

1.7

Linux Boot process?

  1. After the host power-on self-check, load the BIOS hardware information.

  2. Read the boot files of the MBR (GRUB, LILO).

  3. Boot the Linux kernel.

  4. Run the first process init (process number is always 1).

  5. Enter the appropriate run level.

  6. Run the terminal and enter the user name and password.

1.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.

1.9

Interprocess communication used by Linux?

  • Pipes (PIPE), stream pipes (S_PIPE), Named pipes (FIFO)

  • Signal (signal)

  • The message queue

  • The Shared memory

  • A semaphore

  • The socket (socket)

1.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.

1.11

Is it helpful to install multiple desktop environments for 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.

1.12

What is interchange 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.

1.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.

1.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.

1.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.

1.16

What is CLI?

The command line interface (CLI) was the most widely used user interface before the graphical user interface (GUI) was popularized. It usually did not support the 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.

1.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.

1.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.

1.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.

2

Disk, directory, file

2.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.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 the root directory at the top:

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: where system applications are stored. /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: contains 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).

2.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.

2.4

What are hard links 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.

2.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.

3

security

3.1

What security work does a Linux system need to do after initialization?

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.

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 up that only the IP address of the office network can log in to the server (depending on the actual needs of the company). You can also install VPN and other software to connect only 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.

(1) Set the nginx_WAf module to prevent SQL injection.

(2) Start the Web service as WWW user, change the owner and owning group of the website directory to WWW

3.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.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

/ 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 a Shell script?

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

/ Syntax level /

What types of variables can you use 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 do I cancel a variable or unassign a variable?

The unset command is used to cancel variable or variable assignment. The syntax is as follows:

# unset < variable name >

How is the if syntax nested in Shell scripts?

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 for 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?

Basic syntax is as follows:

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

While loop syntax in Shell scripts?

Basic grammar:

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

The basic format of a 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)Copy the code

What is the break command used in Shell scripts?

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 does the continue command do in a 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 do I 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 do I 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 at the same time?

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

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

How do I test a file in a Shell script?

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

The Test USES

-d filename Returns true if the file exists and is a directory

-e File name Returns true if the file exists

-f file name Returns true if the file exists and is a normal file

-r file name Returns true if the file exists and is readable

-s File name Returns true if the file exists and is not empty

-w file name Returns true if the file exists and is writable

-x file name Returns true if the file exists and is executable

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 do you 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 problem

4.1

Check whether a file is a character device file, and if so, copy it to /dev.

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

4.2

Add a new group called class1, and then add 30 users belonging to this group with names of the form STDXX, where xx is 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

4.3

Write Shell program to automatically delete 50 accounts named stud1 to stud50?

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

4.4

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

5

In actual combat

5.1

How do I select a Linux OPERATING system version?

In general, desktop users prefer Ubuntu; RHEL or CentOS is preferred for the server. CentOS is preferred. According to specific requirements:

  • If security requirements are high, select Debian or FreeBSD.

  • Users who need advanced database services and E-mail network applications can choose SUSE.

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

  • 【 Key 】 According to the current situation, the vast majority of 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.

5.2

How to plan a Linux host, what are the steps

  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. Once you’re done, you need to decide how the system needs to be installed, which systems are installed by default, and how to do partitions.

  3. Which parameters of the system need to be optimized, which users need to be created, etc.

5.3

When the user feedback website access is slow, how to deal with?

What are the factors that can cause slow site access?

1. The egress bandwidth of the server is insufficient, and 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 go to the investigation?

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 to solve it?

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.

5.4

What are the methods for Tuning Linux performance?

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

6

File Management commands

6.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

Example:

(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

6.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: indicates the current user of a directory or file

G: current group of directories or files

O: a user or group other than the current user or group of a directory or file

A: All users and groups

Permission Code:

R: indicates the read permission. The value is 4

W: indicates the write permission. The value is 2

X: execution permission, represented by the number 1

– : indicates the deletion permission. The value is 0

S: Special permission

Example:

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

chmod a+x t.log

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

chmod u=r t.log -c

(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)

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

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

6.3

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 subdirectories

Example:

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

chown -c mail:mail log2012.log

(2) Change the file group

chown -c :mail t.log

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

chown -cR mail: test/

6.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 suggest

-r Replicates a directory and all items in the directory

-a The time of the copied file is the same as that of the original file

Example:

(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

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

cp -s a.txt link_a.txt

6.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

Example:

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

find -atime -2

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

find ./ -name ‘*.log’

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

find /opt -perm 777

(4) Search for files larger than 1K

find -size +1000c

(5) Find files equal to 1000 characters

find -size +1000c

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.6

A 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:

find -size +1000c

Example:

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

head 1.log -n 20

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

head -c 20 log2014.log

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

head -n -10 t.log

6.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

(2) View multiple files

less 1.log 2.log

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

6.8

Ln command

The function is to create a synchronous link for a file in another location. If this problem is needed in different directories, there is no need to create the same file for each directory. The link created by LN reduces disk usage.

Link classification: software link and hard link

Soft links:

1. Soft links exist in the form of paths. Similar to shortcuts in the Windows operating system

2. Soft links can cross file systems, but hard links cannot

3. Soft link Can link to a file name that does not exist

4. Soft links Link directories

Hard links:

1. Hard links exist in the form of file copies. But it doesn’t take up real space.

2. Do not create hard links for directories

3. A hard link 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 the previously established link

-S soft link (symbolic link)

-v Displays the detailed processing process

Example:

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

ln -sv source.log link.log

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

ln -v source.log link1.log

(3) Create soft links for directories

ln -sv /opt/soft/test/test3 /opt/soft/test/test5

6.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 rows to display)

-f excludes specific archival systems, such as proc

-r uses the regular expression as the search condition

Example:

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

locate pwd

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

locate /etc/sh

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

Locate -r ‘^/var._reason$’ (where Represents one character, _ represents multiple tasks; .* stands for any number of characters.

6.10

More orders

The function is similar to CAT. More will display page by page to facilitate users to read page by page. The most basic instruction is to press the space key to display the next page, and press the B key to display the back 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

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

ls -l | more -5

Press space to display the next 5 lines.

6.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

(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

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

mv -i log1.txt log2.txt

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

mv * .. /

6.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…

Example:

(1) Delete any.log files, and confirm one by one before deleting:

rm -i *.log

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

rm -rf test

(3) Delete files that start with -f

rm — -f*

6.13

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 rows > Number of rows to display (from back to front)

(1) Loop reading gradually increasing file content

Ping 127.0.0.1 > ping.log &

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

Tail -f ping.log (Viewing logs)

6.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 Change 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

6.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:

6.16

Whereis command

The whereis command can only be used to search for program names, and only binary files (parameter -b), man description files (parameter -m), and source code files (parameter -s) are searched. 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

(2) Locate the source file

whereis -s locate

(3) Find the help file of LCOate

whereis -m locate

6.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.

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.

Example:

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

which ls

(2) Which

which which

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)

View the current PATH configuration:

echo $PATH

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

7

Document editing command

7.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

Common parameters:

-a n –after-context Displays n lines after matching characters

-b n –before-context Displays the first n lines of a matching character

-c n –context Displays n lines before and after the matching character

-c –count Counts the number of columns that match the style

-i ignores case

-l Lists only the names of files whose content matches the specified style

-f Reads the keyword from the file

-n Displays the number of lines in the file containing the matched content

-r Recursively searches for folders

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

(2) Find the specified number of processes

ps -ef | grep svn -c

(3) Read keywords from files

cat test1.txt | grep -f key.log

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

grep -lR ‘^grep’ /tmp

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

grep ‘^[^x]’ test.txt

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

grep -E ‘ed|at’ test.txt

7.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..

Command parameters:

-c Indicates the number of bytes

-l Indicates the number of rows

-m Indicates the number of characters

-w Counts the number of words. A word is defined as a string separated by whitespace, tabs, or newline characters

Example:

(1) Number of lines, words, bytes, file name

wc text.txt

Results:

7 8 70 test.txt

(2) Count the number of lines of output results

cat test.txt | wc -l

8

Disk Management Commands

8.1

The CD command

Syntax of the CD changeDirectory command:

CD [Directory name]

Switch the current directory to dirName.

Example:

(1) Enter the desired directory

cd /

(2) Go to the Home directory

cd ~

(3) Enter the last working path

cd –

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

cd ! $

8.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 manner

-i Displays inode information

The -k block is 1024 bytes

-l Displays only local disks

-t Lists the file system types

Example:

(1) Display the disk usage

df -l

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

df -haT

8.3

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]

Common parameters:

-a Displays the sizes 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 only the total number

-c or –total Displays the total of all directories or files in addition to the size of individual directories or files

Example:

(1) Display the size of folders and subfolders in a readable way

du -h scf/

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

du -ah scf/

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

du -hc test/ scf/

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

du -hc –max-depth=1 scf/

8.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 hiding files

Ls minus A is listed divided by. And.. Other files of

Ls-r in reverse order

Ls -t Sort by file modification time

Ls -s sorts by file size

Ls -h is displayed in a readable size

Ls -l displays detailed information about a file, such as its permission, owner, and size, in addition to the file name

Example:

(1) Sort files in reverse order by time according to easy to read mode, and display file details

ls -lhrt

(2) Display file details in reverse order by size

ls -lhrt

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

ls -l t*

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

ls | sed “s:^:pwd/:”

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

find $pwd -maxdepth 1 | xargs ls -ld

8.5

The mkdir command

The mkdir command is used to create a folder.

Available options:

-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

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

mkdir -p /tmp/test/t1/t

8.6

The PWD command

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

Example:

(1) View the current path

pwd

(2) View the actual path of the soft link

pwd -P

8.7

Rmdir commands

To delete one or more subdirectory items from a directory, you must have the write permission on the parent directory when deleting a directory. Note: You cannot delete a non-empty directory

Example:

Rmdir -p parent/child/child11 rmdir -p parent/child/child11

9

Network communication command

9.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.

9.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

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

9.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]

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

9.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

9.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 允许使用8位字符资料,包括输入与输出。
    -a 尝试自动登入远端系统。
    -b<主机别名> 使用别名指定远端主机名称。
    -c 不读取用户专属目录里的.telnetrc文件。
    -d 启动排错模式。
    -e<脱离字符> 设置脱离字符。
    -E 滤除脱离字符。
    -f 此参数的效果和指定"-F"参数相同。
    -F 使用Kerberos V5认证时,加上此参数可把本地主机的认证数据上传到远端主机。
    -k<域名> 使用Kerberos认证时,加上此参数让远端主机采用指定的领域名,而非该主机的域名。
    -K 不自动登入远端主机。
    -l<用户名称> 指定要登入远端主机的用户名称。
    -L 允许输出8位字符资料。
    -n<记录文件> 指定文件记录相关信息。
    -r 使用类似rlogin指令的用户界面。
    -S<服务类型> 设置telnet连线所需的IP TOS信息。
    -x 假设主机有支持数据加密的功能,就使用它。
    -X<认证形态> 关闭指定的认证形态。
```

```
实例:
```

登录远程主机

```
# 登录IP为 192.168.0.5 的远程主机
telnet 192.168.0.5
```

  

**_10_**

  

**系统管理命令**

**_10.1_**

  

****date 命令****

显示或设定系统的日期与时间。

命令参数:

  

\-d<字符串> 显示字符串所指的日期与时间。字符串前后必须加上双引号。

\-s<字符串> 根据字符串来设置日期与时间。字符串前后必须加上双引号。

\-u 显示 GMT。

%H 小时(00-23)

%I 小时(00-12)

%M 分钟(以 00-59 来表示)

%s 总秒数。起算时间为 1970-01-01 00:00:00 UTC。

%S 秒(以本地的惯用法来表示)

%a 星期的缩写。

%A 星期的完整名称。

%d 日期(以 01-31 来表示)。

%D 日期(含年月日)。

%m 月份(以 01-12 来表示)。

%y 年份(以 00-99 来表示)。

%Y 年份(以四位数来表示)。

实例:

(1)显示下一天

date +%Y%m%d --date="+1 day" //显示下一天的日期

(2)-d 参数使用

date -d "nov 22" 今年的 11 月 22 日是星期三

date -d '2 weeks' 2 周后的日期

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%m(下个月是几月)

**_10.2_**

  

****free 命令****

显示系统内存使用情况,包括物理内存、交互区内存(swap)和内核缓冲区内存。

命令参数:

  

\-b 以 Byte 显示内存使用情况

\-k 以 kb 为单位显示内存使用情况

\-m 以 mb 为单位显示内存使用情况

\-g 以 gb 为单位显示内存使用情况

\-s<间隔秒数> 持续显示内存

\-t 显示内存使用总合

实例:

(1)显示内存使用情况

```
free
free -k
free -m
```

(2)以总和的形式显示内存的使用信息

```
free -t
```

(3)周期性查询内存使用情况

```
free -s 10
```

  

**_10.3_**

  

****kill 命令****

发送指定的信号到相应进程。不指定型号将发送 SIGTERM(15)终止指定进程。如果任无法终止该程序可用"-KILL" 参数,其发送的信号为 SIGKILL(9) ,将强制结束进程,使用 ps 命令或者 jobs 命令可以查看进程号。root 用户将影响用户的进程,非 root 用户只能影响自己的进程。

常用参数:

  

\-l 信号,若果不加信号的编号参数,则使用“-l”参数会列出全部的信号名称

\-a 当处理当前进程时,不限制命令名和进程号的对应关系

\-p 指定 kill 命令只打印相关进程的进程号,而不发送任何信号

\-s 指定发送信号

\-u 指定用户

实例:

(1)先使用 ps 查找进程 pro1,然后用 kill 杀掉

kill -9 $(ps -ef | grep pro1)

**_10.4_**

  

****4\. ps 命令****

ps(process status),用来查看当前运行的进程状态,一次性查看,如果需要动态连续结果使用 top

linux 上进程有 5 种状态:

  

> 1.  运行(正在运行或在运行队列中等待)
>     
> 2.  中断(休眠中, 受阻, 在等待某个条件的形成或接受到信号)
>     
> 3.  不可中断(收到信号不唤醒和不可运行, 进程必须等待直到有中断发生)
>     
> 4.  僵死(进程已终止, 但进程描述符存在, 直到父进程调用 wait4()系统调用后释放)
>     
> 5.  停止(进程收到 SIGSTOP, SIGSTP, SIGTIN, SIGTOU 信号后停止运行运行)
>     

ps 工具标识进程的 5 种状态码:

  

D 不可中断 uninterruptible sleep (usually IO)

R 运行 runnable (on run queue)

S 中断 sleeping

T 停止 traced or stopped

Z 僵死 a defunct (”zombie”) process

命令参数:

  

\-A 显示所有进程

a 显示所有进程

\-a 显示同一终端下所有进程

c 显示进程真实名称

e 显示环境变量

f 显示进程间的关系

r 显示当前终端运行的进程

\-aux 显示所有包含其它使用的进程

实例:

(1)显示当前所有进程环境变量及进程间关系

ps -ef

(2)显示当前所有进程

ps -A

(3)与 grep 联用查找某进程

ps -aux | grep apache

(4)找出与 cron 与 syslog 这两个服务有关的 PID 号码

ps aux | grep '(cron|syslog)'

**_10.5_**

  

****rpm 命令****

Linux rpm 命令用于管理套件。

rpm(redhat package manager) 原本是 Red Hat Linux 发行版专门用来管理 Linux 各项套件的程序,由于它遵循 GPL 规则且功能强大方便,因而广受欢迎。逐渐受到其他发行版的采用。RPM 套件管理方式的出现,让 Linux 易于安装,升级,间接提升了 Linux 的适用度。

```
# 查看系统自带jdk
rpm -qa | grep jdk
# 删除系统自带jdk
rpm -e --nodeps 查看jdk显示的数据
# 安装jdk
rpm -ivh jdk-7u80-linux-x64.rpm
```

  

**_10.6_**

  

****top 命令****

显示当前系统正在执行的进程的相关信息,包括进程 ID、内存占用率、CPU 占用率等

常用参数:

  

\-c 显示完整的进程命令

\-s 保密模式

\-p <进程号> 指定进程显示

\-n <次数>循环显示次数

实例:

```
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): 5.9%us, 3.4%sy, 0.0%ni, 90.4%id, 0.0%wa, 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 java
```

  

前五行是当前系统情况整体的统计信息区。第一行,任务队列信息,同 uptime 命令的执行结果,具体参数说明情况如下:

14:06:23 — 当前系统时间

up 70 days, 16:44 — 系统已经运行了 70 天 16 小时 44 分钟(在这期间系统没有重启过的吆!)

2 users — 当前有 2 个用户登录系统

load average: 1.15, 1.42, 1.44 — load average 后面的三个数分别是 1 分钟、5 分钟、15 分钟的负载情况。

load average 数据是每隔 5 秒钟检查一次活跃的进程数,然后按特定算法计算出的数值。如果这个数除以逻辑 CPU 的数量,结果高于 5 的时候就表明系统在超负荷运转了。

第二行,Tasks — 任务(进程),具体信息说明如下:

系统现在共有 206 个进程,其中处于运行中的有 1 个,205 个在休眠(sleep),stoped 状态的有 0 个,zombie 状态(僵尸)的有 0 个。

第三行,cpu 状态信息,具体属性说明如下:

```
5.9%us — 用户空间占用CPU的百分比。
3.4% sy — 内核空间占用CPU的百分比。
0.0% ni — 改变过优先级的进程占用CPU的百分比
90.4% id — 空闲CPU百分比
0.0% wa — IO等待占用CPU的百分比
0.0% hi — 硬中断(Hardware IRQ)占用CPU的百分比
0.2% si — 软中断(Software Interrupts)占用CPU的百分比
```

备注:在这里CPU的使用比率和windows概念不同,需要理解linux系统用户空间和内核空间的相关知识!

第四行,内存状态,具体信息如下:  

```
32949016k total — 物理内存总量(32GB)
14411180k used — 使用中的内存总量(14GB)
18537836k free — 空闲内存总量(18GB)
169884k buffers — 缓存的内存量 (169M)
```

第五行,swap交换分区信息,具体信息说明如下:

```
32764556k total — 交换区总量(32GB)
0k used — 使用的交换区总量(0K)
32764556k free — 空闲交换区总量(32GB)
3612636k cached — 缓冲的交换区总量(3.6GB)
```

第六行,空行。

第七行以下:各进程(任务)的状态监控,项目列信息说明如下:

```
PID — 进程id
USER — 进程所有者
PR — 进程优先级
NI — nice值。负值表示高优先级,正值表示低优先级
VIRT — 进程使用的虚拟内存总量,单位kb。VIRT=SWAP+RES
RES — 进程使用的、未被换出的物理内存大小,单位kb。RES=CODE+DATA
SHR — 共享内存大小,单位kb
S — 进程状态。D=不可中断的睡眠状态 R=运行 S=睡眠 T=跟踪/停止 Z=僵尸进程
%CPU — 上次更新到现在的CPU时间占用百分比
%MEM — 进程使用的物理内存百分比
TIME+ — 进程使用的CPU时间总计,单位1/100秒
COMMAND — 进程名称(命令名/命令行)
```

  

**_10.7_**

  

****yum 命令****

yum( Yellow dog Updater, Modified)是一个在 Fedora 和 RedHat 以及 SUSE 中的 Shell 前端软件包管理器。

基於 RPM 包管理,能够从指定的服务器自动下载 RPM 包并且安装,可以自动处理依赖性关系,并且一次安装所有依赖的软体包,无须繁琐地一次次下载、安装。

yum 提供了查找、安装、删除某一个、一组甚至全部软件包的命令,而且命令简洁而又好记。

1.列出所有可更新的软件清单命令:yum check-update

2.更新所有软件命令:yum update

3.仅安装指定的软件命令:yum install

4.仅更新指定的软件命令:yum update

5.列出所有可安裝的软件清单命令:yum list

6.删除软件包命令:yum remove

7.查找软件包 命令:yum search

 8.清除缓存命令:  
 yum clean packages: 清除缓存目录下的软件包  
 yum clean headers: 清除缓存目录下的 headers  
 yum clean oldheaders: 清除缓存目录下旧的 headers  
 yum clean, yum clean all (= yum clean packages; yum clean oldheaders) :清除缓存目录下的软件包及旧的headers  
  

实例

安装 pam-devel

**_11_**

  

**备份压缩命令**

**_11.1_**

  

****bzip2 命令****

创建 \*.bz2 压缩文件:bzip2 test.txt 。

解压 \*.bz2 文件:bzip2 -d test.txt.bz2 。

**_11.2_**

  

****gzip 命令****

创建一个 \*.gz 的压缩文件:gzip test.txt 。

解压 \*.gz 文件:gzip -d test.txt.gz 。

显示压缩的比率:gzip -l \*.gz 。

**_11.3_**

  

****tar 命令****

用来压缩和解压文件。tar 本身不具有压缩功能,只具有打包功能,有关压缩及解压是调用其它的功能来完成。

弄清两个概念:打包和压缩。打包是指将一大堆文件或目录变成一个总的文件;压缩则是将一个大的文件通过一些压缩算法变成一个小文件

常用参数:

  

```
-c 建立新的压缩文件
-f 指定压缩文件
-r 添加文件到已经压缩文件包中
-u 添加改了和现有的文件到压缩包中
-x 从压缩包中抽取文件
-t 显示压缩文件中的内容
-z 支持gzip压缩
-j 支持bzip2压缩
-Z 支持compress解压文件
-v 显示操作过程
```

有关 gzip 及 bzip2 压缩:

  

gzip

实例:

压缩 gzip fileName .tar.gz 和.tgz

解压:gunzip filename.gz 或 gzip -d filename.gz

对应:tar zcvf filename.tar.gz tar zxvf filename.tar.gz

bz2

实例:

压缩 bzip2 -z filename .tar.bz2

解压:bunzip filename.bz2 或 bzip -d filename.bz2

对应:tar jcvf filename.tar.gz

解压:tar jxvf filename.tar.bz2

实例:

(1)将文件全部打包成 tar 包

```
tar -cvf log.tar 1.log,2.log 或tar -cvf log.*
```

  
(2)将 /etc 下的所有文件及目录打包到指定目录,并使用 gz 压缩

  

```
tar -zcvf /tmp/etc.tar.gz /etc
```

  

(3)查看刚打包的文件内容(一定加z,因为是使用 gzip 压缩的)

  

```
tar -ztvf /tmp/etc.tar.gz
```

(4)要压缩打包 /home, /etc ,但不要 /home/dmtsai

  

```
tar --exclude /home/dmtsai -zcvf myfile.tar.gz /home/* /etc
```

  

**_11.4_**

  

****4\. unzip 命令****

解压 \*.zip 文件:unzip test.zip

查看 \*.zip 文件的内容:unzip -l jasper.zip

来源| ThinkWon 链接| thinkwon.blog.csdn.net

![C语言与CPP编程](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a649b47601dc45609275b5d0c09f6887~tplv-k3u1fbpfcp-zoom-1.image)

**C语言与CPP编程**

分享C语言/C++,数据结构与算法,计算机基础,操作系统等

49篇原创内容

公众号

> 本文使用 [文章同步助手](https://juejin.cn/post/6940875049587097631) 同步
Copy the code