Reading guide : This article summarizes the latest Linux Interview questions , near 3 swastika , about 100 Problem , Share here , Hopefully that helped .

One 、Linux summary

1. What is? Linux

Linux Is a set of free use and free dissemination classes Unix operating system , It's based on POSIX and Unix Multiple users of 、 multitasking 、 Support for multithreading and multithreading CPU Operating system of . It can run the main Unix Tool software 、 Application and network protocols . It supports 32 Bit and 64 Bit hardware .Linux Inherited Unix Design idea with network as the core , It is a multi-user network operating system with stable performance .

 

2. Unix and Linux What's the difference? ?

Linux and Unix Are powerful operating systems , Are widely used server operating systems , There are many similarities , Some people even mistakenly believe that Unix and Linux The operating system is the same , However , This is not the case , Here's the difference between the two .

1. Open source
Linux It's an open source operating system , There is no need to pay , You can use ;Unix Is a source of intellectual property protection of the traditional commercial software , Use requires payment and authorization .

2. Cross-platform sex
Linux The operating system has good cross platform performance , It can run on a variety of hardware platforms ;Unix The cross platform performance of the operating system is weak , Most of them need to be used together with hardware .

3. Visual interface
Linux Except for command line operations , And the form management system ;Unix It's just a command line system .

4. Hardware environment
Linux The operating system requires less hardware , The installation method is easier to master ;Unix The hardware requirements are more stringent , It is difficult to install .

5. User groups
Linux There is a wide range of users , Both individuals and businesses can use ;Unix The user group is relatively narrow , Most of them are used by large enterprises with high security requirements , Like a bank 、 Telecommunication department, etc , perhaps Unix Hardware manufacturers use , Such as Sun etc. .

 

Compared with Unix operating system ,Linux The operating system is more popular with computer enthusiasts , The main reason is Linux The operating system has Unix All the functions of the operating system , And can be used in ordinary PC All of them are implemented on the computer Unix characteristic , Open source free features , It's easier to popularize !

3. What is? Linux kernel ?

Linux The core of the system is the kernel . The kernel controls all the hardware and software on the computer system , Allocate hardware when necessary , And execute the software as needed .

    System memory management
    Application Management
    Hardware device management
    File system management

4. Linux What are the basic components of ?

Just like any other typical operating system ,Linux Having all these components : kernel ,shell and GUI, System utilities and Applications .Linux The advantage over other operating systems is that each aspect comes with other features , All the code can be downloaded for free .

 

5. Linux Architecture of

In a big way ,Linux The architecture can be divided into two parts :


User space (User Space) : User space includes user applications (User Applications)、C library (C Library) .

 

Kernel space (Kernel Space) : Kernel space includes system call interface (System Call Interface)、 kernel (Kernel)、 Platform architecture related code (Architecture-Dependent Kernel Code) .

Why? Linux The reason why architecture should be divided into user space and kernel space ?

1. modern CPU Different working modes are realized , In different modes CPU The instructions that can be executed are different from the registers that are accessed .
2. Linux from CPU From the angle of , To protect the security of the kernel , Divide the system into two parts .

User space and kernel space are two different states of program execution , We can transfer user space to kernel space in two ways :1) system call ;2) Hardware interrupt .
 

6. BASH and DOS What is the basic difference between ?

BASH and DOS The main difference between consoles is 3 In terms of :

1. BASH Commands are case sensitive , and DOS Orders do not distinguish ;
2. stay BASH Next ,/ character It's the directory separator ,\ As escape character . stay DOS Next ,/ Used as a command parameter separator ,\ It's the directory separator
3. OS Follow the conventions in the named file , namely 8 A character file name followed by a dot , extension 3 Characters .BASH We didn't follow such a routine .

7. Linux Startup process ?

    1、 Host power on self test , load BIOS Hardware information .
    2、 Read MBR The boot file for (GRUB、LILO).
    3、 guide Linux kernel .
    4、 Run the first process init ( The process number is always 1 ).
    5、 Enter the corresponding operation level .
    6、 Running Terminal , Enter your username and password .

8. Linux The default run level of the system ?
 

    To turn it off .
    Single user mode .
    Multi user mode of character interface ( Network not supported ).
    Multi user mode of character interface .
    Unallocated use .
    The multi-user mode of graphical interface .
    restart .

 

9. Linux The inter process communication mode used ?

 

  • The Conduit (pipe)、 Flow pipe (s_pipe)、 Famous pipeline (FIFO).

  • The signal (signal) .

  • Message queue .

  • Shared memory .

  • Semaphore .

  • Socket (socket) .

 

10. Linux What are the system log files ?

Here's the important thing  /var/log/messages  Log files .

This log file is a summary of many process log files , It can be seen from this document that any *** Attempted or successful ***. in addition , If fat friend's system has ELK The logs are collected centrally , It will also be collected .

11. Linux Does it help to install multiple desktop environments ?

Usually , A desktop environment , Such as KDE or Gnome, Enough to run without problems . Although the system allows switching from one environment to another , But it's a priority for users . Some programs work in one environment and can't work in another , So it can also be seen as a factor in choosing which environment to use .

 

12. What is swap space ?

The exchange space is Linux A certain amount of space to use , Used to temporarily save some concurrent programs . When RAM When there is not enough memory to hold all the programs being executed , That's what happens .

 

13. What is? root account

root An account is like an administrator , Allows you to take full control of the system . You can create and maintain user accounts here , Assign different permissions to each account . Every installation Linux All are default accounts .

 

14. What is? LILO?

LILO yes Linux Boot loader for . It is mainly used to put Linux The operating system is loaded into main memory , So that it can start running .

 

15. What is? BASH?

BASH yes Bourne Again SHell Abbreviation . It consists of Steve Bourne To write , As primitive Bourne Shell( from / bin / sh Express ) substitute . It combines the original version of Bourne Shell All functions of , And other functions , Make it easier to use . after that , It has been adapted to run Linux The default of most systems is shell.

 

16. What is? CLI?

Command line interface ( English **:command-line interface**, abbreviation ]:CLI) It is the most widely used user interface before the popularity of GUI , It generally does not support a mouse , The user enters instructions through the keyboard , After the computer receives the instruction , enforce . Others call it character user interface (CUI).

It is commonly believed , Command line interface (CLI) There's no GUI (GUI) So convenient for users to operate . because , Command line interface software usually requires the user to memorize the commands to operate , however , Because of its own characteristics , Command line interface is more economical than graphical user interface . On the premise of memorizing the order , Using a command-line interface is often faster than using a graphical user interface . therefore , Graphical user interface in the operating system , Both have optional command-line interfaces .

 

17. What is? GUI?

Graphical user interface (Graphical User Interface, abbreviation GUI, Also called graphical user interface ) It refers to the computer operation user interface displayed in graphic mode .

Graphical user interface (GUI) is an interface display format for communication between people and computers , Allows users to manipulate icons or menu options on the screen using input devices such as a mouse , To select the command 、 Call file 、 Start a program or perform other routine tasks . Compared to a character interface that uses keyboard input text or character commands to perform routine tasks , GUI has many advantages .

 

18. What are the advantages of open source ?

Open source allows you to put software ( Including source code ) Free distribution to anyone interested . then , People can add features , You can even debug and correct errors in the source code . They can even make it work better , And then again freely redistribute these enhanced source code . This ultimately benefits everyone in the community .

 

19. GNU What is the importance of the project ?

This so-called free software movement has many advantages , For example, you can run the program freely and learn and modify it according to your needs . It also allows you to redistribute copies of the software to others , And the freedom to improve software and release it to the public .

 

Two 、 disk 、 Catalog 、 file

 

1. Simple Linux file system ?

stay Linux Operating system , All resources managed by the operating system , For example, network interface card 、 disc drive 、 The printer 、 Input/output device 、 A normal file or directory is considered a file .

That is to say Linux There is an important concept in the system **: Everything is a document **. Actually, this is Unix A manifestation of philosophy , and Linux It's rewriting Unix And come , So this concept is passed down . stay Unix In the system , Think of all resources as documents , Including hardware equipment .UNIX The system regards every hardware as a file , Usually referred to as device files , In this way, users can access the hardware by reading and writing files .

Linux Support 5 File types , As shown in the figure below : file type

 

 

2. Linux What is the directory structure of ?

This problem , I don't usually ask . It's more about actual use , Need to know .

Linux The structure of the file system is distinct , It's like an upside down tree , The top level is its root directory :
Linux Directory structure of

