I. Getting to Know the Linux Command Line
Linux is an operating system widely used in servers, cloud computing, embedded devices, and development environments. Compared with a graphical interface, the command line offers direct operation, low resource usage, easy automation, and suitability for remote management.
1.1 What Is a Shell?
The Shell is the command interpreter between the user and the operating system kernel.
After the user enters a command, the Shell parses the command, handles the arguments, executes the program, and outputs the result to the terminal.
Common Shells:
| Shell | Characteristics |
|---|---|
| Bash | The most common Shell, with good compatibility |
| Zsh | Supports rich completion and themes |
| Fish | Friendly interactive experience |
| Dash | A lightweight Shell, often used for system scripts |
| Sh | The generic interface name for Unix Shells |
The basic structure of a Linux command line:
command [options] [arguments]
For example:
ls -lah /var/log
Here:
ls: the command name.-l: display in detailed list form.-a: show hidden files.-h: use human-readable file size units./var/log: the command argument, indicating the target directory.
1.2 The Relationship Between Terminal, Shell, and Kernel
flowchart TD
A["User enters a command"] --> B["Terminal"]
B --> C["Shell parses the command"]
C --> D["Locate and execute the program"]
D --> E["System call interface"]
E --> F["Linux kernel"]
F --> G["CPU, memory, disk, network devices"]
G --> H["Execution result"]
H --> I["Shell outputs the result"]
I --> B
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#EAE3F7,stroke:#B7A6D9,color:#51416F
style F fill:#EAE3F7,stroke:#B7A6D9,color:#51416F
style G fill:#FFF1D6,stroke:#E6C98A,color:#76551B
style H fill:#F1F5F9,stroke:#CBD5E1,color:#334155
style I fill:#F1F5F9,stroke:#CBD5E1,color:#334155
Note the following:
- The terminal provides the input and output interface.
- The Shell interprets and executes commands.
- The Linux kernel manages hardware resources and provides system calls.
- A command is usually a standalone executable program, but it may also be a Shell built-in command.
For example, cd is usually a Shell built-in command, because changing the current working directory requires modifying the working directory of the current Shell process itself.
1.3 Viewing Command Help
Linux commands usually offer several ways to get help.
# View command help
ls --help
# View the command manual
man ls
# Query the command type
type cd
type ls
# View the location of a command
which python3
command -v python3
# View Shell command history
history
# Clear the terminal display
clear
Common sections of the man manual:
| Section | Content |
|---|---|
| 1 | General user commands |
| 2 | System calls |
| 3 | C library functions |
| 4 | Device files |
| 5 | File formats and configuration files |
| 8 | System administration commands |
For example:
man 2 open
man 5 passwd
man 8 mount
These view the documentation for system calls, configuration file formats, and system administration commands, respectively.
II. File System and Directory Management
Linux organizes files using a unified directory tree. All files and devices can usually be accessed through file system paths.
2.1 Linux Directory Structure
Common directories and their purposes:
| Directory | Purpose |
|---|---|
/ |
Root directory |
/bin |
Basic user commands; on modern systems usually symlinked to /usr/bin |
/sbin |
System administration commands; on modern systems usually symlinked to /usr/sbin |
/etc |
System configuration files |
/home |
Home directories for regular users |
/root |
Home directory for the root user |
/var |
Variable data such as logs, caches, and queues |
/tmp |
Temporary files |
/usr |
User-space programs, libraries, and shared resources |
/opt |
Optional third-party software |
/dev |
Device files |
/proc |
Virtual filesystem for kernel and process information |
/sys |
Device model and kernel information |
/mnt |
Temporary mount point |
/media |
Mount points for removable media |
/boot |
Files related to the kernel and booting |
View directories:
ls /
ls /etc
ls /var
2.2 View the current directory
# Show current working directory
pwd
# List directory contents
ls
# Detailed listing
ls -l
# Show hidden files
ls -a
# Human-readable file sizes
ls -lh
# Sort by modification time
ls -lt
# List directories recursively
ls -R
In Linux, files beginning with . are usually treated as hidden files.
For example:
.bashrc
.profile
.ssh
2.3 Change directories
# Change into a directory
cd /etc
# Return to home directory
cd ~
# Go up one level
cd ..
# Return to previous directory
cd -
# Change to an absolute path
cd /var/log
# Change to a relative path
cd ../tmp
An absolute path starts from the root directory /.
A relative path starts from the current working directory.
For example, if the current directory is /home/user:
cd documents
It actually enters:
/home/user/documents
2.4 Create files and directories
# Create a directory
mkdir project
# Create nested directories
mkdir -p project/src/main
# Create an empty file
touch app.py
# Create multiple files
touch a.txt b.txt c.txt
# Create a directory with spaces
mkdir "my project"
mkdir -p can automatically create any missing parent directories, and running it repeatedly will not report an error because the directory already exists.
2.5 Copy, move, and delete
# Copy a file
cp source.txt target.txt
# Copy to a specified directory
cp source.txt /tmp/
# Copy a directory recursively
cp -r project project_backup
# Preserve attributes such as permissions and timestamps
cp -a project project_backup
# Move a file
mv old.txt new.txt
# Move a directory
mv project /opt/
# Delete a file
rm app.py
# Delete an empty directory
rmdir empty_dir
# Delete a directory recursively
rm -r project
rm operations carry relatively high risk, especially recursive deletion.
Do not run the following without understanding the path:
rm -rf /
rm -rf /*
Before deleting data in a production environment, it is recommended to check the target first:
pwd
ls -la /目标目录
If necessary, first move the files to a temporary directory, and clean them up after confirming everything is correct.
2.6 View file contents
# Output the entire file
cat config.txt
# View with pagination
less config.txt
# View the beginning of a file
head config.txt
# View the first 20 lines
head -n 20 config.txt
# View the end of a file
tail config.txt
# View the last 100 lines
tail -n 100 app.log
# Follow logs in real time
tail -f app.log
# View multiple files at the same time
cat a.txt b.txt
When viewing logs, the most commonly used command is:
tail -f /var/log/syslog
Log file names may vary by distribution; you can also use:
journalctl -f
2.7 File Search
find can search by criteria such as file name, type, size, modification time, and permissions.
# Find by name
find /home -name "app.py"
# Ignore case
find /home -iname "app.py"
# Find directories
find /var -type d -name "log"
# Find files
find /var -type f -name "*.log"
# Find files larger than 100MB
find / -type f -size +100M 2>/dev/null
# Find files modified in the last day
find /var/log -type f -mtime -1
# Find empty files
find /tmp -type f -empty
Common file types:
| Type parameter | Meaning |
|---|---|
-type f |
Regular file |
-type d |
Directory |
-type l |
Symbolic link |
-type b |
Block device |
-type c |
Character device |
2.8 File Content Search
grep is used to search for text content within files.
# Search for a keyword
grep "error" app.log
# Ignore case
grep -i "error" app.log
# Show line numbers
grep -n "error" app.log
# Search directories recursively
grep -r "database" /etc
# Show only matching file names
grep -rl "password" /etc
# Use extended regular expressions
grep -E "error|warning|failed" app.log
# Invert match
grep -v "DEBUG" app.log
Combined usage:
grep -inE "error|failed" /var/log/app.log | tail -n 50
This command finds recent error and failure records.
2.9 File Links
Linux supports hard links and symbolic links.
# Create a hard link
ln original.txt hardlink.txt
# Create a symbolic link
ln -s original.txt softlink.txt
# View the inode
ls -li
Differences between the two:
| Comparison item | Hard link | Symbolic link |
|---|---|---|
| Target | Same inode | Path string |
| Across filesystems | Usually not supported | Supported |
| Directory links | Usually not allowed for regular users | Supported |
| Original file deleted | Data remains accessible | Target path becomes invalid |
| inode | Same as original file | Has its own inode |
3. File Permissions and User Management
Linux controls file access using users, groups, and permissions.
3.1 Viewing File Permissions
ls -l
Example:
-rwxr-xr-- 1 alice developers 1024 Dec 04 10:00 app.sh
The permission field can be broken down as:
- rwx r-x r--
│ │ │
│ │ └── Permissions for other users
│ └────── Permissions for the owning group
└────────── File owner permissions
The first character indicates the file type:
-: Regular file.d: Directory.l: Symbolic link.b: Block device.c: Character device.
Permission meanings:
| Permission | Meaning for files | Meaning for directories |
|---|---|---|
| r | Read file contents | List directory contents |
| w | Modify file contents | Create, delete, and rename directory entries |
| x | Execute file | Enter the directory and access objects within it |
Directory permissions are especially important.
For example, even if a directory allows reading, without execute permission you cannot properly access the files inside it.
3.2 chmod: Modifying Permissions
Permissions can be set using either symbolic or numeric notation.
# Add execute permission for the owner
chmod u+x app.sh
# Add write permission for the group
chmod g+w app.sh
# Remove write permission for others
chmod o-w app.sh
# Add read permission for everyone
chmod a+r app.sh
Numeric permissions:
| Number | Permission | Binary |
|---|---|---|
| 4 | r | 100 |
| 2 | w | 010 |
| 1 | x | 001 |
| 7 | rwx | 111 |
| 6 | rw- | 110 |
| 5 | r-x | 101 |
| 4 | r-- | 100 |
For example:
# rwxr-xr-x
chmod 755 app.sh
# rw-r--r--
chmod 644 config.txt
# rw-------
chmod 600 private.key
# Recursively change directory permissions
chmod -R 755 project
In production environments, do not casually run this against the entire system:
chmod -R 777 /
This would severely break the system's permission boundaries.
3.3 chown: Changing Ownership
# Change the file owner
sudo chown alice app.txt
# Change the owner and group
sudo chown alice:developers app.txt
# Recursively change a directory
sudo chown -R alice:developers /opt/project
# Change only the group
sudo chgrp developers app.txt
Viewing user information:
id
id alice
groups alice
3.4 Special Permissions
Linux also has three common special permissions:
| Permission | Value | Effect |
|---|---|---|
| SUID | 4 | When executing a file, use the file owner's effective user identity |
| SGID | 2 | When executing a file, use the file's group identity; on directories, typically causes newly created objects to inherit the directory's group |
| Sticky Bit | 1 | Within a directory, typically only the file owner, directory owner, or privileged user may delete files |
Examples:
# Set SUID
chmod 4755 program
# Set SGID
chmod 2755 shared_dir
# Set the Sticky Bit
chmod 1777 /tmp
# View special permissions
ls -ld /tmp
/tmp typically uses the Sticky Bit to prevent ordinary users from arbitrarily deleting other users' files.
3.5 User Management
Common user management commands:
# Add a user
sudo useradd -m alice
# Set a password
sudo passwd alice
# Modify user information
sudo usermod -s /bin/bash alice
# Add a user to a supplementary group
sudo usermod -aG sudo alice
# View a user
id alice
# Delete a user
sudo userdel alice
# Delete a user and their home directory
sudo userdel -r alice
Notes:
- The name of the administrative group may be
sudoorwheeldepending on the distribution. - The
-ainusermod -aGis very important; it means to append the group membership. - If
-ais omitted, the user's existing supplementary groups may be overwritten.
3.6 sudo and root
root is the superuser on Linux and has extremely high system privileges.
Ordinary users can temporarily perform privileged operations via sudo:
sudo apt update
sudo systemctl restart nginx
sudo cat /etc/shadow
View sudo privileges:
sudo -l
Edit the sudo configuration:
sudo visudo
In production environments, it is recommended to follow the principle of least privilege:
- Use a regular user for daily work.
- Use sudo only when necessary.
- Avoid logging in as root for long periods.
- Fine-grained control sudo permissions.
- Do not write passwords directly into shell scripts.
4. Process Management and Resource Monitoring
A process is an instance of a running program. Linux allocates CPU time, memory, and other resources through its process management mechanisms.
4.1 Viewing Processes
# View processes in the current terminal
ps
# View all processes for the current user
ps -u "$USER"
# View all processes on the system
ps aux
# Display as a process tree
ps -ef --forest
# Sort by CPU usage
ps aux --sort=-%cpu
# Sort by memory usage
ps aux --sort=-%mem
Common fields:
| Field | Meaning |
|---|---|
| PID | Process ID |
| PPID | Parent process ID |
| USER | Owning user |
| %CPU | CPU usage |
| %MEM | Memory usage |
| VSZ | Virtual memory size |
| RSS | Resident physical memory size |
| STAT | Process state |
| COMMAND | Startup command |
4.2 top Real-time Monitoring
top
top can display in real time:
- CPU usage.
- Memory and swap usage.
- Process resource consumption.
- System load.
- Process running state.
Common shortcuts:
| Key | Function |
|---|---|
| P | Sort by CPU |
| M | Sort by memory |
| T | Sort by running time |
| k | Send a signal to a specified process |
| r | Change process priority |
| 1 | Display the status of each CPU core |
| q | Quit |
You can also use:
htop
htop provides a more intuitive interactive interface, but may need to be installed separately.
4.3 Viewing the Process Tree
pstree
pstree -p
View a specified process:
pstree -p 1234
Processes have parent-child relationships, and common system services may also create multiple worker processes.
4.4 Terminating Processes
# Send the default SIGTERM to a process
kill 1234
# Explicitly send SIGTERM
kill -15 1234
# Force terminate
kill -9 1234
# Terminate processes by name
pkill nginx
# Match against the full command line
pkill -f "python app.py"
Common signals:
| Signal | Number | Effect |
|---|---|---|
| SIGHUP | 1 | Hangup; some services use it to reload configuration |
| SIGINT | 2 | Interrupt |
| SIGQUIT | 3 | Quit and possibly produce a core dump |
| SIGKILL | 9 | Force terminate; cannot be caught or ignored |
| SIGTERM | 15 | Request that the process exit normally |
| SIGSTOP | 19 | Suspend the process; cannot be caught or ignored |
| SIGCONT | 18 | Resume the process |
Normally, you should prefer SIGTERM, giving the program a chance to release resources and save state.
Only consider SIGKILL when a process cannot exit normally.
4.5 Running Programs in the Background
# Run in background
python3 app.py &
# View current shell jobs
jobs
# Bring job to foreground
fg
# Send job to background
bg
# Suspend foreground program
Ctrl + Z
# Terminate foreground program
Ctrl + C
If you want the program to keep running after you exit the terminal:
nohup python3 app.py > app.log 2>&1 &
Here:
nohup: ignore the hangup signal.>: redirect standard output.2>&1: redirect standard error to standard output.&: run in the background.
However, long-running services in production environments are better managed by a service manager such as systemd, rather than relying solely on nohup.
4.6 View CPU and memory
# View CPU and memory overview
lscpu
free -h
# View detailed memory information
cat /proc/meminfo
# View CPU information
cat /proc/cpuinfo
# View system load
uptime
# View virtual memory statistics
vmstat 1
Understanding free -h:
total used free shared buff/cache available
Mem: 15Gi 4Gi 2Gi 200Mi 9Gi 10Gi
Swap: 4Gi 0Gi 4Gi
Focus on:
total: total memory.used: used memory.free: completely free memory.buff/cache: buffers and cache.available: estimated memory available for new programs.
Linux uses free memory to cache file data, so a low free value does not necessarily mean memory is insufficient.
available is usually more useful as a reference than looking at free alone.
4.7 View disk I/O and system load
# View system load
uptime
# View disk I/O
iostat -xz 1
# View system resource statistics
vmstat 1
# View process I/O
sudo iotop
iostat can help identify issues such as disk throughput, IOPS, wait time, and device utilization.
5. Disk and Filesystem Management
Disk management is an important part of Linux operations and maintenance, including device identification, partitioning, formatting, mounting, and capacity monitoring.
5.1 View disk devices
# View block devices
lsblk
# View filesystem types and mount points
lsblk -f
# View disk partitions
sudo fdisk -l
# View disk usage
df -h
# View space used by a directory
du -sh /var/log
# View sizes of first-level entries under a directory
du -h --max-depth=1 /var
Difference between df and du:
| Command | Function |
|---|---|
| df | View overall filesystem usage |
| du | Calculate space used by directories or files |
If df shows that the disk is full while the results from du are noticeably smaller, there may be files that have been deleted but are still open by a process.
You can investigate with the following command:
sudo lsof +L1
5.2 Partitioning and formatting
Partitioning tool:
sudo fdisk /dev/sdb
You can also use:
sudo parted /dev/sdb
Formatting example:
# Create an ext4 filesystem
sudo mkfs.ext4 /dev/sdb1
# Create an XFS filesystem
sudo mkfs.xfs /dev/sdb1
Note: Formatting destroys the existing filesystem data on the target partition. Before doing so, you must confirm the device name, partition, and backup status.
Do not copy /dev/sdb1 from the examples and run it directly.
5.3 Mounting filesystems
Create a mount point:
sudo mkdir -p /data
Mount the partition:
sudo mount /dev/sdb1 /data
View mount information:
df -h
findmnt
mount
Unmount the filesystem:
sudo umount /data
If unmounting fails, you can check which processes are using the mount point:
sudo lsof +f -- /data
Do not force-unmount a data disk that is in use without understanding the impact.
5.4 Automatic Mounting at Boot
Linux typically uses /etc/fstab to configure mounting at boot.
Check the partition UUID:
sudo blkid
Edit the configuration:
sudo nano /etc/fstab
Example:
UUID=xxxx-xxxx /data ext4 defaults,nofail 0 2
Field descriptions:
| Field | Meaning |
|---|---|
| UUID | Unique filesystem identifier |
| Mount Point | Mount point |
| Type | Filesystem type |
| Options | Mount options |
| Dump | dump backup flag |
| Pass | Filesystem check order at boot |
After making changes, it is recommended to verify first:
sudo findmnt --verify
sudo mount -a
mount -a attempts to mount filesystems in fstab that are not yet mounted.
5.5 Checking Disk Space Usage
# Check the root partition
df -h /
# View all filesystems
df -hT
# Find large files
sudo find /var -type f -size +500M -ls
# Calculate the size of the log directory
sudo du -sh /var/log/*
# Check directory usage
sudo du -xhd1 / 2>/dev/null | sort -h
If disk space is insufficient, you can troubleshoot using the following approach:
- Identify the filesystem that is low on space.
- Locate the directories using the most space.
- Find large files that are growing abnormally.
- Determine whether the files are still in use.
- Evaluate log rotation, cache cleanup, or disk expansion options.
- After cleanup, verify space and service status again.
Do not directly delete system files whose purpose you do not understand.
6. Package Management
Linux distributions typically use package managers to install, update, and uninstall programs.
6.1 Debian and Ubuntu: APT
Update the package index:
sudo apt update
Upgrade installed software:
sudo apt upgrade
Install software:
sudo apt install nginx
Uninstall software:
sudo apt remove nginx
Uninstall software and its configuration:
sudo apt purge nginx
Remove unused dependencies:
sudo apt autoremove
Search for packages:
apt search nginx
View package information:
apt show nginx
6.2 RHEL, Rocky Linux, AlmaLinux: DNF
# Update packages
sudo dnf update
# Install software
sudo dnf install nginx
# Uninstall software
sudo dnf remove nginx
# Search for software
dnf search nginx
# View package information
dnf info nginx
# View installed software
dnf list installed
Older RHEL-based distributions may also use yum.
6.3 Arch Linux: Pacman
# Synchronize the package database and upgrade the system
sudo pacman -Syu
# Install software
sudo pacman -S nginx
# Uninstall software
sudo pacman -R nginx
# Search for software
pacman -Ss nginx
# View installed software
pacman -Q
6.4 Comparison of Package Managers
| Distribution | Manager | Package format |
|---|---|---|
| Ubuntu | apt | deb |
| Debian | apt | deb |
| Linux Mint | apt | deb |
| Fedora | dnf | rpm |
| RHEL | dnf | rpm |
| Rocky Linux | dnf | rpm |
| AlmaLinux | dnf | rpm |
| Arch Linux | pacman | pkg.tar.zst |
Software repositories, package versions, and dependency policies may differ between distributions.
Do not use the Debian-family apt command directly on Fedora or Arch Linux.
6.5 Querying the Software Installation Location
# Query the command path
command -v nginx
# Check the program version
nginx -v
# On Debian-based systems, query which package a file belongs to
dpkg -S /usr/sbin/nginx
# On RPM-based systems, query which package a file belongs to
rpm -qf /usr/sbin/nginx
7. Service Management: systemd
On modern Linux distributions, many systems use systemd to manage services and the system boot process.
Note that not all Linux distributions use systemd; other init and service management solutions such as OpenRC and runit also exist.
7.1 Viewing Service Status
# View service status
systemctl status nginx
# Check whether the service is running
systemctl is-active nginx
# Check whether the service is enabled at boot
systemctl is-enabled nginx
# List all services
systemctl list-units --type=service
7.2 Starting, Stopping, and Restarting Services
# Start the service
sudo systemctl start nginx
# Stop the service
sudo systemctl stop nginx
# Restart the service
sudo systemctl restart nginx
# Reload the configuration
sudo systemctl reload nginx
# Enable start at boot
sudo systemctl enable nginx
# Disable start at boot
sudo systemctl disable nginx
The difference between restart and reload:
restart: stops the service and then starts it again, which may interrupt existing connections.reload: asks the service to reload its configuration; whether this is supported depends on the specific service.
After modifying the Nginx configuration, you can first check it:
sudo nginx -t
Once you have confirmed the configuration is valid, run:
sudo systemctl reload nginx
7.3 Viewing System Logs
# View system logs
journalctl
# View logs for a specific service
journalctl -u nginx
# View the last 100 lines
journalctl -u nginx -n 100
# Follow logs in real time
journalctl -u nginx -f
# View logs from the current boot
journalctl -b
# View logs at error level and above
journalctl -p err
# View logs within a specified time range
journalctl --since "2026-12-04 10:00:00"
If a service fails to start:
sudo systemctl status nginx
sudo journalctl -u nginx -n 100 --no-pager
7.4 The systemd Service Startup Process
flowchart TD
A["System boot"] --> B["systemd initialization"]
B --> C["Read Unit configuration"]
C --> D["Analyze service dependencies"]
D --> E["Start service process"]
E --> F{"Startup successful?"}
F -->|Yes| G["Service enters running state"]
F -->|No| H["Record startup error"]
H --> I["Check configuration, permissions, and dependencies"]
I --> J{"Problem fixed?"}
J -->|Yes| E
J -->|No| K["Remain in failed state and alert"]
G --> L["Continuously monitor service status"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#EAE3F7,stroke:#B7A6D9,color:#51416F
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#FFF1D6,stroke:#E6C98A,color:#76551B
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#FCE8E8,stroke:#E5AAAA,color:#8A3D3D
style I fill:#F1F5F9,stroke:#CBD5E1,color:#334155
style J fill:#FFF1D6,stroke:#E6C98A,color:#76551B
style K fill:#FCE8E8,stroke:#E5AAAA,color:#8A3D3D
style L fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
7.5 Writing a Custom systemd Service
Suppose there is a Python program:
/opt/myapp/app.py
Create the service configuration:
sudo nano /etc/systemd/system/myapp.service
Content:
[Unit]
Description=My Python Application
After=network.target
[Service]
Type=simple
User=appuser
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/python3 /opt/myapp/app.py
Restart=on-failure
RestartSec=5
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
Configuration notes:
| Setting | Purpose |
|---|---|
| Description | Service description |
| After | Startup order dependency |
| Type | Service type |
| User | User to run as |
| WorkingDirectory | Working directory |
| ExecStart | Startup command |
| Restart | Restart policy |
| RestartSec | Restart interval |
| Environment | Environment variables |
| WantedBy | Installation target |
Load and start it:
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
Check the running status:
sudo systemctl status myapp
Check the logs:
sudo journalctl -u myapp -f
In production environments, you should also configure permission restrictions, resource limits, timeout policies, and logging policies according to the program's characteristics.
8. Network Management and Remote Connections
Linux servers usually provide Web, database, SSH, and other services over the network.
8.1 Viewing Network Interfaces
# View network interfaces and IP addresses
ip addr
# Short form
ip a
# View network interface status
ip link
# View routing table
ip route
# View DNS configuration
cat /etc/resolv.conf
View the default gateway:
ip route | grep default
8.2 Network Connectivity Testing
# Test connectivity to the target host
ping -c 4 8.8.8.8
# View the routing path
traceroute example.com
# DNS query
nslookup example.com
# More detailed DNS query
dig example.com
# Test a TCP port
nc -zv example.com 443
Some commands may need to be installed separately.
8.3 Checking Listening Ports
# View listening ports
ss -tuln
# Show process information
sudo ss -tulnp
# View TCP connections
ss -tan
# View UDP connections
ss -uan
Parameter meanings:
| Parameter | Meaning |
|---|---|
-t |
TCP |
-u |
UDP |
-l |
Listening state |
-n |
Show numeric addresses and ports |
-p |
Show process information |
-a |
Show all related sockets |
For example:
sudo ss -tulnp | grep ':80'
This can check whether any process is listening on port 80.
8.4 SSH Remote Login
Connect to a remote Linux server:
ssh user@192.168.1.100
Specify a port:
ssh -p 2222 user@192.168.1.100
Use a private key:
ssh -i ~/.ssh/id_ed25519 user@192.168.1.100
Generate a key:
ssh-keygen -t ed25519
Copy the public key:
ssh-copy-id user@192.168.1.100
SSH configuration is usually located at:
/etc/ssh/sshd_config
After modifying the server configuration, validate the configuration first:
sudo sshd -t
Then reload the service:
sudo systemctl reload ssh
On some distributions, the service name is sshd.
When modifying SSH configuration, it is recommended to keep the current session open and confirm that a new session can log in successfully, so that accidental changes do not interrupt remote access.
8.5 File Transfer
Using SCP:
# Upload a file
scp app.py user@192.168.1.100:/home/user/
# Download a file
scp user@192.168.1.100:/home/user/app.py .
Copy a directory:
scp -r project user@192.168.1.100:/home/user/
Using rsync:
# Synchronize a directory
rsync -avz project/ user@192.168.1.100:/opt/project/
# Show transfer progress
rsync -avz --progress project/ user@192.168.1.100:/opt/project/
rsync is suitable for incrementally synchronizing large directories.
Note that the trailing / in the source path affects synchronization semantics:
project/: Synchronize the contents of the directory.project: Usually places the directory itself as a subdirectory under the destination directory.
9. Log Management and Troubleshooting
Logs are an important basis for diagnosing Linux system issues.