In the process of Linux server administration and maintenance, it is very necessary to master some common commands. These commands can not only help you better understand and control the system, but also improve work efficiency and reduce the probability of errors. This article will detail some of the commands commonly used on Linux servers, covering everything from basic file operations to advanced system administration, aiming to be comprehensive and help readers gain a deeper understanding of the usage and principles of each command.
I. File and Directory Operation Commands I. File and Directory Operation Commands
1. ls -- lists the contents of a directory
ls is one of the most commonly used commands to list the contents of a directory. It displays files and subdirectories in the current directory or in a specified directory.
Expand to view parameters
ls -l: lists files in long format, showing details such as permissions, number of links, owner, file size and modification time.
ls -a: displays hidden files, i.e. those starting with . files, i.e. those starting with .
ls -h: Combined with -l, shows human-readable file sizes, e.g. 1K, 234M.
2. cd -- switch directories
cd is used to change the current working directory.
Expand to view parameters
cd ~ or cd: Return to the user's home directory.
cd -: Returns to the previous working directory.
cd ... : Return to the previous directory.
3. pwd -- displays the current working directory
pwd (print working directory) is used to display the current working directory path.
Expand to view parameters
[root@localhost tmp]# pwd
/tmp
[root@localhost tmp]#
4. mkdir -- create directory
mkdir is used to create a new directory.
Expand to view parameters
mkdir -p /path/to/directory: recursively creates directories. If the parent directory does not exist, mkdir creates it automatically.
5. rmdir -- delete empty directory
rmdir can only delete empty directories. If the directory is not empty, you can use rm -r.
Expand to view parameters
rmdir directory_name
6. rm -- to delete a file or directory
rm is used to delete files or directories. Deletion operations are not recoverable, so use caution.
Expand to view parameters
rm file_name
7. cp -- copy file or directory
The cp command is used to copy a file or directory.
Expand to view parameters
cp source_file destination_file
8. mv -- move or rename a file or directory
The mv command is used to move or rename files or directories.
Expand to view parameters
mv old_name new_name
9. touch -- create empty files or update file timestamps
touch is typically used to create a new empty file, or to update the timestamp of an existing file.
Expand to view parameters
touch file_name
II. File content viewing and editing commands
1. cat -- connects and displays the contents of the file
cat is a common command for viewing the contents of files, especially small files.
Expand to view parameters
cat file1 file2 > merged_file: merge multiple files into one.
cat -n file_name: show line number.
2. less and more -- paging the contents of the document
less and more are used to page through the contents of a file. Compared to more, less is more feature-rich.
Expand to view parameters
In less, you can use the up and down arrow keys to scroll through the file and press q to exit.
The more command displays the contents page by page; press the space bar to turn the page.
3. head and tail -- view the head or tail of a file
The head and tail commands are used to view the first few lines or the last few lines of a file, respectively. head and tail commands are used to view the first few lines or the last few lines of a file, respectively.
Expand to view parameters
head -n 10: View the first 10 lines of the file.
tail -n 10 file_name: view the last 10 lines of the file.
tail -f file_name: view the updated contents of the file in real time, usually used for monitoring log files.
4. nano and vim -- file editors
nano and vim are two popular text editors. nano is an easy-to-use editor for novices, while vim is powerful and suitable for advanced users.
Expand to view parameters
vim file_name: Open the file for editing.
In nano, press Ctrl+O to save the file, Ctrl+X to exit editing.
In vim, press i to enter insert mode, press Esc when you are done editing, type :wq to save and exit.
III. Permissions and user management commands
1. chmod -- change file permissions
The chmod command is used to change the permissions of a file or directory. Permissions consist of read (r), write (w), and execute (x), and are represented by the numbers 4, 2, and 1, respectively. chmod command is used to change the permissions of a file or directory. Permissions consist of read (r), write (w), and execute (x), and are represented by the numbers 4, 2, and 1, respectively.
Expand to view parameters
chmod u+x file_name: Add execute permission to the file owner.
chmod -R 755 directory_name: recursively modify directory permissions.
2. chown -- change file owner
The chown command is used to change the owner and the group to which a file or directory belongs. chown command is used to change the owner and the group to which a file or directory belongs. chown command is used to change the owner of a file or directory.
Expand to view parameters
chown owner_name:group_name file_name: Changes both the owner and the group to which it belongs.
chown -R owner_name:group_name directory_name: Recursively change the owner of a directory and its contents.
3. passwd -- change user passwords
The passwd command is used to change the password of the current user or another user. passwd command is used to change the password of the current user or another user.
Expand to view parameters
passwd user_name: Change the password for the specified user, must have administrator privileges.
4. useradd and userdel -- adding and removing users
The useradd command is used to create new users, while userdel is used to delete users. useradd is used to create new users, while userdel is used to delete users.
Expand to view parameters
userdel user_name: Delete the user.
useradd -m -s /bin/bash new_user: creates a user and assigns it a home directory and default shell.
5. usermod -- modify user information
The usermod command is used to modify information about an existing user.
Expand to view parameters
usermod -l new_user_name old_user_name: Change the user name.
usermod -d /new/home/dir user_name: Change the user's home directory.
6. groups -- shows the groups to which the user belongs
The groups command is used to display all groups to which the specified user belongs.
Expand to view parameters
groups user_name
Displays the group to which the current user belongs without arguments.
IV. Process management commands
1. ps -- show process status
The ps command is used to display the status of processes currently running on the system.
Expand to view parameters
ps -ef: Display detailed process information.
ps aux | grep process_name: Filter and display specific processes.
2. top and htop -- real-time display of process status
The top and htop commands are used to display the running status of each process on the system in real time. htop is an enhanced version of top that provides a more user-friendly interface.
Expand to view parameters
In top, you can press k to kill the process and q to exit.
htop offers a colorful display and more interactive features.
3. kill and killall -- terminate processes
The kill and killall commands are used to terminate processes. kill terminates a process based on its process ID (PID), while killall terminates all matching processes based on their names.
Expand to view parameters
kill -9 PID: Force terminate the process.
killall process_name: Terminate all processes named process_name.
4. bg and fg -- background and foreground process control
The bg and fg commands are used to control processes running in the background or foreground.
Expand to view parameters
fg %1: call background jobs back to the foreground.
jobs: List all background jobs.
5. nohup -- keep running command
The nohup command is used to continue running a process after exiting the terminal, and is usually used in conjunction with the & symbol to put the command into the background.
Expand to view parameters
nohup command &
The output of nohup is saved in a file by default.
The combination of nohup and & allows the command to run in the background and not be terminated when the terminal is closed.
V. Network management commands
1. ping -- check network connectivity
The ping command is used to test the connectivity between a host and a target host. It determines the network connectivity status by sending an ICMP request packet and receiving an answer packet back.
ping
Expand to view parameters
ping -c 4 :Send only 4 request packets.
ping -i 0.5 : Set the time interval for sending request packets to 0.5 seconds.
2. ifconfig and ip -- network interface configuration
The ifconfig command is used to display and configure network interfaces; however, in modern systems, the more powerful ip command is preferred.
Expand to view parameters
ifconfig
ifconfig eth0 up: Enables network card eth0.
ip addr show: Displays IP address information for all network interfaces.
ip link set eth0 up: enable NIC eth0.
3. netstat and ss -- network status checking
The netstat command is used to display information about network connections, routing tables, interface statistics, and so on, while the ss command is a modern alternative to netstat that provides similar functionality but is faster.
Expand to view parameters
netstat -tuln
netstat -anp: shows all connections and their corresponding processes.
ss -tuln: shows all listening TCP and UDP ports.
4. traceroute -- route tracing
The traceroute command is used to trace the routes that packets travel through to reach the destination host. It can help identify bottlenecks in the network.
Expand to view parameters
traceroute
traceroute -n : Displays the IP address of the routing node in numeric form.
On some systems, traceroute may be replaced by the tracepath command.
5. wget and curl -- file downloads and network requests
Both wget and curl are command-line tools for network requests, often used for downloading files and interacting with APIs.
Expand to view parameters
wget /
wget -c /: downloads a file in a disconnected state.
curl -O / : Download a file and save it as the original filename.
curl -I : Get HTTP headers.
6. scp and rsync -- remote transfer of files
The scp command is used to transfer files between local and remote hosts via the SSH protocol. rsync command provides more efficient synchronization and supports incremental transfers.
Expand to view parameters
scp local_file user@remote_host:/path/to/destination/
scp -r directory user@remote_host:/path/to/destination/: recursively transfer directory.
rsync -avz local_dir user@remote_host:/path/to/destination/: incrementally synchronize the directory and compress the transferred data.
7. ftp and sftp -- file transfer protocols
The ftp and sftp commands are used to transfer files via the FTP protocol. sftp is a secure transfer method via SSH.
Expand to view parameters
ftp remote_host
put local_file: Upload a file to a remote host.
get remote_file: download a file from a remote host.
sftp user@remote_host: start a secure file transfer session.
VI. Disk and file system management commands
1. df -- view disk space usage
The df command is used to display the disk space usage of a file system.
Expand to view parameters
df -h
df -h: displays disk space usage in a human-readable format.
df -T: displays the file system type.
2. du -- to see how much space a directory or file occupies
The du command is used to display the amount of disk space occupied by a directory or file.
Expand to view parameters
du -sh directory_name
du -h --max-depth=1 /path/to/directory: show the space occupied by each subdirectory in the directory.
du -a: Detailed display including files.
3. fdisk and parted -- disk partitioning tools
The fdisk and parted commands are used to manage disk partitions. fdisk works with MBR partition tables, while parted supports both GPT and MBR partition table formats.
Expand to view parameters
fdisk /dev/sda
fdisk -l: lists all disks and their partition tables.
parted /dev/sda: enters the parted interactive mode and performs disk partitioning operations.
4. mkfs -- creating file systems
The mkfs command is used to create a file system on a partition.
Expand to view parameters
mkfs.ext4 /dev/sda1
mkfs -t ext4 /dev/sda1: Specify the file system type as ext4.
/dev/sda1: Creates an XFS file system.
5. mount and umount -- mounting and unmounting file systems
The mount command is used to mount a file system to a specified mount point, while the umount command is used to unmount a mounted file system.
Expand to view parameters
mount /dev/sda1 /mnt
mount -a: Mount all filesystems defined in /etc/fstab.
umount /mnt: unmount the file system mounted on /mnt.
6. fsck -- file system check
The fsck command is used to check and repair errors in the file system.
Expand to view parameters
fsck /dev/sda1
fsck -y /dev/sda1: automatically fixes errors found.
fsck -n /dev/sda1: only detects errors, does not fix them.
7. mount and unmount -- NFS network file system
When using NFS (Network File System), you can use the mount command to mount a remote NFS share to the local system.
Expand to view parameters
mount -t nfs remote_host:/path/to/share /mnt/nfs
umount /mnt/nfs:uninstallationNFSmount point。
VII. System monitoring and optimization commands
1. uptime -- view system uptime
The uptime command is used to display the uptime of the system, the current time, the number of logged-in users, and the average load on the system.
Expand to view parameters
uptime
Output format: current time, system uptime, current number of logged-in users, load average (average of 1, 5, and 15 minutes, respectively).
2. free -- view memory usage
The free command is used to display the system's memory and swap partition usage.
Expand to view parameters
free -h
free -h: Display memory usage in human-readable format.
free -m: Display memory usage in MB.
3. vmstat -- system performance monitoring
The vmstat command is used to report information about virtual memory, processes, and CPU activity, and is an important tool for system performance monitoring.
Expand to view parameters
vmstat 2 5
The two parameters after vmstat indicate the sampling interval (2 seconds) and the number of samples (5).
The output information includes important metrics such as memory usage, processes, and CPU usage.
4. iostat -- disk I/O monitoring
The iostat command is used to monitor the system's disk I/O usage, including CPU usage and disk read/write rates.
Expand to view parameters
iostat -x 2 5
The -x parameter provides detailed extended statistics.
The latter parameter indicates sampling every 2 seconds for a total of 5 samples.
5. sar -- system activity report
The sar command is a powerful system activity monitoring tool that reports information on a wide range of system activities such as CPU, memory, disk, network, and more.
Expand to view parameters
sar -u 1 5
sar -u: report CPU usage.
sar -r: report memory usage.
sar -r 1 5
sar -n DEV: Report traffic data for network interfaces.
sar -d: reports I/O usage of disk devices.
6. top and htop -- real-time system monitoring
The top and htop commands provide a real-time system monitoring interface that displays important information about system processes, CPU, memory usage, and so on. htop is an enhanced version of top that provides a more user-friendly interface and more features.
Expand to view parameters
top
top -o %CPU: display processes sorted by CPU usage.
htop: start the htop interface, you can use arrow keys, F key to operate.
F5: Toggle the tree view in htop to show the parent-child relationship of processes.
7. atop -- advanced system monitoring tool
The atop command is an advanced system and process monitoring tool that continuously logs the system's resource usage, including CPU, memory, disk, network, and so on.
Expand to view parameters
atop
atop -r: read previous log files for analysis.
atop -c: show detailed resource usage for each process.
8. glances -- lightweight system monitoring
The glances command is a cross-platform system monitoring tool that supports displaying a wide range of resource usage such as CPU, memory, disk, network, etc. and provides a simple interface.
Expand to view parameters
glances
glances -t 2: set the refresh interval to 2 seconds.
glances -s: Starts in server mode, accessible over the network.
9. nmon -- system performance monitoring
The nmon command is a comprehensive system performance monitoring tool that supports monitoring a wide range of system resources such as CPU, memory, network, disk, and so on.
Expand to view parameters
nmon
Press c: to display CPU usage.
Press m: displays memory usage.
Press d: displays disk I/O.
Press q: to exit the nmon interface.
10. iotop -- disk I/O monitoring
The iotop command is used to display the disk I/O usage of a process in real time, similar to the top command.
Expand to view parameters
iotop
iotop -o: show only processes that are performing I/O operations.
iotop -P: show total I/O usage by process.
11. strace -- system call trace
The strace command is used to trace the system calls of a process and is an important tool for debugging and analyzing program behavior.
Expand to view parameters
strace -p PID
strace -c ls: Counts the number and time of system calls during the execution of the ls command.
strace -e open ls: Trace only the operations related to the open system call in the ls command.
12. dstat -- integrated system resource monitoring
The dstat command integrates the functions of vmstat, iostat, netstat and other commands, and is able to display the resource usage of CPU, disk, network, memory and other aspects in real time.
Expand to view parameters
dstat
dstat -cdngy: Displays statistics on CPU, disk, network, page swap, and system load.
dstat --top-cpu: Displays the process that occupies the most CPU.
13. tcpdump -- network traffic capture
The tcpdump command is used to capture and analyze network packets and is an important tool for network troubleshooting and security analysis.
Expand to view parameters
tcpdump -i eth0
tcpdump -i eth0 port 80: Captures HTTP traffic on interface eth0.
tcpdump -w : Save the captured packets to a file for later analysis.
14. iftop -- real-time network traffic monitoring
The iftop command is used to display the traffic situation of a network interface in real time, similar to the top command, but focusing on network traffic.
Expand to view parameters
iftop -i eth0
iftop -n: Displays the IP address in numeric form.
iftop -P: Display port information.
15. vnstat -- network traffic statistics
The vnstat command is used to record and display traffic statistics for network interfaces, allowing you to monitor network traffic for a long period of time and generate reports.
Expand to view parameters
vnstat -i eth0
vnstat -h: Displays human-readable traffic statistics.
vnstat -d: Display daily traffic statistics.
VIII. Log management commands
1. tail and head -- viewing the contents of a file
The tail and head commands are used to view the beginning or end of a file and are often used to view log files.
Expand to view parameters
tail -f /var/log/syslog
tail -n 20 /var/log/syslog: View the last 20 lines of the file.
head -n 20 /var/log/syslog: View the first 20 lines of the file.
2. less and more -- paging the contents of the document
The less and more commands are used to page through the contents of a file. less provides richer functionality, supporting forward and backward paging.
Expand to view parameters
less /var/log/syslog
In the less interface, press G to jump to the end of the file, and g to jump to the beginning of the file.
more is a simplified version of less, which only supports forward paging.
3. grep -- text search
The grep command is used to search for matching lines of text in a file and is often used to extract key information from log files.
Expand to view parameters
grep "error" /var/log/syslog
grep -i "error" /var/log/syslog: searches ignoring case.
grep -r "error" /var/log/: recursively searches all files in the directory.
4. logger -- sends messages to system logs
The logger command is used to send custom messages to the system log and is often used for debugging scripts or programs.
Expand to view parameters
logger "This is a test message"
logger -p "Custom message": Specify the log level to send the message.
logger -t myscript "Script started": Specify the log label to send the message.
5. logrotate -- log rotation
logrotate is a log management tool for automatic rotation, compression, deletion and email notification of log files. The configuration file is usually located in /etc/.
Expand to view parameters
logrotate /etc/
logrotate -f /etc/: Enforces log rotation.
The log rotation configuration allows you to control how long the log files are kept, how they are compressed, the number of archives, and so on.
IX. User and rights management commands
1. useradd and userdel -- adding and removing users
The useradd command is used to create new users in the system, while userdel is used to delete users.
Expand to view parameters
useradd newuser
useradd -m newuser: Creates a home directory for a new user.
userdel -r olduser: Deletes the user and removes its home directory.
2. passwd -- change user passwords
The passwd command is used to change a user's login password. Administrators can use this command to set passwords for other users.
Expand to view parameters
passwd username
passwd: when executed without parameters, changes the password for the current user.
passwd -d username: removes the user's password and allows login without password.
3. usermod -- modify user information
The usermod command is used to modify user account information, such as user group, login shell, home directory, and so on.
Expand to view parameters
usermod -aG sudo username
usermod -l newname oldname: Change the username.
usermod -d /new/home/dir username: Change the user's home directory.
4. groupadd and groupdel -- adding and removing user groups
The groupadd command is used to create a new user group, and the groupdel command is used to delete a user group.
Expand to view parameters
groupadd newgroup
groupdel oldgroup: Delete a user group.
gpasswd -a username newgroup: Adds a user to a user group.
5. chown and chmod -- file permission management
The chown command is used to change the owner and user group of a file or directory, and the chmod command is used to modify the permissions of a file or directory.
Expand to view parameters
chown user:group filename
chown root:staff /path/to/file: Changes the owner of a file to root and the group to staff.
chown -R user:group /path/to/directory: recursively changes the owner and group of a directory and all its subfiles and subdirectories.
chmod 755 filename
chmod u+x filename: Adds execute permission to the file owner.
chmod -R 755 /path/to/directory: recursively changes permissions on a directory and its contents.
6. chgrp -- modify file groups
The chgrp command is used to change the user group of a file or directory and is similar to chown, but focuses on modifying the group rather than the owner.
Expand to view parameters
chgrp staff filename
chgrp -R staff /path/to/directory: recursively changes the user group of a directory and its contents.
7. umask -- set default privilege masks
The umask command is used to set the default permission mask for newly created files and directories, thus controlling the default permissions for new files.
Expand to view parameters
umask 022
umask 077: default permissions are 600 for new files and 700 for directories.
The configuration can be persisted by adding the umask setting to ~/.bashrc.
8. sudo and su -- elevation of privileges
The sudo command is used to execute commands with superuser (or other user) privileges, while the su command is used to switch to another user.
Expand to view parameters
sudo command
sudo -i: Open an interactive shell as superuser.
sudo -u username command: Execute a command as the specified user.
su -
su username: Switch to the specified user.
exit: Exit the current user and return to the original shell.
9. id and whoami -- view user information
The id command is used to display the UID, GID, and group information of the current user, while the whoami command is used to display the user name of the current login.
Expand to view parameters
id
id username: Displays UID, GID and group information of the specified user.
whoami: displays the username of the current user.
10. last and lastlog -- view user login logs
The last command is used to display the system's most recent user login record, while the lastlog command is used to display the most recent login time for all users.
Expand to view parameters
last
last -n 10: show last 10 logins.
lastlog: displays the last login time for all users.
lastlog -u username: displays the last login time for the specified user.