Common catalog description :

  • /bin: Store binary executables (ls,cat,mkdir etc. ), Common commands are usually here ;

  • /etc: Store system management and configuration files ;

  • /home: The root directory where all user files are stored , Is the base point of the user's home directory , Such as user user The home directory of /home/user, It can be used ~user Express ;

  • **/usr **: For storing system applications /opt: Location of optional application packages for additional installation . In general , We can tomcat And so on are all installed here ;

  • /proc: Virtual file system directory , Is a mapping of system memory . You can directly access this directory to get system information ;

  • /root: The super user ( System administrator ) The home directory ( The privileged class o);

  • /sbin: Store binary executables , Only root Ability to visit . Here are the system level management commands and programs used by the system administrator . Such as ifconfig etc. ;

  • /dev: Used to store equipment files ;

  • /mnt: System administrator install temporary file system installation point , The system provides this directory for users to temporarily mount other file systems ;

  • /boot: Store all kinds of files used for system boot ;

  • **/lib **: Storage and system operation related library files ;

  • /tmp: Used to store all kinds of temporary documents , It's a public temporary file storage point ;

  • /var: Files used to store data that needs to be changed at run time , It is also the overflow area of some large files , For example, log files of various services ( System startup log, etc .) etc. ;

  • /lost+found: This directory is usually empty , The system shut down abnormally and left “ homeless ” The file of (windows What's the next name .chk) Right here .


3. What is? inode ?

Generally speaking , The interview doesn't ask inode . however inode It's an important concept , Is to understand Unix/Linux The basis of file system and hard disk storage .

understand inode, Start with file storage .

The files are stored on the hard disk , The smallest unit of hard disk storage is called " A sector "(Sector). Each sector stores 512 byte ( amount to 0.5KB).

When the operating system reads the hard disk , Not sector by Sector , That's inefficient , Instead, read multiple sectors continuously at once , Read one at a time " block "(block). This is made up of multiple sectors " block ", Is the smallest unit of file access ." block " Size , The most common is 4KB, Eight in a row sector Form a block.

File data is stored in " block " in , So obviously , We also have to find a place to store the meta information of the file , For example, the creator of the file 、 Date the file was created 、 File size and so on . This area of file meta information is called inode, The Chinese translation is " The index node ".

Every file has a corresponding inode, It contains some information about the file .

sketch Linux File system pass i The process of transforming the logical structure and physical structure of a file by a node ?

Generally speaking , The interviewer is not very good at asking this question .

Linux adopt inode The node table transforms the logical and physical structure of the file .

· inode Node is a 64 Byte long table , Table contains information about the file , Where is the size of the file 、 File owner 、 Important information such as the access permission method of the file and the type of the file . stay inode The most important part of the node table is the disk address table . In the disk address table 13 Block number , The file will read the corresponding blocks in the order in which they appear in the disk address table .
· Linux The file system passes the inode The node is connected to the file name , When the file needs to be read , The file system looks up the item corresponding to the file name in the current directory table , The corresponding inode Node number , Through the inode The disk address table of the node connects the physical blocks of the scattered files into the logical structure of the files .

4. What are hard links and soft links ?

1) Hard links

because Linux Under the file is through the index node (inode) To identify documents , Hard links can be thought of as a pointer , Pointer to the file inode , The system doesn't reallocate it inode . Every time you add a hard link , Add the number of links to the file 1 .

Insufficient :1) You can't link between files in different file systems ;2) Only super users can create hard links for directories .

2) Soft link

Soft links overcome the shortcomings of hard links , There are no file system restrictions , Any user can create symbolic links to directories . So now it's more widely used , It has more flexibility , It can even span different machines 、 Different networks link files .

 

Insufficient : Because the link file contains the path information of the original file , So when the original file is moved from one directory to another , Visit the link file again , The system can't find it , Hard links don't have this flaw , Move as much as you want ; It also requires the system to allocate extra space for creating new inodes and saving the original file path .

Under the actual situation , Basically using soft links . The differences are summarized as follows :

·  Hard links cannot cross partitions , Software chains can span partitions .
·  Hard links point to a inode node , And soft link is to create a new inode node .
·  Delete hard link files , The original file will not be deleted , Delete soft link file , Will delete the original file .

5. RAID What is it? ?

RAID The full name is redundant array of independent disks (Redundant Array of Independent Disks), The basic idea is to combine multiple relatively inexpensive hard drives , Become a hard disk array group , Make the performance reach or even surpass one expensive 、 A huge hard disk .RAID It's usually used on server computers , Use identical hard disks to form a logical sector , So the operating system will only treat it as a hard disk .

RAID Divided into different levels , Each level makes different trade-offs in data reliability and read-write performance . in application , You can choose different ones according to your actual needs RAID programme .

Of course , Because a lot of companies use cloud services , It's hard to reach RAID The concept , More likely it's a normal cloud disk 、SSD The concept of yunpan sauce purple .

 

3、 ... and 、 Security

 

1. a Linux What security work should be done after the system initializes the environment ?

    1、 Add normal user login , prohibit root The user login , change SSH Port number .

        modify SSH Ports don't have to be absolute . Of course , If you want to be exposed to the Internet , It is suggested that .l

    2、 The server logs in with a key , No password login .

    3、 Turn on the firewall , close SElinux , Set corresponding firewall rules according to business requirements .

    4、 loading fail2ban This prevents SSH Brute force Software .

    5、 Only the company's office network is allowed to export IP Can log in to the server ( Look at the actual needs of the company )

        You can also install *** Such as software , Only connections are allowed *** To the server .

    6、 Modify the number of historical command records to 10 strip .

    7、 Only servers that need access to the Internet are allowed , Everything else is forbidden .

    8、 Do a good job in software protection .
        8.1 Set up nginx_waf Modules prevent SQL Inject .
        8.2 hold Web Service usage www User start , Change the owner and group of the site directory to www .

2. What do you mean CC ***? What do you mean DDOS ***?

CC ***, Mainly for *** Page , Simulate multiple users visiting your page constantly , So that your system resources are exhausted .

DDOS ***, The Chinese name is distributed denial of service ***, It refers to the combination of multiple computers with the help of server technology *** platform , To launch... Against one or more targets DDOS ***.

***, That is, through a large number of legitimate requests to occupy a large number of network resources , In order to achieve the purpose of paralyzing the network .

How to prevent CC *** and DDOS ***?

prevent CC、DDOS ***, These can only be done with hardware firewall traffic cleaning , take *** Traffic leads to black holes .

Flow cleaning this piece , Mainly to buy ISP The defense of service providers *** You can have a good service , The computer room generally has free flow , We usually buy services , After all *** It won't last long .

3. What is website database Injection ?

Due to the uneven level and experience of programmers , Most programmers write code , There is no judgment on the validity of user input data .

 

There are security risks in the application . Users can submit a database query code , According to the result returned by the program , Get some data he wants to know , That's what's called SQL Inject .

 

SQL Inject , It's from normal WWW Port access , And on the surface, it looks like a normal Web There's no difference in page access , If the administrator is not used to checking the log , May be *** Not for a long time .

How to filter and prevent ?
Database web page side injection of this , Consider using nginx_waf Filtering and prevention .

 

Shell


1. Shell What is a script ?

One Shell Script is a text file , Contains one or more commands . As system administrator , 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 tasks .

- What is default login Shell ?

stay Linux operating system ,"/bin/bash" Is the default login Shell, It's assigned when the user is created .

Use chsh The command can change the default Shell . An example is shown below :

 

## chsh < user name > -s < new shell>## chsh ThinkWon -s /bin/sh

 


- stay Shell Script , How to write comments ?

Annotations can be used to describe what a script can do and how it works . Comment each line with # start . Examples are as follows :

 

#!/bin/bash## This is a commandecho “I am logged in as $USER”

 


2. Grammar level

 

- Can be in Shell What types of variables are used in the script ?

stay Shell Script , We can use two types of variables :

System defined variables : System variables are created by the system itself . These variables are usually made up of capital letters , Can pass set Command view .

User defined variables : User variables are generated and defined by system users , The value of the variable can be passed through the command "echo $< Variable name >" see .

- Shell Script $? What is the purpose of the mark ?

Writing a Shell Script time , If you want to check if the previous command was executed successfully , stay if Use in condition $? You can check the end state of the previous command .

·  If the end state is 0 , Indicates that the previous command was executed successfully . for example : 

 

  [email protected]:~## ls /usr/bin/shar    /usr/bin/shar    [email protected]:~## echo $?    0

 


·  If the end state is not 0, Description command execution failed . for example :   

 

 [email protected]:~## ls /usr/bin/share    ls: cannot access /usr/bin/share: No such file or directory    [email protected]:~## echo $?    2

 


- Bourne Shell(bash) What are the special variables in ?

The following table lists Bourne Shell Special variables set for the command line .

 

 Built in variables      explain $0     The name of the script on the command line $1     The first command line argument $2     The second command line argument …..    …….$9     The ninth command line argument $##     Number of command line arguments $*     All command line arguments , Space off 

 


