preface
- This article also cost me a lot of effort. First of all, I want to make it clear that at least more than 100% of the knowledge points in this article before I write this article are not clear. Moreover, the total number of words after writing this article is no more than 24 hours, with a statistics of more than 27800 words and more than 1240 lines. I feel cool and tired after writing this article, So it's more than enough to finish linux in one day except shell programming.
- The main purpose of my writing this article is to have a better absorption effect. In short, the completion of this article is certainly not enough. For example, a lot of knowledge is not comprehensive. In fact, there is no need to write comprehensive. Basically, it is just to write in the commonly used knowledge points.
- In short, it is because of my knowledge limitations. After all, I learned it now. Then, in addition, the writing time is not long. I just slip away after a rough look at the typesetting. Therefore, the problems or omissions in the article are welcome to comment
linux foundation
terminal
It is our common command-line interaction mode, such as the ugly cmd of Windows, powershell, etc. anyway, the command interaction is called the terminal, and most of our use of linux is based on the terminal
The terminal is divided into device terminal, physical terminal, virtual terminal, graphic terminal, serial terminal and pseudo terminal. We connect the server through ssh protocol through terminal tools and use pseudo terminal
shell and command prompt
- Shell is the interpreter of linux system, which is similar to the compiler in programming. The source code written in high-level language needs to be compiled into binary code that can be understood by the computer through the compiler, so as to achieve the purpose of execution. The shell is similar to this function. The shell is an interface to interact with the kernel. It converts the commands we enter into into binary data that the computer can understand and execute. The common shell in linux is bash. Of course, there are many other shells
Common Linux shell s: sh, bash, csh, tcsh, ash
Different organizations have developed different shells. They have their own advantages. Some occupy less resources, some support advanced programming functions, some have good compatibility, and some pay attention to user experience. We can also regard the shell as a language. Bah, it is a language, and it also has any loop conditions in its syntax. It is an interpretative script language similar to php and python. It is commonly understood as a software connecting the system kernel to the user
cat /etc/shells //Use this command to view a list of shell s
You can view the default shell of the current device by using the echo $SHELL command. Obviously, my Ubuntu uses bash by default. As for why / bin/bash is, it is related to the role of the bin file, which I will talk about later
Of course, you can also cd to the bin directory to print out the bash. It's certainly not easy to understand. It's best to experience it. It's like playing with a toy racing car when you were a child. Although you can't understand the circuit board inside after you open the shell of the toy, there is still a driving force to drive you to open it, And it's not as easy to break as toys. If you play with your system, you can reinstall it. Moreover, linux is still open source, which is too much
-
Replace default shell
chsh //Enter the command, and then enter the password to change the default shell
Here I share some problems I encountered when I modified the default shell. At first, after I modified the default shell, I entered echo @SHELL and found that my default shell had not changed. I always thought there was something wrong with my operation. As a result, I didn't restart. Then I switched the shell to a specific file format, such as "/ bin/bash", Bash is just a file under the bin file. Remember the core tenet of linux, "everything is a file", which my master told me
Another trick is to remember this command, chsh == change shell, which is easier to remember, isn't it
command prompt
This is the small box in front of the input command
┌──(kali㉿kali)-[~] └─$
among kali@kali , the previous Kali represents the user name, the latter Kali represents the host name, [] represents the current path, which means the home path. The KaTeX parse error: Expected 'EOF', got '#' at position 16: at the place where the command is entered immediately indicates the user with what permissions you are now`# ̲ Number represents that the current user has the highest permission`
As mentioned here, I'll talk about absolute paths and relative paths by the way
/ :Root directory character . :Current directory character .. :Parent directory character ~ : Home directory symbol (home directory is different for different users), for example root User's~The absolute path is/root,and kali User's~yes/home/kali,pysnow User's~yes/home/pysnow Absolute path: the path must be written by the root directory / Written, e.g /var/www/html Relative path: the path is not written by the root directory / It is written by the parent directory(.),Home directory(~)It's written at the beginning. For example, I execute it pwd The command knows. My absolute path now is/usr/lib,Then I want to use it in the current directory cd ./php,Where did you switch? The answer is/usr/lib/php,So this./It's equivalent to/usr/lib,Why use this relative path? Of course, it's for convenience For example, your current path is/var/www/html/898wdahwdw89ydhwh/var/www/html,You want to switch to/var/www/html/898wdahwdw89ydhwh Up the path, you are the choice cd ../../../,Or choice cd /var/www/html/898wdahwdw89ydhwh,The answer is obvious, isn't it
Linux basic commands
Command format
command [option] [ARGUMENTS...]
Query command help: COMMAND --help or man COMMAND
Command completion function: when only a part of the command is input, press the tab key to complete the command. If there is no response, it is because there are more than one candidate command. Double clicking the tab can display all commands starting with the current input content. For example, enter system, press tab once, and it will be automatically completed into system CTL. Completion function It can also be used on the path. When you encounter a name that is strange and difficult to type, you can only enter the first few words, and then use the automatic completion function to complete the file name, which greatly reduces the fault tolerance of your input commands and improves the efficiency
- Options: used to enable or disable one or more functions of the command
Short options: - c for example: - L, - H, - P, - D, etc. start with a single cross post and the options are one character
Long options: – word, for example: -- help, -- name, -- dbs, etc
Parameter [ARGUMENTS]: note of the command:
Multiple options and multiple parameters and commands are separated by white space characters
Cancel and end command execution: Ctrl+c (forced end), Ctrl+d (normal exit)
Multiple commands can be separated by; symbols
The demonstration is as follows:
Simple command
-
date displays the current time
-
cal display calendar
-
halt,shutdown -h now,poweroff
-
reboot restart
-
whoami view current user name
-
who view all current online sessions
-
w view all online sessions and ongoing operations (executing commands) of the current system
-
tty to see what terminal number is currently used
- ls command is one of the most commonly used commands in Linux. It is short for list source. This command simply shows the files and directories in the directory.
-
The cd command is also one of the most commonly used commands. The function of cd is very simple. It is to switch the current directory, just like the cd in the cmd of window
-
As mentioned earlier, apt is Ubuntu and Debian, Kali's package manager (in short, it means automatically loading software). The significance of the package manager is that many software development on Linux will use many of the same system call functions, such as file IO and memory call, so there is no need to repeat the development of such duplicate things, so they are stored in the general library, but not all libraries exist in the system by default. Different software can be used Different library files can be used, which is called software dependency, and apt is used to solve this problem. If apt is used to install software, it will automatically help users deal with dependency problems and automatically install various dependencies required by the software. In this way, it will save users a lot of trouble. In addition, there are others
apt update refresh repository index
apt upgrade upgrades all upgradeable packages
Apt install < app name > install app
Yum list < app name > List apps//Here, you can use wildcards to search for applications, such as apt list apache *, which can search for all applications starting with apache
Apt remove < app name > delete app
Apt reinstall < app name > reinstall app
apt command | Superseded command | Function of command |
---|---|---|
apt install | apt-get install | Install package |
apt remove | apt-get remove | Remove package |
apt purge | apt-get purge | Remove packages and configuration files |
apt update | apt-get update | Refresh repository index |
apt upgrade | apt-get upgrade | Upgrade all upgradeable packages |
apt autoremove | apt-get autoremove | Automatically delete unwanted packages |
apt full-upgrade | apt-get dist-upgrade | Automatically handle dependencies when upgrading packages |
apt search | apt-cache search | Search application |
apt show | apt-cache show | Show installation details |
linux file system
Linux is very different from the file system of windows system. In Linux, many basic commands are related to the file system. The file system of Linux is very different from the well-known windows file system, which is mainly reflected in the following aspects:
First, the path name separator is different. The directory separator of linux is * * / * *, and the directory separator of Windows system is * *
The structure of the path is different. The absolute path of Windows consists of two parts, namely, the partition name and the path in the disk, while linux has only a unique root directory, which is a tree file structure divergent from the root directory
Functions of some fixed directories in linux:
/boot:Boot file storage directory, kernel file(vmlinuz),boot loader (bootloader, grub)Are stored in this directory /bin:Basic commands for all users;Cannot be associated to a separate partition, OS Start the program that will be used /sbin:Basic commands of management class;Cannot be associated to a separate partition, OS Start the program that will be used /lib:The basic shared library files and kernel module files that the program depends on at startup (/lib/modules) /lib64:Dedicated to x86_64 Secondary shared library file storage location on the system /etc:Profile directory /home/USERNAME:Ordinary user home directory /root:Administrator's home directory /media:Portable mobile device mount point /mnt:Temporary file system mount point /dev:Storage location of equipment files and special files /opt:Installation location of third-party applications /srv:Data used by services running on the system /tmp:Temporary file storage location/proc: Virtual file system for outputting kernel and process information/sys:Used to output information about hardware devices on the current system virtual file system /selinux: security enhanced Linux,selinux Storage location of relevant security policies and other information usr: universal shared, read-only data bin: Application program provided to ensure that the system has complete functions sbin: ditto lib:32 Bit usage lib64:Only 64 bit systems exist include: C Program header file(header files) share:Structured independent data, e.g doc, man etc. local:Installation location of third-party applications /var: variable data files cache: Application cache data directory lib: Application status information data local:Dedicated to/usr/local Applications under store variable data; lock: Lock file log: Log directory and files opt: Dedicated to/opt Applications under store variable data; run: Running process related data,Typically used to store processes pid file spool: Application data pool tmp: Save temporary data generated between system restarts
File types under linux
-: normal file
d: Catalog file
b: Block device
c: Character device
l: Symbolic link file
p: Pipe file pipe
s: Socket file socket
Where do you see this file type? Enter ls -l
In the leftmost column, the first character is basically * * - * * d l. These are the file types of the file, followed by the permission to change the file, including the read permission and the write permission
Detailed usage of ls command
ls -a Display all files in the current directory (including hidden files, saved).The first file or directory is called a hidden file/Table of contents) ls -l Display detailed information ls -R Recursively display all non hidden directories of the current directory/File (execute carefully. Many file card screens will appear at once. If they appear, you can press Linux Forced end key combination Ctrl + c To prevent the command from continuing) ls -ld Show directory only ls -1 Document line display ls –S Sort by size ls –t Press mtime sort ls –u coordination-t Options, display and press atime Sort from new to old ls –U Display by directory storage order ls –X Sort by file suffix
Common wildcards:
The wildcard is a kind of matching rule for directory / file names, which is easy to understand. People like us who often inject commands should know better. There are many ways to write wildcards. Here are some of the most commonly used:
*Matches zero or more characters
? Match any single character
[0-9] matching number range
For example, what has a flag PHP file, you can't directly enter the four characters of flag, but you can use wildcards to achieve the same purpose, that is, fla *, f??????? etc.
Another image example is that when you play the game, you feel that a teammate is unhappy, and then you button and scold the past. As a result, the game turns all your words into * * *. You know what this wildcard meansWhat is within bi? This wildcard can be anything. It may mean what you want, or it may mean completely another meaning, so you need to give it more description to make its meaning limit smaller
This is the actual operation of wildcards. Of course, you can also experiment on your own linux system
Common file operation commands and tools
cp Copy: Option parameters: -i:Prompt before overwrite –n:Do not overwrite, pay attention to the order of the two -r, -R: Recursively copy the directory and all the contents inside -a: Archive, equivalent to-dR --preserv=all -d:--no-dereference --preserv=links Do not copy the original file, only copy the link name --preserv[=ATTR_LIST] -p: equivalent--preserv=mode,ownership,timestamp -v: --verbose -f: --force Usage: cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... cp SRC DEST Note: OPTION Represents a parameter, SRC(SOURCE)Represents the copy source, that is, the copied file or directory, DEST Indicates the copy target, that is, the directory or file to which you want to copy, DIRECTORY Represents a directory
Just look at the principle is not enough, or you have to operate it
cp flag.php flag1 //Set the file flag Copy PHP to the current directory and rename it to flag1 ls //It is found that there is an extra flag1 in this directory, and flag PHP still exists cp -r ./* /tmp //Copy all files or folders in the current directory to / tmp, where - r means recursive copy, which means recursive copy of the directory and all its contents ls /tmp and ls //It is found that the echo of the two commands is the same, indicating that the complete replication is successful cp 517pysnow flag.php flag123 mysql ./test/ //Copy multiple files to the test folder of the current directory at the same time ls ./test //Found the file 517pysnow flag PHP flag123 mysql, indicating that the operation is correct
mv move / rename
Option parameters:
-i: Interactive, prompt whether to overwrite
-f: Force move. If there is a file with the same name, it will be overwritten
The usage logic is basically the same as that of cp, so please refer to the above cp command for logic
It is also a practical operation. As long as the cp command is OK, it will be OK
rm delete
Have you ever heard of such a string of code, from deleting the library to the expression package running away
sudo rm -rf /*
In fact, the syntax is almost the same. For these three commands, just remember the specific usage of one command, and then compare it with other codes
df disk usage view command
This is a very common directory, where-h It is to convert the output content into content that is convenient for people to read, that is, direct execution df In bytes( B)To show disk occupancy, plus-h How much can it be displayed G,Easier to read
apt system package management tool
I have briefly talked about this tool before. In fact, this tool needs more knowledge to understand its underlying principle. At least it needs to know what is called "library" and what is called "dependency". Anyway, it involves a lot. If you are interested, you can baidu Google by yourself
You can add a - y at the end of the apt command to indicate the default consent request
When you use apt tool to install an application, it will ask you yes/no. at this time, if you add this - y, it will help you fill in this yes and will not ask you again
I didn't ask you yes/no this time. I installed it directly with one click. Although this function is useless, it's still good to remember. It's not difficult anyway
lrzsz upload and download tool
The server uploads files not only by ftp, but also by other tools, such as lrzsz, which has stable transmission speed. These performance aspects are not much worse than ftp transmission. As for the principle, you can search the network communication principle and the logic of ftp and lrzsz
usage method:
First use apt perhaps yum Tools will lrzsz Download it sudo apt/yum install lrzsz -y This tool has only two commands sz: Download files from the server sendzipper,I call it sending files from the server rz: Upload file to server receivezipper,Accept files on server Is it easy to remember? Let's actually operate it
-
First, open the / var/www/html directory and find an index.html file. We will experiment with that file
cd /var/www/html
-
Send files on the server side
sz ./index.html
-
Then a dialog box will pop up
This will save the file
-
The next step is to upload the file to the server
rz ./ //Accept files to current directory
zip/unzip compression and decompression tool
Installation: sudo apt/yum install zip -y sudo apt/yum install unzip -y You can also directly sudo apt/yum install unzip zip -y
One thing to note here is that when decompressing, you should use the - O parameter to indicate the encoding method, otherwise it will be garbled, because the default encoding method of linux is ans
--Compress the file a into a.zip
zip a.zip a
--Compress the file a b c into a.zip
zip a.zip a b c
--Compress the directory TMP into tmp.zip (- r option is used to compress the directory)
zip -r tmp.zip tmp
--Unzip the a.zip file
unzip a.zip
tar compression
Similar to zip, tar is the most common compressed package compression tool in linux. The compressed package file ends with. Tar. Besides gzip and bzip2 for the first time, in short, these tools can be used as good tools for source code backup, and the three tools are often used together. Generally speaking, the combined use is to package multiple files into one file through tar, and then call gzip or bzip2 to package them To generate a compressed package with. tar.gz or. tar.bz2
Packing compression tar [option] [Compressed file name] [File name to be compressed] Unpack and decompress tar [option] [The name of the file to unzip] [option2] [Decompression path] //If the decompression path is not selected, it is extracted to the current path by default
-c Package and generate archives -x Unpack, unpack the file -v List the detailed process of archiving and de archiving and display the progress -f Specify the file name. If there are multiple options, this option must be placed last -z call gzip Command to compress or decompress -j call bzip2 Command to compress or decompress -C Specify the decompression directory. Note: the directory must already exist.
*Redirect
What is the redirection of linux shell? As the name suggests, it is to reposition the direction. What direction is to locate? That is, the direction of input and output. In other words, the redirection of linux shell is to change the direction of input and output
Next, let me talk about input and output
Input generally means that you input data through the keyboard, and then the shell interprets and compiles the data you enter, and then sends it to the kernel for operation. This is the standard input direction, that is, the relationship between the keyboard and the program
On the contrary, the output is that the computer reflects the calculated results on the external display screen through intermediate agents such as shell. This is called output, which is the relationship from program to display screen
File descriptor
Everything in linux is a file, including the hardware devices you use for input and output. linux assigns an ID to each open file, also known as a composition descriptor,
When Linux programs perform any form of I/O operations, they are reading or writing a file descriptor. A file descriptor is just an integer associated with the open file. Behind it may be an ordinary file, FIFO, pipeline, terminal, key disk, display, or even a network connection on the hard disk. stdin, stdot, stderr are on by default Yes, you can operate them directly
Output redirection
Usually, our output results are directly displayed on the display screen, that is, the output with the display screen. However, sometimes, in order to facilitate sorting out the output content, such as the operation log of a website, you say you directly display the output content through the shell, which you usually don't use. Only when there is a problem, You will remember to find the output results for a few days. At this time, you only output these output results without storing them, so you have no place to view them. It's very uncomfortable, isn't it? So we want to store all these output contents in a file. When we want to view them, Just print out the contents of this file
So to summarize: why do we redirect output? Because there are some output results, we don't want them to be displayed directly on the display screen, but store them, which is output redirection
Standard output redirection: command > file //Relocate the output result of executing the command in the form of overwrite and output it to the file file command >> file //Reposition the output result of executing the command in the form of superposition and output it to the file file Error output redirection: command 2> file //Relocate the output result of the error executing the command in the form of overwrite and output it to the file file command 2>> file //Reposition the output result of the error executing the command in the form of superposition and output it to the file file Correct error output and redirection: command >file 2>&1 //Relocate the correct and error results of the output of the command to the file file in the form of overwrite command >>file 2>&1 //Relocate the correct and error results of the output of the command to the file file in the form of superposition command >file1 2>file2 //Save the correct output results in file1 and the wrong output information in file2 command >>file1 2>file2 //Save the correct output results in file1 in superposition mode and the wrong output information in file2 in superposition mode
matters needing attention
- The redirector > indicates overlay and > > indicates overlay
- The '&' symbol in 2 > & 1 here represents the meaning of escape, which means to escape the following one into a file descriptor
- If the standard output is not specified, it defaults to 1, that is, it should be written as command 1 > file in command > file, but it is omitted here
- The file descriptor must be next to the directional symbol
input redirection
What is the operation of input redirection? We can know that generally the input data is typed by the keyboard, and this input redirection is not to let the data entered by the keyboard be read, but we specify to read the input data
Standard input redirection: command < flie //Execute the overwritten form in file as the input data of command command << end //Always read the command of the keyboard, and stop reading data until it meets the end character. The end character here is "end". Of course, this end character can be customized command <file1 >file2 //Take the contents in file1 as the input of command, and save the standard output results to file2 file
matters needing attention
- If the standard output is not specified, it defaults to 0, that is, the command < file should have been written as command 0 < file, but he omitted this 0 here
- Enter the redirection symbol < <. The function of this symbol is to use a specific delimiter as the end flag of command input instead of Ctrl+D
- < < the following delimiter can be defined freely. As long as the same delimiter is encountered again, the content between the two delimiters will be used as the input of the command (excluding the delimiter itself)
*Pipeline
linux pipeline character "|"
definition
- Use the pipe character "|" provided by Linux to separate the two commands, and the output of the command on the left of the pipe character will be used as the input of the command on the right of the pipe character
I suggest you write the one I wrote first linux redirection article Take a look at the previous output concept, which is helpful to understand the function of this pipeline symbol
- When multiple pipeline symbols appear, the output result of the command execution in the first pipeline symbol is redirected as the input of the previous command in the second pipeline symbol, and so on~~
matters needing attention
commandA | commandB
-
This pipeline character can only redirect the standard output, not the error output, which means that the output result will be used as the input of the following command only when the previous command can be executed
-
The command to the right of the pipe character must be able to accept the input command
summary
- In fact, it seems that the function of pipeline symbol is the same as that of input-output redirection, that is, changing the direction of output and input, but there are also differences
- For example, the pipeline symbol executes two processes at the same time, that is, the commands on both sides of the symbol are one process, while the redirection symbol > has only one process
- The redirection output of the redirector can only be a file, that is, command < file, but the pipeline can be a command
- The pipe character can only redirect the standard input and standard output, and redirection has more redirection function of error output than it
- Of course, output redirection can only be followed by files, that is, command > file
*User authority = > User Management & authority control
introduce
linux is a multi-user system, which arranges corresponding permissions for each user, so as to better manage files. For example, a user assigns a class of files, so that this class of files can only allow specific users to carry out sensitive operations, so as to prevent other files from being affected and the system from running down due to misoperation
Here I will first introduce some simple terms of user groups
- Uid: user identifier. Each user has a specific value. This is to make it easier for the kernel to call information about your user during execution. Different users generally have different UIDs. For example, the uid of root is 0 by default, and the uid of ordinary users is 500-6000, but some linux starts from 1000, such as kali, Then between the two users is the pseudo user's uid
- gid: the meaning of group indicator is the same as that of user indicator, which can be understood by analogy
- Landing shell: This is discussed in detail in another article. It is an application that connects the system kernel to the user
linux users:
linux user types
-
Super user: root, uid=0, the highest authority management user. You can modify the permissions of other users. By default, it is the highest authority for all files, that is, read-write execution
root Is all classes Unix The administrator of the system has the highest authority, so it will be very convenient in our daily use. There will be no problem of insufficient authority above, but the relative security risk is also greater. Sometimes it is because root A wrong command executed by the user leads to an irreversible crash of the system. In a word, it has great ability and greater responsibility -pysnow,Everyone is using it root Users must be careful when, especially when operating some system files
-
Ordinary user: has limited permissions of the operating system, and the UID value is 500 – 6000
There can be multiple ordinary users. The permissions of ordinary users are limited. For example, some files in the root directory only have read permissions, and some sensitive files only have execution but no read permissions. Then, this ordinary user is different from the pseudo user. He has a password, which is commonly known as the login password. It is also used shell And each ordinary user has his own home directory, which is generally located in/home A folder with the same name as your user in the directory. For example, my ordinary user name is kali,Then my home directory is/home/kali,This home directory can be used~Instead, of course, this home directory does not have to be consistent with your user name. You can modify it. Why should we have this ordinary user? Firstly, it must be to ensure safety and prevent misoperation. Secondly, it is convenient for management. For example, if you hand over your system to multiple people, you can't directly use it root Give it permission. You must give it a user with relatively low permission, so that it can not only enjoy some services brought by the system, but also prevent them from damaging their own system. Take several practical examples, such as the administrator account, teacher account and student account of the campus network. They have different permissions, super control in the live broadcasting room, ordinary bullet screen users, etc
-
Pseudo user: a permanent user specially created to meet the needs of the system process. Since there is no shell assigned to him, it cannot be used for login operation. The uid is 1-499
It is also called system or service users. Generally speaking, the role of these users is to meet the permission needs when executing a system process. Some system files ordinary users do not have permission. Therefore, in order to execute this command, higher permission needs to be allocated, but it can not be too high, as high as root Users do that, so they will execute it for different users according to different functions *Generally speaking, a command or service corresponds to a pseudo user *Pseudo users are not only used to execute system related processes, but also enable some third-party service functions, such as website services. Some of them may need higher permissions than ordinary users. Therefore, when installing this service, a pseudo user will be added to your system by default to make the service run normally *When you execute an operation command, it will be executed in the name of a specific user. When you log in with an ordinary user, you want to execute it reboot The command to restart the system is not allowed, but why is it allowed when operating? It is because you execute the command as one of the pseudo users of the system Common system pseudo users are as follows: bin Have executable user command files sys Own system files adm Own account file uucp UUCP use lp lp or lpd Subsystem usage nobody NFS use
You can use the cat /etc/passwd command to view the details of all users of the current system
linux user management
Add user
useradd [option] User name
option Options: -c comment Specify an annotative description. -d Directory specifies the user's home directory. If this directory does not exist, it will be used at the same time-m Option to create a home directory. -g User group specifies the user group to which the user belongs. -G User group. User group specifies the additional group to which the user belongs. -s Shell File specifies the user's login Shell. -u User number specifies the user number of the user, if both exist-o Option, you can reuse the identification numbers of other users.
example
-
useradd -c Blog specific example users pysnow
You can see that this comment is a string of descriptions added to the user. In fact, it has no effect except to facilitate the understanding of the user's functions, so as to prevent you from not knowing which user is used for what when you create more users
-
xxxxxxxxxx useradd -u 1314 -g 1111 -s /usr/bin/bash -dm /home/example pysnow
matters needing attention
-
If you do not specify anything except the user name when creating a user, it will default to the following results
comment The information of is empty or* Home directory defaults to/home In the folder with the same name as the currently created user uid It will default to the highest of all current users uid Add 1 on the basis of, for example, the users in my current system uid The largest value is 1314, so I pass useradd example Command to create the user, its uid It should be 1315 gid Default to uid The same unless you actively configure or modify it, and when you pass-g When adding a user group, select gid Must already exist bash Default use/bin/sh
- When two or more users with the same uid are created through the - o option, these users will be regarded as one user, but the functions of these users will not be affected, that is to say, these users are still separated from each other in terms of functions
-
-
delete user
Deleting a user is actually deleting part of the file information, that is, deleting the information about the user in / etc / passwd and / etc / shadow
Command
```bash
userdel [option] username
```
common option Options are-r,That is, delete recursively, and delete the user's home directory together userdel -r user name
Modify user
Modify the user's attributes, that is, the attributes mentioned in useradd above
usermod [option] user name common option Above -c comment Specify an annotative description. -d Directory specifies the user's home directory. If this directory does not exist, it will be used at the same time-m Option to create a home directory. -g User group specifies the user group to which the user belongs. -G User group. User group specifies the additional group to which the user belongs. -s Shell File specifies the user's login Shell. -u User number specifies the user number of the user, if both exist-o Option, you can reuse the identification numbers of other users.
Manage user passwords
That is to manage the user's login password. By default, the user we created through the useradd command does not have a password, that is, there is no login password. It is locked by another system and cannot log in and use. Therefore, in order to log in and use the new user, we must add a password for it
passwd [option] user name //Modify the passwords of other users. Generally, the root user is used for operation passwd [option] //Modify the default user name, that is, the current user
Common option s are as follows
-l(lock) Lock the password, that is, disable the account. -u(unlock) Password unlock. -d(delete) Make the account no password. -f(force) Force the user to change the password at the next login.
matters needing attention
- When an ordinary user changes his password for himself, he will ask the current user's password, which is similar to qq changing password
- But when you use root to change the password for others, you won't ask. It's similar to qq's recall password function
- When you use the - d option to change the password of a user or your current user to none, the system will not let you log in by default when you try to log in again. You can also use the - l option to achieve the same purpose of not being allowed to log in
linux user properties
user attribute
User name: a string representing the user account. It is usually no longer than 8 characters and consists of upper and lower case letters and/Or numbers. The login name cannot have a colon(:),Because the colon is a separator here. For compatibility, it is best not to include dot characters in the login name(.),And do not use hyphens(-)Plus sign(+)Take the lead. Password: the login password of the user name. In some systems, the encrypted user password is stored Although this field only stores the encrypted string of the user password, not clear text, but because/etc/passwd The file is readable to all users, so this is still a security risk. So now many Linux System (e.g SVR4)All used shadow Technology to store the real encrypted user password in/etc/shadow File, and in/etc/passwd Only one special character is stored in the password field of the file, such as“ x"Or“*" User identifier(uid):Is an integer that is used internally to identify users. Generally, it corresponds to the user name one by one. If the user identification numbers corresponding to several user names are the same, they will be regarded as the same user within the system, but they can have different passwords, different home directories and different logins Shell Wait. Generally, the value range of user ID is 0~65 535. 0 Super user root Identification number of, 1~99 It is reserved by the system. As a management account, the identification number of ordinary users starts from 100 Linux In the system, the limit is 500. Group identifier: similar to the user identifier, it represents the group to which the user belongs, and/etc/passwd Is with/etc/group Corresponding comment(Annotative description):Similar to the comments in programming, it will not run when compiling and running, but it can help others quickly understand the code. The field records some personal situations of users. For example, the user's real name, telephone number, address, etc. this field has no practical use Linux The format of this field is not uniform in many systems Linux In the system, this field stores an arbitrary annotative description text for finger Output of the command. Home directory: the user's starting working directory. It is the directory where the user is located after logging in to the system. In most systems, the home directory of each user is organized in the same specific directory, and the name of the user's home directory is the login name of the user. Each user has read, write and execute (search) permissions on his own home directory, and the access permissions of other users to this directory are set according to the specific situation. land shell: After the user logs in, it is necessary to start a process, which is responsible for transmitting the user's operation to the kernel. This process is the command interpreter or a specific program that the user runs after logging in to the system, that is Shell. Shell Are users and Linux Interface between systems. Linux of Shell There are many kinds, each with different characteristics sh(Bourne Shell), csh(C Shell), ksh(Korn Shell), tcsh(TENEX/TOPS-20 type C Shell), bash(Bourne Again Shell)Wait. The system administrator can specify a user according to the system conditions and user habits Shell. If not specified Shell,Then the system uses sh Is the default login Shell,That is, the value of this field is/bin/sh. User login Shell It can also be specified as a specific program (this program is not a command interpreter). Using this feature, we can limit the user to run only the specified application. After the application runs, the user will automatically exit the system Linux The system requires that only those programs registered in the system can appear in this field. *Pseudo user: These users are/etc/passwd There is also a record in the file, but they cannot log in because they are logged in Shell Empty. Their existence is mainly to facilitate system management and meet the requirements of corresponding system processes for file ownership.
User related documents
-
In the / etc directory of linux, there is a file called passwd, which stores the information of all users of the current system, that is, user attributes
-
Similarly, in the current / etc directory, there is a file called shadow, which is used to encrypt the information after the user password. Generally, ordinary users do not have access
-
Similarly, under the current directory is a file called skel, which is a configuration file used to configure the default attributes when creating users
Next, I will explain the first two documents in detail
-
/etc/passwd file
user name:Password:User identification number:Group identification number:Annotative description:home directory:Sign in Shell example: pysnow:x:1314:1111::/home/example:/usr/bin/bash user name: pysnow Password: x User ID: 1314 Group ID: 1111 comment Description: None Home directory:/home/example land bash: /usr/bin/bash
You can see that each line in this file represents the information of a user. The information of each line is separated by semicolons
-
/etc/shadow file
Because the / etc/passwd file is readable by all users, if the user's password is too simple or the law is obvious, an ordinary computer can easily crack it. Therefore, Linux systems with high security requirements separate the encrypted password word and store it separately in a file. This file is the / etc/shadow file. It is only supported by super users Have the permission to read the file, which ensures the security of the user password.
/The record lines in / etc/shadow correspond to those in / etc/passwd one by one. It is automatically generated by pwconv command according to the data in / etc/passwd
Its file format is similar to / etc/passwd
Login name:encrypted password:Last modification time:Minimum time interval:Maximum time interval:Warning time:Inactive time:Failure time:sign example: pysnow:!:18973:0:99999:7::: Login name:"Login name"Is with/etc/passwd User account with the same login name in the file Encrypted password: the password field stores the encrypted user password, with a length of 13 characters. If it is empty, the corresponding user does not have a password and does not need a password when logging in; if it does not belong to the set { ./0-9A-Za-z }The corresponding user cannot log in. Last modification time: it refers to the number of days from a certain time to the last password modification. The time starting point may be different for different systems Minimum time interval: refers to the minimum number of days between two password changes. Maximum time interval: refers to the maximum number of days that the password remains valid. Warning time: the field indicates the number of days between the system warning the user and the official expiration of the user password. Inactive time: refers to the maximum number of days that the user has not logged in but the account can remain valid. Expiration time: the field gives an absolute number of days. If this field is used, the lifetime of the corresponding account will be given. After the expiration, the account will no longer be a legal account and can no longer be used to log in.
linux user group
Each user has one or more user groups (additional groups) belonging to him. The purpose of this is to facilitate management. For example, when your system has a large number of users, you can't manage them one by one. At this time, you can install your own needs and divide them into different groups. In this way, you can directly manage user information in batches through group operations in the future
In linux, the default is to automatically generate a group when generating users, and the group identifier (gid) is consistent with the user identifier (uid)
linux user group management
Add group:
groupadd [option] User group Commonly used option Options: -g GID Specifies the group identification number for the new user group( GID). -o General and-g Options are used together to represent the name of the new user group GID You can connect with existing user groups in the system GID Same.
Delete group:
groupdel User group
Modify group properties
groupmod [option] User group Commonly used option Options: -g GID Specify a new group ID for the user group. -o And-g Options are used together with the new user group GID You can connect with existing user groups in the system GID Same. -n New user group changes the name of the user group to a new name
linux user group related files
-
User grouping is a means to manage users and control access rights in Linux system.
-
Each user belongs to a user group; there can be multiple users in a group, and a user can also belong to different groups.
-
When a user is a member of multiple groups at the same time, the main group to which the user belongs is recorded in the / etc/passwd file, that is, the default group to which the user belongs when logging in, while other groups are called additional groups.
-
When a user wants to access a file belonging to an additional group, he must first use the newgrp command to make himself a member of the group to be accessed.
-
All information about user groups is stored in the / etc/group file. The format of this file is also similar to that of the / etc/passwd file. Several fields are separated by colons (:). These fields are:
Group name:Password:Group identification number:List of users in the group Group name: the name of the user group, consisting of letters or numbers/etc/passwd Like the login in, the group name should not be duplicate. Password: the field stores the password word encrypted by the user group. Generally Linux The user groups of the system do not have passwords, that is, this field is generally empty or empty*. Group ID: similar to user ID, it is also an integer, which is used internally to identify groups. Intra group user list: it is a list of all users belonging to this group, with commas between different users(,)Separate. This user group may be the user's primary group or an additional group.
linux user group note
-
As I said earlier, a user can have multiple user groups at the same time. In fact, multiple groups here are multiple additional groups, and there is only one group. How to say, a user can only correspond to one user group, but a user group can correspond to multiple users. In order to realize the operation of corresponding multiple users, the concept of additional groups appears, which means, This is why our virtual machines and ECS can raise permissions and switch root users, because all users in the same user group share permissions with each other
For example, kali in the figure here has an additional group, root
-
Users can switch to other user groups through newgrp. Of course, the premise is that the user group is your additional group
newgrp root //Switch to root group
File operation permission modification
We have learned the concept of users and user groups from the above, and then the permissions of these users and user groups are different
File permission description
In linux, each file has its permission settings, that is, what permissions it has for who and what permissions it has for those groups
You can use the ls -l command to view the permission information of the file
Total consumption 8 -rw-r--r-- 1 kali kali 210 12 December 17:17 test2 -rw-r--r-- 1 kali kali 13 12 December 6:53 test2~ -[jurisdiction] [User] [Group] ~~~~
On the left of each line of file information, there is a nine character character beginning with -. The corresponding permissions correspond to these nine permissions, then the user name and then the user group name
- The beginning of this is actually the file type
Permission user
root: It is superior to all users and has the highest permission by default user: User That is, the owner corresponding to each file. The owner user has all the permissions of this file group: Non affiliated users in user group: That is, other users belonging to the owner in the user group of this file will set some permissions other: Other users For the remaining users, these users will be assigned permissions separately. Generally speaking, the permissions of other users are basically none
file right
There are three kinds of permissions for files: r w x, that is, read, write, and execute. Of course, there is another one -, which means no permission
File permission assignment
These nine characters are divided into three groups. Each group corresponds to a user with permission. Each user with permission is assigned to three types of permissions, i.e
rwx rwx rwx user group other
- If you do not have permission, it will be replaced by -
Permission representation type
There are two ways to set the Linux file permission attribute, one is a number and the other is a symbol.
There are nine basic permissions for Linux files, namely owner / group / others. Each of the three identities has its own read/write/execute permissions.
The score comparison table of each authority is as follows:
- r:4
- w:2
- x:1
example:
-rwxrwx--- The above permission information can be decomposed into rwx rwx --- That is to say, both the owner and the group belong to rwx The three permissions have no permissions for other users. What is the number? owner = rwx = 4+2+1 = 7 group = rwx = 4+2+1 = 7 others= --- = 0+0+0 = 0 That's 770
File permission attribute operation command
chgrp
Role: change the file group Syntax: chgrp [-R] Group name file name Parameter options -R: Recursively change the file group, that is, when changing the group of a directory file, if you add-R The group of all files in this directory will be changed.
chown
You can change the file owner or the file group at the same time Syntax: chown [–R] Master name file name chown [-R] Owner name: the name of the owner group and the file name Parameter options -R: Recursively change the file group, that is, when changing the group of a directory file, if you add-R The group of all files in this directory will be changed.
chmod
-
The most commonly used permission operation command is used to modify the permission attribute of the file mentioned above
-
chmod modifies permissions in the two ways mentioned above, although I didn't write the second one
chmod [-R] xyz File or directory Options and parameters: xyz : This is the permission attribute of the number type just mentioned. It is rwx The addition of attribute values. -R : Recursion(recursive)Continuous change of, that is, all files in the secondary directory will be changed
Numeric change file properties
example:
chmod 777 test2 Modify file test2 The attribute of is the permission for all users to read, write and execute
Symbols change file properties
chmod | u g o a | +(accession) | r | File or directory |
---|---|---|---|---|
g | -(remove) | w | ||
o | =(setting) | x | ||
a |
example:
chmod a-x test2 That is, the execution permissions of all users are subtracted
Switch user command su
whoami:View the user name of the currently used user id: View the current user's uid Value, and the group to which it belongs who:View actionable users
sudo [command]: As Administrator root Execute command as su -[username]: Switching users is generally used for switching between ordinary users. The name in front of the user name-,Indicates the environment of the new user after switching to the target user, so it is recommended to add sudo su: Switch to root User, input required root User password exit: To return to the user before switching, you can also use ctrl+D replace
Text processing command
As the name suggests, it is a command for processing text information. Here I will briefly explain some frequently used text processing commands
grep
grep is a very powerful text filtering command. It supports regular expression and other matching methods. It mainly cooperates with the function of pipeline character for file search
for instance:
ls /bin|grep python
This line of command is to filter and output all the file names containing the string python in the bin directory
Of course, the grep command tool also has many option s. You can search other people's articles and explanations by yourself
grep [option] patten Specify file common grep parameter list -c Prints the number of matching lines per input file -l Print the name of each input file -n Provide the line number of the input line -i Ignore the case of letters in expressions. -v Reverse selection to output the line without configuration parameters -a : take binary File to text Search data by file
find:
Powerful file and directory search commands
In fact, the find command does not belong to the file processing command, but belongs to the file operation. However, I just wrote the grep command here. After looking at it, it seems that there is no content about find, so I will put the use of the find command here
find is usually used in conjunction with file operation commands, such as deleting files in batches
find route [option] "Search content"
route: It can be relative road strength or absolute road strength. In short, it should indicate which file directory to search in option basis: -name : Search by file or directory name -iname : Searches by file or directory name, case insensitive -size : Search by file size -user/group : According to owner/Group lookup -amin : Find by access time -cmin : Find based on the time when the file properties were modified -mmin : Find according to the time when the file content is modified -a : Both conditions are met at the same time -o : Either of the two conditions can be satisfied Search for: It varies according to the selected basis. Generally, it is the file name or directory name to be searched. Wildcards can be used for search
ln hard link and soft link
There are two link modes in linux: hard link and soft link. Link, as the name suggests, is something that connects files, similar to the URL of a website. Skills indicate the location of the page, that is, the location of the file. They can also pass parameters to the URL to achieve the purpose of file operation. This is link, and lu command is the link to generate files
Hard connection Hard connection refers to the connection through the index node. stay Linux In the file system of, no matter what type of file is saved in the disk partition, it is assigned a number, called the inode number(Inode Index). stay Linux In, multiple file names point to the same inode. For example: A yes B Hard link( A and B Are file names), then A In the catalog entry for inode Node number and B In the catalog entry for inode The node number is the same, i.e. one inode The node corresponds to two different file names, and the two file names point to the same file, A and B It is completely equal to the file system. Deleting one of them will not affect the access of the other. The function of hard connection is to allow a file to have multiple valid path names, so that users can establish a hard connection to important files to prevent "accidental deletion". The reason is as described above, because there is more than one connection to the index node corresponding to the directory. Deleting only one connection does not affect the index node itself and other connections. Only when the last connection is deleted will the connection between the data block of the file and the directory be released. In other words, the condition for the real deletion of files is that all hard connected files related to them are deleted. Soft connection Another connection is called symbolic connection( Symbolic Link),Also called soft link. Soft link files are similar to Windows It is actually a special file. In symbolic connection, the file is actually a text file containing the location information of another file. For example: A yes B Soft links for( A and B All file names), A In the catalog entry for inode Node number and B In the catalog entry for inode Different node numbers, A and B It points to two different inode,It then points to two different data blocks. However A All that is stored in the data block is B Pathname of (can be found based on this) B Directory entry). A and B There is a "master-slave" relationship between them, if B Deleted, A It still exists (because the two files are different), but it points to an invalid link.
ln [option] [File absolute path] Link file name option: -s :Create soft link
Practical examples
-
I created a hard link test1 and a soft link test2 for 1.txt in the / home/kali/pysnow directory
-
When I output the contents of test1 and test2 respectively, they are the same as the output of 1.txt
Through ls -i, you can see that the node of test1 is the same as the node of 1.txt, which means that the two belong to the same link and can operate on the corresponding information on the disk
When I delete the link of test1 and access the soft link of test2, the file content is not affected
*****To sum up*
- The soft link is equivalent to the shortcut in Windows and the pointer in C language. After deletion, it will not affect the contents of the file itself on the disk
- By default, a file information corresponds to a hard link. When we create a hard link through the ln command, both file links can modify the storage of files in the disk, and the relationship is and, that is, the operation will take effect only when both must do the same operation
vim/vi
Installation: sudo apt install vim sudo yum install vim
vim and vi are text editing tools on Linux. All Unix like systems come with vi text editor. vim can be regarded as an upgraded version of vi. we usually use vim more
-
vim is an excellent programming program, not a word processing program (vim official)
-
vim also has the functions of most graphical programming software, such as automatic completion, compiler, error jump, etc., so it's not too much to say that it is a programming software
Edit mode:
- Command mode
- Input mode
- Last line mode
Command mode: User just started vi/vim,It enters command mode. In this state, keyboard tapping will be ignored Vim Recognized as a command, not an input character. For example, we press at this time i,It does not enter a character, i As an order. Here are some common commands: i Switch to input mode to enter characters. x Deletes the character at the current cursor. : Switch to the bottom line command mode to enter commands on the bottom line. To edit text: start Vim,After entering command mode, press i,Switch to input mode. Command mode has only some basic commands, so you still have to rely on the bottom line command mode to enter more commands.
Input mode Press in command mode i Enter the input mode. In input mode, the following keys can be used: Character keys and Shift Combination, enter characters ENTER,Enter, line feed BACK SPACE,Backspace key to delete the previous character of the cursor DEL,Delete key to delete one character after the cursor Direction keys to move the cursor in the text HOME/END,Move the cursor to the beginning of the line/End of line Page Up/Page Down,upper/Page down Insert,Switch cursor to input/When you replace the mode, the cursor changes to a vertical bar/Underline ESC,Exit the input mode and switch to the command mode
last line node Press in command mode:(English colon) enters the bottom line command mode. The bottom line command mode can input single or multiple character commands, and there are many available commands. In the baseline command mode, the basic commands are (colon has been omitted): q Exit program w Save file Press ESC Key to exit the bobbin thread command mode at any time.
Open file via vim filename command
Cursor movement: The keyboard can be used in command mode h j k l Use four keys to move the cursor (it must be lowercase English letters, the meaning of uppercase is different, remember), or use the direction key to move the cursor h - Shift left j - Move down k - Move up l - Shift right
Then press i to enter the editing mode. At this time, you can see the insert at the bottom of the screen (pretending to be, i changed linux into Chinese). Try to write a hello word at the bottom of the file
How to save it after writing? Press esc directly to enter the command mode, then press the colon to enter the bottom line command mode, enter wq and press enter, so that the file can be saved
Then use the cat command to verify
Obviously, it succeeded. Basically, the operations used in this example are enough
This is the end of the article. Can you give people some praise and attention~~