- How to cancel a variable or a variable assignment ?

unset The command is used to cancel a variable or to cancel the assignment of a variable . The syntax is shown below :

 

## unset < Variable name >

 


- Shell Script if How syntax is nested ?

 

if [  Conditions  ]then command 1 command 2…..elseif [  Conditions  ]then command 1 command 2….else command 1 command 2…..fifi

 


- stay Shell How to compare two numbers in the script ?

stay if-then Use the test command ( -gt etc. ) To compare two numbers . for example :

 

#!/bin/bashx=10y=20if [ $x -gt $y ]thenecho “x is greater than y”elseecho “y is greater than x”fi

 


- Shell Script case Sentence syntax ?

The basic grammar is as follows :

 

case  Variable  in value 1) command 1 command 2….. Finally order !! value 2) command 1 command 2…… Finally order ;;esac

 


Shell Script for Cyclic grammar ?

The basic grammar is as follows :-

 

for  Variable  in  Loop list do command 1 command 2…. Finally order done

 

Shell Script while Cyclic grammar ?

·  Like for loop ,while Loop repeats its command block as long as the condition holds .
·  differ for loop ,while The loop will iterate , Until its condition is not true .

Basic grammar :

 

while [  Conditions  ]do command …done

 


- do-while The basic format of the statement ?

do-while Statement similar to while sentence , But execute the command before checking the conditional statement (LCTT Translation notes : Means to perform at least once .). The following is to use do-while Sentence syntax :

 

do{ command } while ( Conditions )    1    2    3    4

 


- Shell Script break Role of command ?

break A simple use of the command is to exit the loop in execution . We can do it in while and until Use in loop break Command out of loop .

- Shell Script continue Role of command ?

continue Orders are different from break command , It just jumps out of the iteration of the current loop , Not the whole cycle .continue Orders are very useful in many cases , For example, mistakes happen , But we still hope that when we continue to carry out the big cycle .

 

- How to make scripts executable ?

Use chmod Command to make the script executable . Examples are as follows :chmod a+x myscript.sh .

 

#!/bin/bash  The role of ?#!/bin/bash  yes  Shell  The first line of the script , It's called Shi Pang (shebang) That's ok .     here  #  The symbol is called  hash , and  !  be called  bang.     It means to order through  /bin/bash  To execute .

 


- How to debug Shell Script ?

    Use -x' Count (sh -x myscript.sh) Can debug Shell Script .
    Another way is to use -nv Parameters (sh -nv myscript.sh).

- How to redirect standard output and error output to the same location at the same time ?

    Method 1 :2>&1 ( Such as ## ls /usr/share/doc > out.txt 2>&1 ) .
    Method 2 :&> ( Such as ## ls /usr/share/doc &> out.txt ) .

- stay Shell Script , How to test files ?

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

 

Test          usage -d  file name      If the file exists and is a directory , return true-e  file name      If the file exists , return true-f  file name      If the file exists and is a normal file , return true-r  file name      If the file exists and is readable , return true-s  file name      If the file exists and is not empty , return true-w  file name      If the file exists and can be written , return true-x  file name      If the file exists and is executable , return true

 


- stay Shell How do scripts define functions ?

A function is a block of code with a name . When we define code blocks , We can call the function name in our script , The block will be executed . An example is shown below :

 

$ diskusage () { df -h ; } Translation notes : Here's what I gave shell Function syntax , The original text doesn't have [ function ]  Function name  [()]{ command ;[return int;]}

 

How to make Shell Get input from the terminal on the script ?

read The command can be read from the terminal ( Using the keyboard ) The data of .read Command to get the user's input and put it in the variable you give . Examples are as follows :

 

## vi /tmp/test.sh#!/bin/bashecho ‘Please enter your name’read nameecho “My Name is $name”## ./test.shPlease enter your nameThinkWonMy Name is ThinkWon

 

 

- How to perform arithmetic operations ?

There are two ways to perform arithmetic operations :

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

Four 、 Programming questions


1. Determine whether a file is a character device file , If you copy it to /dev Under the table of contents ?

 

#!/bin/bashread -p "Input file name: " FILENAMEif [ -c "$FILENAME" ];then cp $FILENAME /devfi

 


2. Add a new group as class1 , And then add... That belongs to this group 30 Users , The form of the user name is stdxx , among xx from 01 To 30 ?

 

#!/bin/bashgroupadd class1for((i=1;i<31;i++))do        if [ $i -le 10 ];then                useradd -g class1 std0$i        else                useradd -g class1 std$i        fidone

 


3. To write Shell Program , Realize automatic deletion 50 The function of an account , The account name is stud1 to stud50 ?

 

#!/bin/bashfor((i=1;i<51;i++))do                userdel -r stud$idone

 


4. Write a sed command , modify /tmp/input.txt The content of the document ?

requirement :
·  Delete all blank lines .
·  In a row , If you include “11111”, It's in “11111” Insert in front “AAA”, stay “11111” Insert... At the back “BBB” . such as : The content will be 0000111112222 Change the line from "to" 0000AAA11111BBB2222 .

 

[[email protected]~]## cat -n /tmp/input.txt     1  000011111222     2     3  000011111222222     4  11111000000222     5     6     7  111111111111122222222222     8  2211111111     9  112222222    10  1122    11    ##  Delete all empty line commands [[email protected]~]## sed '/^$/d' /tmp/input.txt0000111112220000111112222221111100000022211111111111112222222222222111111111122222221122##  Insert the specified character [[email protected]~]## sed 's#\(11111\)#AAA\1BBB#g' /tmp/input.txt0000AAA11111BBB2220000AAA11111BBB222222AAA11111BBB000000222AAA11111BBBAAA11111BBB1112222222222222AAA11111BBB1111122222221122

 

 

5、 ... and 、 actual combat

 

1. How to choose Linux Operating system version ?

In general , Desktop users prefer Ubuntu ; Server preferred RHEL or CentOS , First of all CentOS .

According to the specific requirements :

·  High security requirements , select Debian perhaps FreeBSD .

·  Users who need to use advanced database services and e-mail network applications can choose SUSE .

·  If you want new technology and new functions, you can choose Feddora ,Feddora yes RHEL and CentOS A beta and pre release version of .

·【 a key 】 According to the current situation , Most Internet companies choose CentOS . It is more commonly used now 6 series , About half of the market now . The other reason is CentOS More focus on the server area , And there are no copyright restrictions .

CentOS 7 series , It will be used more slowly .

2. How to plan a Linux host , How is the procedure ?

    1、 Determine what the machine is for , For example, do WEB 、DB、 Or the game server .

        Different uses , The configuration of the machine will be different .

    2、 When you're sure , It depends on how the system needs to be installed , Which systems are installed by default 、 How to do partition .

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

3. When the user feedback website visit slow , How to deal with it ?

- What kind of factors will lead to slow website access ?

   1、 The server exit bandwidth is not enough

      The export bandwidth purchased by the server itself is relatively small . Once the concurrency is large , It will result in a small export bandwidth allocated to each user , The access speed will be slow .
      Bandwidth reduction across carrier networks . for example , The company's website is on the telecom network , Then the customer side docking is Great Wall broadband or Unicom , This can also lead to a reduction in bandwidth .

    2、 The server is overloaded , It's not responding

        It can be analyzed from two aspects :
        Analyze system load , Use w Order or uptime Command to view system load . If the load is high , Then use top Command view CPU ,MEM Wait for occupancy , Or CPU Busy , Either there's not enough memory .
        If both are normal , Use it again sar Command analysis network card traffic , Analysis is not subject to ***. Once the cause of the problem is analyzed , Take corresponding measures to solve , If you decide whether or not to kill some processes , Or forbid some visits and so on .

    3、 Database bottleneck

     If there are more slow queries . Then it's up to developers or DBA To assist in SQL Statement optimization .
     If the database is slow to respond , Consider adding a database cache , Such as Redis etc. . then , You can also build MySQL Master-slave , a MySQL The server is responsible for writing , The others read from the database .

    4、 Website development code is not optimized well

     for example SQL Statement is not optimized , It takes a lot of time to read and write the database .

- Slow access to websites , How to investigate ?

    1、 The first thing is to determine whether it is a client-side or a server-side problem . When receiving feedback from users, the visit is slow , Visit the website immediately , If you visit here quickly , Basically, it's a client problem , You need to patiently explain to the customer , Help customers solve problems .

    Don't just look at the problems on the server side . We have to start at the source , Step by step down .

    2、 If the visit is slow , Then you can use the browser's debugging function , It takes too much time to load the data , It's the slow loading of pictures , Or some data is slow to load .

    3、 For server load situation . Look at the server hardware ( The Internet 、CPU、 Memory ) Consumption of . If it's a purchased virtual machine , For example, Alibaba cloud , You can log in to the alicloud platform to provide monitoring in all aspects , such as CPU、 Memory 、 Bandwidth usage .

    4、 If you find that the hardware resource consumption is not high , Then you need to check the log , Let's see MySQL Slow query log , See if it's something SQL Statement query is slow , This leads to slow website access .

- How to solve ?

    1、 If it's an exit bandwidth problem , It's been a long time to apply for increasing the export bandwidth .
    2、 If there are more slow queries , Then it's up to developers or DBA To assist in SQL Statement optimization .
    3、 If the database is slow to respond , Consider adding a database cache , Such as Redis wait . And then you can build MySQL Master-slave , a MySQL The server is responsible for writing , The others read from the database .
    4、 Apply to buy CDN service , Load user access .
    5、 If the visit is still slow , Then we need to optimize the overall architecture . Be dedicated to your role , Multiple servers provide the same service .

4. Linux What are the methods of performance tuning ?

    1、Disabling daemons ( close daemons).
    2、Shutting down the GUI ( close GUI).
    3、Changing kernel parameters ( Change kernel parameters ).
    4、Kernel parameters ( Kernel parameters ).
    5、Tuning the processor subsystem ( Processor subsystem tuning ).
    6、Tuning the memory subsystem ( Memory subsystem tuning ).
    7、Tuning the file system ( File system subsystem tuning ).
    8、Tuning the network subsystem( Network subsystem tuning ).

6、 ... and 、 Document management order


1. cat command

cat Commands are used to connect files and print them to standard output devices .

cat There are three main functions :

1. Show the whole file at once :

 

cat filename

 

2. Create a file from the keyboard :

 

cat > filename

 


Only new files can be created , You can't edit an existing file .

3. Merge several files into one file :

 

cat file1 file2 > file

 


    -b Output line number to non null
    -n Output all line numbers

- example :

(1) hold log2012.log Add the line number to the contents of the file and input log2013.log In this document

 

cat -n log2012.log log2013.log

 


(2) hold log2012.log and log2013.log The contents of the document are numbered ( Blank lines do not add ) Then attach the content to log.log in

 

cat -b log2012.log log2013.log log.log

 


(3) Use here doc Generate new file

 

cat >log.txt <<EOF>Hello>World>PWD=$(pwd)>EOFls -l log.txtcat log.txtHelloWorldPWD=/opt/soft/test

 


(4) Reverse list

 

tac log.txtPWD=/opt/soft/testWorldHello

 


2. chmod command

Linux/Unix The file call permission of is divided into three levels : File owner 、 group 、 other . utilize chmod You can control how files are called by others .

Used to change linux Access to system files or directories . Use it to control access to files or directories . There are two uses for this command . One is a text setter that contains letters and operator expressions ; The other is the number setting method including numbers .

Each file or directory has three groups of access rights , Each group is represented by three digits , Read by the owner of the document 、 Write and execute permissions ; Read by users in the same group as the owner 、 Write and execute permissions ; Read by other users in the system 、 Write and execute permissions . You can use ls -l test.txt lookup .

With documents log2012.log For example :

 

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

 


The first column has 10 A place , The first character specifies the file type . In the usual sense , A directory is also a file . If the first character is a horizontal line , Represents a non directory file . If it is d, Represents a directory . From the second character to the tenth 9 Characters ,3 A group of characters , They respectively represent 3 Group user permissions for files or directories . The permission character represents empty permission with a horizontal line ,r Read only ,w Representative writing ,x Representative executable .

Common parameters :

 

-c  When there is a change , Report processing information -R  Process all files in the specified directory and its subdirectories 

 


Scope of authority :

 

u : The current user of the directory or file g : The current group of directories or files o : Users or groups other than the current users or groups of directories or files a : All users and groups 

 


Authority code :

 

r : Read permission , Use numbers 4 Express w : Write permissions , Use numbers 2 Express x : Executive authority , Use numbers 1 Express - : Delete permission , Use numbers 0 Express s : Special privileges 

 


- example :
(1) odd file t.log All users can execute permissions

 

chmod a+x t.log

 


(2) Revoke all original permissions , Then give the owner read permission , And output processing information

 

chmod u=r t.log -c

 


(3) to file The owner of the assignment read 、 Write 、 perform (7) Authority , to file The group assigned to read 、 perform (5) Authority , Assign execution... To other users (1) Authority

 

chmod 751 t.log -c( perhaps :chmod u=rwx,g=rx,o=x t.log -c)

 


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

 

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

 


3. chown command

chown Change the owner of the specified file to the specified user or group , The user can be a user name or a user ID; Groups can be group names or groups ID; File is a list of files separated by spaces to change permissions , Support for wildcards .

 

-c  Display information about the changed part -R  Handle specified directories and subdirectories 

 

 

- example :

(1) Change owners and groups And display the change message

 

chown -c mail:mail log2012.log

 


(2) Change file group

 

chown -c :mail t.log

 


(3) Change the folder and sub file directory to mail

 

chown -cR mail: test/

 


4. cp command

Copy the source file to the destination file , Or copy multiple source files to the destination directory .

Be careful : Command line copy , If the target file already exists, you will be prompted whether to overwrite , And in the shell Script , If not -i Parameters , It will not prompt , It's direct coverage !

 

-i  Tips -r  Copy 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 test Under the table of contents , Keep the original file for , If there is a prompt in the original file whether to overwrite .

 

cp -ai a.txt test

 


(2) by a.txt Suggest a link ( Shortcut )

 

cp -s a.txt link_a.txt

 


5. find command

Used to find files in the file tree , And deal with it accordingly .

Command format :

 

find pathname -options [-print -exec -ok ...]

 


Command parameter :

 

pathname: find Directory path found by command . For example . To represent the current directory , use / To represent the system root .-print:find Command to export matching files to standard output .-exec:find Command to execute the shell command . The form of the corresponding command is 'command' {  } \;, Be careful {   } and \; Space between .-ok: and -exec It's the same thing , Only in a more secure mode shell command , Before each command is executed , Will give a hint , Let the user decide whether to execute .

 


Command options :

 

-name  Find files by file name -perm  Search for files by file permissions -user  Search files by file owner -group   Find files by their group .-type   Find a type of file , Such as :   b -  Block device file    d -  Catalog    c -  Character device file    l -  Symbolic link file    p -  Pipeline files    f -  Ordinary documents 

 


- example :

(1) lookup 48 Documents modified within hours

 

find -atime -2

 


(2) Find... In the current directory With .log Final document .. Represents the current directory

 

find ./ -name '*.log'

 


(3) lookup /opt Under the table of contents Permission is 777 The file of

 

find /opt -perm 777

 


(4) Find greater than 1K The file of

 

find -size +1000c

 

 

(5) Search equals 1000 Character file

 

find -size 1000c

 


-exec Parameters are followed by command command , It ends with ; Marked for the end , So the semicolon after this command is indispensable , Considering that semicolons have different meanings in different systems , So add a backslash in front .{} Curly brackets stand for the front find Find out the file name .
 

6. head command

head Used to display the beginning of the file to the standard output , Default head Command to print the beginning of its corresponding file 10 That's ok .

Common parameters :

 

-n< Row number >  Number of lines displayed ( The number of lines is a complex number indicating the number from the last to the front )

 


example :

(1) Show 1.log Before file 20 That's ok

 

head 1.log -n 20

 


(2) Show 1.log Before document 20 byte

 

head -c 20 log2014.log

 


(3) Show t.log Last 10 That's ok

 

head -n -10 t.log

 


7. less command

less And more similar , But use less You can browse files at will , and more Move forward only , But can't move back , and less The entire file will not be loaded until it is viewed .

Common command parameters :

 

-i   Ignore case when searching -N   Show the line number of each line -o  < file name >  take less  The output is saved in the specified file -s   Show a row of consecutive empty actions / character string : Search down “ character string ” The function of ? character string : Search up “ character string ” The function of n: Repeat the previous search ( And  /  or  ?  of )N: Repeat the previous search in reverse ( And  /  or  ?  of )-x < Numbers >  take “tab” Key is displayed as the specified number space b   Turn back one page d   Turn back half a page h   Show help screen Q   sign out less  command u   Scroll forward half a page y   Scroll one line of space bar forward   Scroll to enter   Scroll one page [pagedown]: Page down [pageup]:    Page up 

 


example :

(1)ps View process information and go through less Pagination display

 

ps -aux | less -N

 


(2) View multiple files

 

less 1.log 2.log

 


have access to n View next , Use p Check out the previous .

 

8. ln command

The function is to create a synchronous link for the file in another location , When the problem is needed in different directories , You don't need to create the same file for each directory , adopt ln Created Links (link) Reduce disk usage .

Link categories : Software links and hard links

Soft link :

    1. Soft link , In the form of a path . Be similar to Windows Shortcuts in the operating system
    2. Soft links can Cross file system , Hard links cannot
    3. Soft link can link to a file name that does not exist
    4. Soft links can link directories

Hard links :

    1. Hard links , In the form of a copy of a document . But it doesn't take up the actual space .
    2. Hard links to directories are not allowed
    3. Hard links can only be created in the same file system

We need to pay attention to :

    First of all :ln The command keeps every linked file in sync , in other words , No matter where you change , Other documents will change the same ;
    second :ln The links are divided into soft links and hard links , Soft links are ln –s Source file Target file , It will only create a mirror image of the file in the location you choose , Does not take up disk space , Hard links ln Source file Target file , No parameters -s, It will generate a file of the same size as the source file in the location you choose , Whether it's soft link or hard link , Keep files in sync .
    Third :ln Instructions are used to link files or directories , If more than two files or directories are specified at the same time , And the final destination is an existing directory , All the files or directories specified previously will be copied to the directory . If multiple files or directories are specified at the same time , And the final destination is not an existing directory , Then an error message will appear .

Common parameters :

 

-b  Delete , Overwrite previously established links -s  Soft link ( A symbolic link )-v  Show detailed processing 

 


example :

(1) Create soft links to files , And display the operation information

 

ln -sv source.log link.log

 


(2) Create hard links to files , And display the operation information

 

ln -v source.log link1.log

 


(3) Create soft links to directories

 

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

 


9. locate command

locate Through the search system built-in document database to quickly find files , Database by updatedb Program to update ,updatedb By cron daemon Periodically called . By default locate The command searches the database faster than the entire hard disk data , But the worse is locate If the found file is recently created or Just changed its name , You may not find , In the internal setting ,updatedb I run once a day , Can be modified by crontab To update the settings (etc/crontab).

locate And find Command similar , It can be used as *、? Wait for regular match search

Common parameters :

 

-l num( Number of lines to display )-f    Exclude specific file systems , Such as the proc Ruled out -r    Use regular expressions as search conditions 

 


example :

(1) Find and pwd All relevant documents ( The filename contains pwd)

 

locate pwd

 


(2) Search for etc All under the directory sh Opening file

 

locate /etc/sh

 


(3) lookup /var Under the table of contents , With reason Final document

 

locate -r '^/var.*reason$'( among . Represents a character ,* Represent multiple tasks ;.* Represents any number of characters )

 


10. more command

Function like cat, more It will display one page at a time for users to read one page at a time , And the most basic command is to press the blank key (space) The next page shows , Press b The key will go back (back) One page shows .

Command parameter :

 

+n       From the first  n  Line start display -n        Define screen size as n That's ok +/pattern  Search for the string before each file is displayed (pattern), Then it starts to display... After the first two lines of the string -c        Clear the screen from the top , Then show -d        Tips “Press space to continue,’q’ to quit( Press the space bar to continue , Press q Key to exit )”, Disable the ring function -l         Ignore Ctrl+l( Change the page ) character -p        Wrap the document by clearing the window instead of scrolling , And -c Similar options -s        Display consecutive blank lines as one line -u        Remove the underline from the contents of the document 

 


Common operation command :

 

Enter     Down  n  That's ok , Need to define . The default is  1  That's ok Ctrl+F    Scroll down one screen of the space bar    Scroll down one screen Ctrl+B   Go back to the previous screen =        Output the line number of the current line :f      Output filename and line number of current line V       call vi Editor ! command     call Shell, And execute the command q        sign out more

 


example :

(1) Display files from the 3 What you can do

 

more +3 text.txt

 


(2) In the list of file directory details , With the help of pipes, each display 5 That's ok

 

ls -l | more -5

 


Press the space to display 5 That's ok .

 

11. mv command

Move or change file name , According to the second parameter type ( Such as catalogue , Move the file ; If it is a file, command the file again ).

When the second parameter is Directory , The first parameter can be multiple files or directories separated by spaces , Then move multiple files specified by the first parameter to the directory specified by the second parameter .

example :

(1) Will file test.log Rename it to test1.txt

 

mv test.log test1.txt

 


(2) Will file log1.txt,log2.txt,log3.txt Move to the root test3 Directory

 

mv llog1.txt log2.txt log3.txt /test3

 


(3) Will file file1 Renamed as file2, If file2 Already exist , Ask if you want to overwrite

 

mv -i log1.txt log2.txt

 


(4) Move all files under the current folder to the previous directory

 

mv * ../

 


12. rm command

Delete one or more files or directories in a directory , If not used -r Options , be rm Directory will not be deleted . If you use rm To delete files , Usually you can still restore the file to its original state .

 

rm [ Options ]  file …

 


example :
(1) Delete any .log file , One by one asked to confirm before deleting :

 

rm -i *.log

 


(2) Delete test Delete all files in subdirectories and subdirectories , And there's no need to confirm one by one :

 

rm -rf test

 


(3) Delete with -f Opening file

 

rm -- -f*

 


13. tail command

Used to display the end of the specified file , When no file is specified , To process as input information . Often check log files .

Common parameters :

 

-f  Cyclic reading ( Used to view incremental log files )-n< Row number >  Display row number ( From the back forward )

 


(1) Loop through the increasing contents of the file

 

ping 127.0.0.1 > ping.log &

 


Background operation : You can use jobs -l see , You can also use fg Move it to the front desk to run .

 

tail -f ping.log

 


( Check the log )

 

14. touch command

Linux touch The command is used to modify the time attribute of a file or directory , Including access time and change time . If the file does not exist , The system will create a new file .

ls -l It can display the time record of the file .

grammar

 

touch [-acfm][-d< Date time >][-r< A reference document or catalogue >] [-t< Date time >][--help][--version][ File or directory …]

 


    Parameter description :
    a Changing the reading file time records .
    m Change modify file time records .
    c If the object file does not exist , We will not create a new file . And --no-create The effect is the same .
    f Don't use , To other unix While retaining compatibility of the system .
    r Recording a reference time profile , And --file The effect is the same .
    d Setting the Time and Date , You can use a variety of different formats .
    t Time record set file , Format and date The same instruction .
    –no-create It does not create a new file .
    –help Lists the instruction format .
    –version Listed version Message .

example

Use instruction "touch" Modify file "testfile" The time attribute of is the current system time , Enter the following command :

 

$ touch testfile                # Modify the time attribute of the file 

 


First , Use ls Command view testfile File properties , As shown below :

 

$ ls -l testfile                # View the time attribute of the file   # The modification time of the original document is 16:09  -rw-r--r-- 1 hdd hdd 55 2011-08-22 16:09 testfile

 


Execution instruction "touch" After modifying the file properties , And check the time attribute of the file again , As shown below :

 

$ touch testfile                # Modify the file time attribute to the current system time   $ ls -l testfile                # View the time attribute of the file   # The time attribute of the modified file is the current system time   -rw-r--r-- 1 hdd hdd 55 2011-08-22 19:53 testfile

 


Use instruction "touch" when , If the specified file does not exist , A new blank file will be created . for example , In the current directory , Use this command to create a blank file "file", Enter the following command :

 

$ touch file            # Create a file called “file” New blank file for 

 


15. vim command

Vim It's from vi Developed a text editor . Code completion 、 The functions of compiling and error jump are very rich , Widely used in programmers .

    Open the file and jump to 10 That's ok :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 There are three modes , Command mode (Command mode), The input mode (Insert mode) And bottom line command mode (Last line mode).

To put it simply , We can think of these three patterns as icons at the bottom :

 

16. whereis command

whereis Command can only be used for program name search , And just search for binaries ( Parameters -b)、man Documentation ( Parameters -m) And source code files ( Parameters -s). If the parameter is omitted , Then all information .whereis And locate All search based on the database built in the system , So it's very efficient , and find Is to traverse the hard disk to find the file .

Common parameters :

 

-b    Locate the executable .-m    Locate help file .-s    Locate the source file .-u    Search for executable files in the default path 、 Source code file 、 Documents other than help documents .

 


example :

(1) lookup locate Procedure related documents

 

whereis locate

 


(2) lookup locate Source file

 

whereis -s locate

 


(3) lookup lcoate Help file for

 

whereis -m locate

 


17. which command

stay linux To find a file , But I don't know where it is , You can use some of the following commands to search for :

 

which      View the location of the executable .whereis  Check the location of the file .locate   Cooperate with the database to view the file location .find         Actually search hard disk for file name .

 


which Is in PATH In the specified path , Search for the location of a system command , And return the first search result . Use which command , You can see if a system command exists , And where exactly the command is executed .

Common parameters :

 

-n  Specifies the length of the filename , The specified length must be greater than or equal to the longest filename in all files .

 


example :
(1) see ls Whether the order exists , Perform which

 

which ls

 


(2) see which

 

which which

 


3) see cd

 

which cd( Show that there is no , because  cd  It's a built-in order , and  which  The search shows  PATH  The command )

 


View the current PATH To configure :

 

echo $PATH

 


Or use env View all environment variables and their corresponding values

7、 ... and 、 Document editing command

 

1. grep command

Powerful text search commands ,grep(Global Regular Expression Print) Global regular expression search .

grep It works like this , It searches for string templates in one or more files . If the template includes spaces , Must be referenced , All strings after the template are treated as file names . Search results are sent to standard output , Does not affect the content of the original document .

Command format :

 

grep [option] pattern file|dir

 


Common parameters :

 

-A n --after-context After the matching characters are displayed n That's ok -B n --before-context Show before matching characters n That's ok -C n --context  Show before and after matching characters n That's ok -c --count  Calculated in line with the number of columns styles -i  Ignore case -l  List only the file names whose contents match the specified style -f  Read keywords from file -n  Shows the number of lines in the file that match the content -R  Recursively looking up folders 

 


grep The regular expression of :

 

^  # The beginning of the anchor line   Such as :'^grep' Match all to grep Beginning line .$  # The end of the anchoring line   Such as :'grep$' Match all to grep The line at the end ..  # Match a non newline character   Such as :'gr.p' matching gr Followed by an arbitrary character , And then there was p.*  # Match zero or more previous characters   Such as :'*grep' Match all one or more spaces followed by grep The line of ..*   # Use together to represent any character .[]   # Match a specified range of characters , Such as '[Gg]rep' matching Grep and grep.[^]  # Match a character that is not in the specified range , Such as :'[^A-FH-Z]rep' Match does not contain A-R and T-Z The beginning of a letter , Following the rep The line of .\(..\)  # Mark match characters , Such as '\(love\)',love Marked as 1.\<      # Anchor the beginning of the word , Such as :'\<grep' The match consists of grep The line at the beginning of the word .\>      # Anchor the end of the word , Such as 'grep\>' The match consists of grep The lines of the ending words .x\{m\}  # Repeat characters x,m Time , Such as :'0\{5\}' Matching inclusion 5 individual o The line of .x\{m,\}  # Repeat characters x, At least m Time , Such as :'o\{5,\}' Match at least 5 individual o The line of .x\{m,n\}  # Repeat characters x, At least m Time , Not more than n Time , Such as :'o\{5,10\}' matching 5--10 individual o The line of .\w    # Match text and numeric characters , That is to say [A-Za-z0-9], Such as :'G\w*p' Match with G Followed by zero or more text or number characters , And then there was p.\W    #\w The reverse form of , Match one or more non word characters , Such as a period .\b    # Word lock , Such as : '\bgrep\b' Only match grep.

 


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 file

 

cat test1.txt | grep -f key.log

 

  
(4) Search recursively from the folder to grep Beginning line , And list only the documents

 

grep -lR '^grep' /tmp

 


(5) Search for non x Line contents of the switch

 

grep '^[^x]' test.txt

 


(6) Display contains ed perhaps at The content line of the character

 

grep -E 'ed|at' test.txt

 

 

2. wc command  


wc(word count) The function is to count the number of bytes in the specified file 、 Number of words 、 Row number , And output the statistical results

Command format :

 

wc [option] file..

 


Command parameter :

 

-c  Count the number of bytes -l  The statistical number of rows -m  Count characters -w  Count the number of words , A word is defined as a blank 、 A string separated by a skip or newline character 

 


example :
(1) Looking for documents Row number Number of words Number of bytes file name

 

wc text.txt

 


result :

 

7     8     70     test.txt

 


(2) Count the lines of the output result

 

cat test.txt | wc -l

 

 

8、 ... and 、 Disk management commands

 

1. cd command

cd(changeDirectory) Command syntax :

 

cd [ Directory name ]

 


explain : Switch current directory to dirName.

example :
(1) Enter the desired directory

 

cd /

 

(2) Get into “home” Catalog

 

cd ~

 

(3) Enter the last working path

 

cd -

 

(4) Take the parameters of the last command as cd Parameters use .

 

cd !$

 


2. df command

Display disk space usage . How much space is used to get the hard disk , How much space and other information is left , If no filename is specified , Then the free space of all currently mounted file systems will be displayed . By default , Disk space will be 1KB Display for units , Unless the environment variable POSIXLY_CORRECT To be designated , That would be to 512 Bytes for display :

 

-a  List of all file systems -h  Display information in a way that is easy to read -i  Show inode Information -k  The block is 1024 byte -l  Show only local disks -T  List file system types 

 


example :
(1) Display disk usage

 

df -l

 

(2) List all file systems and their types in an easy to read way

 

df -haT

 


3. du command

du The command is also used to view the usage space , But with the df The difference is Linux du Command is a view of the space used by files and directory disks :

Command format :

 

du [ Options ] [ file ]

 


Common parameters :

 

-a  Show all file sizes in directory -k  With KB Show file size in units -m  With MB Show file size in units -g  With GB Show file size in units -h  Display the file size in an easy to read way -s  Show totals only -c or --total   In addition to displaying the size of individual directories or files , It also shows the sum of all directories or files 

 


example :
(1) Display the size of folders and subfolders in an easy to read way

 

du -h scf/

 


(2) Display all file sizes in the folder in an easy to read way

 

du -ah scf/

 


(3) Display the size of disk space occupied by several files or directories , And count the sum of them

 

du -hc test/ scf/

 


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

 

du -hc --max-depth=1 scf/

 


4. ls command

Namely list Abbreviation , adopt ls The command can not only view linux Files contained in the folder , And you can view file permissions ( Including directory 、 Folder 、 File permissions ) Check catalog information and so on .

Common parameter collocation :

 

ls -a  List all files in the directory , Include with . Start with hidden files ls -A  In addition to the listed . And .. Other documents of ls -r  In reverse order ls -t  Sort by file modification time ls -S  Sort by file size ls -h  Display in readable size ls -l  In addition to the filename , Also file permissions 、 owner 、 File size and other information are listed in detail 

 


example :
(1) Sort in reverse chronological order by readability , And show file details

 

ls -lhrt

 

 (2) Display file details in reverse order of size

 

ls -lrS

 

(3) List all in the current directory with "t" The details of the opening Directory

 

ls -l t*

 

(4) List file absolute paths ( No hidden files )

 

ls | sed "s:^:`pwd`/:"

 

(5) List file absolute paths ( Contains hidden files )

 

find $pwd -maxdepth 1 | xargs ls -ld

 


5. mkdir command

mkdir The command is used to create a folder .

The available options :
    -m: Set access to new directory , It can also be used. chmod Command settings ;
    -p: It can be a path name . At this time, if some directories in the path do not exist , With this option added , The system will automatically create directories that are not yet available , That is, multiple directories can be created at one time .

example :
(1) The current working directory is created with the name t Folder

 

mkdir t

 

(2) stay tmp The creation path under the directory is test/t1/t The catalog of , If it does not exist , Create :

 

mkdir -p /tmp/test/t1/t

 


6. pwd command

pwd The command is used to view the current working directory path .

example :
(1) View current path

 

pwd

 

(2) See the actual path of the soft link

 

pwd -P

 


7. rmdir command

Remove one or more subdirectory entries from a directory , When deleting a directory, you must also have write permission to its parent directory .
Be careful : Cannot delete non empty directory

example :
(1) When parent If the subdirectory is deleted and makes it an empty directory , The way be deleted :

 

rmdir -p parent/child/child11

 

 

Nine 、 Network communication command

 

1. ifconfig command

    ifconfig For viewing and configuring Linux The network interface of the system .
    View all network interfaces and their status :ifconfig -a .
    Use up and down Command to start or stop an interface :ifconfig eth0 up and ifconfig eth0 down .

2. iptables command

iptables , It's a configuration Linux Kernel firewall command line tool . Very powerful , For our development , Master how to open the port . for example :

    Put the source IP by 192.168.1.101 Visit native 80 Port's packets are rejected directly :iptables -I INPUT -s 192.168.1.101 -p tcp --dport 80 -j REJECT .

    Turn on 80 port , because web It's the port to the outside world

 

    iptables -A INPUT -p tcp --dport 80 -j ACCEP

 

 
    in addition , Pay attention to the use of iptables save command , Preservation . otherwise , After the server restarts , The configured rules will be lost .

3. netstat command

Linux netstat Command is used to display network status .

utilize netstat Instructions can let you know the whole thing Linux The network of the system .

grammar

 

netstat [-acCeFghilMnNoprstuvVwx][-A< Network type >][--ip]

 


Parameter description :
    -a or –all Show... In all connections Socket.
    -A< Network type > or –< Network type > List the relevant addresses in the connection of this network type .
    -c or –continuous Keep listing network status .
    -C or –cache Display the cache information of router configuration .
    -e or –extend Display other network related information .
  -F or –fib Show FIB.
    -g or –groups Display the group members list of multi broadcast function .
    -h or –help Online Help .
    -i or –interfaces Display the web interface information form .
    -l or –listening Shows the server in the monitor Socket.
    -M or –masquerade Show fake network connections .
    -n or –numeric Use it directly IP Address , Instead of going through the domain name server .
    -N or –netlink or –symbolic Displays the symbolic connection name of the network hardware peripheral .
    -o or –timers Display timer .
    -p or –programs Display in use Socket Program identification code and program name .
    -r or –route Show Routing Table.
    -s or –statistice Display network work information statistics .
    -t or –tcp Show TCP The connection status of the transport protocol .
    -u or –udp Show UDP The connection status of the transport protocol .
    -v or –verbose Display during execution of instructions .
    -V or –version Display version information .
    -w or –raw Show RAW The connection status of the transport protocol .
    -x or –unix And the effect of this parameter is specified "-A unix" Parameters are the same .
    –ip or –inet And the effect of this parameter is specified "-A inet" Parameters are the same .

example

How to check which ports are open in the system ?

 

[[email protected] ~ 13:20 #55]# netstat -lnpActive Internet connections (only servers)Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program nametcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1035/sshdtcp        0      0 :::22                       :::*                        LISTEN      1035/sshdudp        0      0 0.0.0.0:68                  0.0.0.0:*                               931/dhclientActive UNIX domain sockets (only servers)Proto RefCnt Flags       Type       State         I-Node PID/Program name    Pathunix  2      [ ACC ]     STREAM     LISTENING     6825   1/init              @/com/ubuntu/upstartunix  2      [ ACC ]     STREAM     LISTENING     8429   1003/dbus-daemon    /var/run/dbus/system_bus_socket

 


How to check the network connection status ?

 

[[email protected] ~ 13:22 #58]# netstat -anActive Internet connections (servers and established)Proto Recv-Q Send-Q Local Address               Foreign Address             Statetcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTENtcp        0      0 192.168.147.130:22          192.168.147.1:23893         ESTABLISHEDtcp        0      0 :::22                       :::*                        LISTENudp        0      0 0.0.0.0:68                  0.0.0.0:*

 


How to count the number of current process connections in the system ?

    Enter the command netstat -an | grep ESTABLISHED | wc -l .
    Output results 177 . Altogether 177 The number of connections .

use netstat Command with other commands , According to the source IP Count all to 80 Port of ESTABLISHED Number of state Links ?

    Strictly speaking , The test of this topic is to awk Use .

First , Use netstat -an|grep ESTABLISHED command . give the result as follows :

 

tcp        0      0 120.27.146.122:80       113.65.18.33:62721      ESTABLISHEDtcp        0      0 120.27.146.122:80       27.43.83.115:47148      ESTABLISHEDtcp        0      0 120.27.146.122:58838    106.39.162.96:443       ESTABLISHEDtcp        0      0 120.27.146.122:52304    203.208.40.121:443      ESTABLISHEDtcp        0      0 120.27.146.122:33194    203.208.40.122:443      ESTABLISHEDtcp        0      0 120.27.146.122:53758    101.37.183.144:443      ESTABLISHEDtcp        0      0 120.27.146.122:27017    23.105.193.30:50556     ESTABLISHED

 


4. ping command

Linux ping The command is used to detect the host .

perform ping Command will use ICMP Transfer protocol , Send a message asking for a response , If there is no problem with the network function of the remote host , They'll respond to the message , So we know that the host is working normally .

 

Specifies the number of times packets are received

 

ping -c 2 www.baidu.com

 


5. telnet command

Linux telnet The command is used for remote login .

perform telnet Command to start terminal phase operation , And log in to the remote host .

grammar

 

telnet [-8acdEfFKLrx][-b< Host alias >][-e< Break away from character >][-k< domain name >][-l< User name >][-n< Log files >][-S< Service type >][-X< Certification Form >][ Host name or IP Address < Communication port >]

 


Parameter description :
    -8 Allow to use 8 Bit character data , Including input and output .
    -a Try to log in to the remote system automatically .
    -b< Host alias > Use the alias to specify the remote host name .
    -c Do not read... In the user's private directory .telnetrc file .
    -d Start troubleshooting mode .
    -e< Break away from character > Set escape character .
    -E Filter out detached characters .
    -f And the effect of this parameter is specified "-F" Parameters are the same .
    -F Use Kerberos V5 At the time of certification , Add this parameter to upload the authentication data of the local host to the remote host .
    -k< domain name > Use Kerberos At the time of certification , Add this parameter to let the remote host use the specified domain name , Not the domain name of the host .
    -K Do not automatically log in to the remote host .
    -l< User name > Specify the user name to log on to the remote host .
    -L Allow output 8 Bit character data .
    -n< Log files > Specify file record information .
    -r Use similar rlogin Command user interface .
    -S< Service type > Set up telnet What you need to connect IP TOS Information .
    -x Suppose the host has the function to support data encryption , Just use it .
    -X< Certification Form > Turn off the specified authentication mode .

example
Log on to the remote host

 

#  Sign in IP by  192.168.0.5  Remote host of telnet 192.168.0.5

 

 

Ten 、 System management command

 

1. date command


Display or set the date and time of the system .

Command parameter :

 

-d< character string >  Display the date and time indicated by the string . String must be preceded by double quotes .-s< character string >  Set date and time based on string . String must be preceded by double quotes .-u  Show GMT.%H  Hours (00-23)%I  Hours (00-12)%M  minute ( With 00-59 To express )%s  Total seconds . The starting time is 1970-01-01 00:00:00 UTC.%S  second ( In local usage )%a  Abbreviation of week .%A  The full name of the week .%d  date ( With 01-31 To express ).%D  date ( Including mm / DD / yyyy ).%m  month ( With 01-12 To express ).%y  year ( With 00-99 To express ).%Y  year ( In four figures ).

 


example :
(1) Show next day

 

date +%Y%m%d --date="+1 day"  // Show the date of the next day 

 

(2)-d Parameters use

 

date -d "nov 22"   This year's  11  month  22  It's Wednesday date -d '2 weeks' 2 Date after week date -d 'next monday' ( Next Monday's date )date -d next-day +%Y%m%d( Tomorrow's date ) perhaps :date -d tomorrow +%Y%m%ddate -d last-day +%Y%m%d( Yesterday's date )  perhaps :date -d yesterday +%Y%m%ddate -d last-month +%Y%m( Last month was a few months )date -d next-month +%Y%m( Next month is a few months )

 


2. free command

Display system memory usage , Including physical memory 、 Interactive area memory (swap) And kernel buffer memory .

Command parameter :

 

-b  With Byte Display memory usage -k  With kb Display memory usage in units -m  With mb Display memory usage in units -g  With gb Display memory usage in units -s< Seconds apart >  Continuous display memory -t  Display the total memory usage 

 


example :
(1) Display memory usage

 

freefree -kfree -m

 

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

 

free -t

 

(3) Periodically query memory usage

 

free -s 10

 


3. kill command

Send the specified signal to the corresponding process . No specified model will be sent SIGTERM(15) Terminate the specified process . If no termination of the program is available "-KILL" Parameters , The signal it sends is SIGKILL(9) , Will force the process to end , Use ps Order or jobs Command to view the process number .root The user will affect the user's progress , Not root Users can only affect their own processes .

Common parameters :

 

-l   The signal , If no signal number parameter is added , Then use “-l” The parameter lists all the signal names -a   When processing the current process , There is no limit to the correspondence between the command name and the process number -p   Appoint kill  The command only prints the process number of the relevant process , Without sending any signals -s   Specify to send a signal -u   Designated user 

 


example :
(1) First use ps Find the process pro1, And then use kill kill

 

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

 


4. ps command

ps(process status), Used to view the current running process status , One time check , If dynamic continuous results are needed top

linux There are 5 States :
    1. function ( Running or waiting in the running queue )
    2. interrupt ( Sleeping , Blocked , Waiting for a condition to form or receive a signal )
    3. Non interruptible ( Received signal does not wake up and cannot run , The process must wait until an interrupt occurs )
    4. dead ( The process has terminated , But the process descriptor exists , Until the parent process calls wait4() Release after system call )
    5. stop it ( Process received SIGSTOP, SIGSTP, SIGTIN, SIGTOU Stop operation after signal )

ps The tool identifies the 5 State code :

 

D  Non interruptible  uninterruptible sleep (usually IO)R  function  runnable (on run queue)S  interrupt  sleepingT  stop it  traced or stoppedZ  dead  a defunct (”zombie”) process

 


Command parameter :

 

-A  Show all processes a  Show all processes -a  Display all processes under the same terminal c  Show the real name of the process e  Show environment variables f  Show relationships between processes r  Display the current running process of the terminal -aux  Show all processes that contain other uses 

 


example :
(1) Display all current process environment variables and inter process relationships

 

ps -ef

 

(2) Show all current processes

 

ps -A

 

(3) And grep Join to find a process

 

ps -aux | grep apache

 

(4) Find out and cron And syslog These two services are related to PID number

 

ps aux | grep '(cron|syslog)'

 


5. rpm command

Linux rpm Commands are used to manage packages .

rpm(redhat package manager) It was Red Hat Linux The distribution is designed to manage Linux Procedures for each package , Because it follows GPL Rules and functions are powerful and convenient , So it's popular . Gradually adopted by other distributions .RPM The emergence of suite Management , Give Way Linux Easy to install , upgrade , Indirectly promoted Linux Applicability of .

 

#  View the system jdkrpm -qa | grep jdk#  Delete the system jdkrpm -e --nodeps  see jdk Display data #  install jdkrpm -ivh jdk-7u80-linux-x64.rpm

 


6. top command

Displays information about the processes currently being executed by the system , Including process ID、 Memory usage 、CPU Occupancy rate, etc

Common parameters :

 

-c  Show full process commands -s  Confidentiality mode -p < Process number >  Specify the process display -n < frequency > Number of cycles 

 

 

example :

 

top - 14:06:23 up 70 days, 16:44,  2 users,  load average: 1.25, 1.32, 1.35Tasks: 206 total,   1 running, 205 sleeping,   0 stopped,   0 zombieCpu(s):  5.9%us,  3.4%sy,  0.0%ni, 90.4%id,  0.0%wa,  0.0%hi,  0.2%si,  0.0%stMem:  32949016k total, 14411180k used, 18537836k free,   169884k buffersSwap: 32764556k total,        0k used, 32764556k free,  3612636k cachedPID 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

 


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

first line , Task queue information , Same as uptime Command execution results , The specific parameters are as follows :

14:06:23 — Current system time

up 70 days, 16:44 — The system is already running 70 God 16 Hours 44 minute ( During this period, the system did not restart !)

2 users — The current is 2 Users log in to the system

load average: 1.15, 1.42, 1.44 — load average The next three numbers are 1 minute 、5 minute 、15 Minute load .

load average The data is every 5 Check the number of active processes per second , The value calculated according to the specific algorithm . If this number is divided by logic CPU The number of , Results higher than 5 It means that the system is overloaded .

The second line ,Tasks — Mission ( process ), The details are as follows :

System now shared 206 A process , Some of them are in operation 1 individual ,205 Sleeping (sleep),stoped There are 0 individual ,zombie state ( Corpse ) There are 0 individual .

The third line ,cpu State information , The specific attributes are as follows :

 

5.9%us —  User space occupancy CPU Percent of .3.4% sy —  Kernel space footprint CPU Percent of .0.0% ni —  Change the priority of the process occupied CPU Percent of 90.4% id —  Free CPU percentage 0.0% wa — IO Waiting for occupation CPU Percent of 0.0% hi —  Hard interrupt (Hardware IRQ) Occupy CPU Percent of 0.2% si —  Soft interrupt (Software Interrupts) Occupy CPU Percent of 

 


remarks : ad locum CPU Usage ratio and windows Different concepts , You need to understand linux Knowledge of system user space and kernel space !

In the fourth row , Memory status , The details are as follows :

 

32949016k total —  Total physical memory (32GB)14411180k used —  Total memory in use (14GB)18537836k free —  Total free memory (18GB)169884k buffers —  Amount of memory cached  (169M)

 


The fifth row ,swap Exchange partition information , The details are as follows :

 

32764556k total —  Total exchange area (32GB)0k used —  Total swap area used (0K)32764556k free —  k free (32GB)3612636k cached —  Total number of swap buffers buffered (3.6GB)

 


Sixth elements , Blank line .

Below line 7 : Processes ( Mission ) Status monitoring of , The project line information is described as follows :

 

PID —  process idUSER —  Process owner PR —  Process priority NI — nice value . Negative value indicates high priority , A positive value indicates a low priority VIRT —  Total virtual memory used by the process , Company kb.VIRT=SWAP+RESRES —  Used by process 、 Physical memory size not swapped out , Company kb.RES=CODE+DATASHR —  Shared memory size , Company kbS —  Process status .D= Uninterrupted sleep  R= function  S= sleep  T= track / stop it  Z= Zombie process %CPU —  Last updated to now CPU Percentage of time used %MEM —  Percentage of physical memory used by the process TIME+ —  Used by process CPU Total time , Company 1/100 second COMMAND —  Process name ( Command name / Command line )

 


top Interactive commands

 

h  Show top Interactive command help information c  Toggle display command name and full command line m  Sort by memory usage P  according to CPU Sort by percentage size T  According to time / Sort the cumulative time W  Write current settings to ~/.toprc In file o perhaps O  Change the order in which items are displayed 

 


7. yum command

yum( Yellow dog Updater, Modified) It's a Fedora and RedHat as well as SUSE Medium Shell Front end package manager .

Based on RPM Package management , Can be automatically downloaded from the specified server RPM Package and install , Dependency relationships can be handled automatically , And install all the dependent packages at once , No need to download it over and over again 、 install .

yum Provides search 、 install 、 Delete a 、 A set or even a whole package of commands , And the command is simple and easy to remember .

    1. List all updatable software list commands :yum check-update
    2. Update all software commands :yum update
    3. Install only the specified software commands :yum install <package_name>
    4. Update only the specified software commands :yum update <package_name>
    5. List all installable software list commands :yum list
    6. Delete package command :yum remove <package_name>
    7. Find package command :yum search
    8. Clear cache command :
        yum clean packages: Clear package in cache directory
        yum clean headers: Clear... From the cache directory headers
        yum clean oldheaders: Clear the old... In the cache directory headers
        yum clean, yum clean all (= yum clean packages; yum clean oldheaders) : Clear the packages and old ones in the cache directory headers

example
install pam-devel

 

[[email protected] ~]# yum install pam-devel

 

11、 ... and 、 Backup compression command
1. bzip2 command

    establish *.bz2 Compressed files :bzip2 test.txt .
    decompression *.bz2 file :bzip2 -d test.txt.bz2 .

2. gzip command

    Create a *.gz The compressed file of :gzip test.txt .
    decompression *.gz file :gzip -d test.txt.gz .
    Shows the compression ratio :gzip -l *.gz .

3. tar command

Used to compress and decompress files .tar It has no compression function , It only has packaging function , About compression and decompression is to call other functions to complete .

Figure out two concepts : Pack and compress . Packaging refers to turning a large number of files or directories into a total file ; Compression is to transform a large file into a small file through some compression algorithms

Common parameters :

 

-c  Create a new compressed file -f  Specify the compressed file -r  Add files to a compressed package -u  Add changes and existing files to the package -x  Extract files from a compressed package -t  Show the contents of the compressed file -z  Support gzip Compress -j  Support bzip2 Compress -Z  Support compress Unzip the file -v  Display operation process 

 


of gzip And bzip2 Compress :

 

gzip  example : Compress  gzip fileName .tar.gz  and .tgz   decompression :gunzip filename.gz  or  gzip -d filename.gz           Corresponding :tar zcvf filename.tar.gz     tar zxvf filename.tar.gzbz2 example : Compress  bzip2 -z filename .tar.bz2  decompression :bunzip filename.bz2 or bzip -d filename.bz2        Corresponding :tar jcvf filename.tar.gz          decompression :tar jxvf filename.tar.bz2

 


example :
(1) Pack all the files into tar package

 

tar -cvf log.tar 1.log,2.log  or tar -cvf log.*

 


(2) take /etc Package all the files and directories under to the specified directory , And use gz Compress

 

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

 


(3) View the contents of the file just packed ( Be sure to add z, Because it's using gzip Compression of the )

 

tar -ztvf /tmp/etc.tar.gz

 


(4) To compress and pack /home, /etc , But don't /home/dmtsai

 

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

 


4. unzip command

    ·  decompression *.zip file :unzip test.zip .
    ·  see *.zip The content of the document :unzip -l jasper.zip .