引言

Linux系统管理是每个运维工程师和后端开发者必备的核心技能。无论是日常的服务器维护,还是复杂的生产环境管理,熟练掌握Linux命令和系统管理技巧都至关重要。本文将通过实际案例,系统地介绍Linux系统管理的各个方面,帮助读者从入门到精通。

文件系统管理

基础文件操作

Linux文件系统是一切操作的基础,掌握文件操作命令是系统管理的第一步。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 文件和目录基本操作
# 查看当前目录
pwd

# 列出文件和目录
ls -la # 详细列表,包含隐藏文件
ls -lh # 人性化显示文件大小
ls -lt # 按修改时间排序
ls -lS # 按文件大小排序

# 创建目录
mkdir -p /opt/app/logs # 递归创建目录
mkdir -m 755 mydir # 创建目录并设置权限

# 复制文件和目录
cp file1 file2 # 复制文件
cp -r dir1 dir2 # 递归复制目录
cp -p file1 file2 # 保持文件属性
cp -u source dest # 只复制更新的文件

# 移动和重命名
mv oldname newname # 重命名文件
mv file /path/to/dest # 移动文件
mv *.txt /backup/ # 批量移动文件

# 删除文件和目录
rm file # 删除文件
rm -rf directory # 强制递归删除目录
rm -i *.log # 交互式删除

# 查找文件
find /var/log -name "*.log" -type f -mtime -7 # 查找7天内的日志文件
find /home -user john -size +100M # 查找用户john的大文件
find /tmp -empty -delete # 查找并删除空文件

# 文件内容查看
cat file.txt # 显示文件内容
less file.txt # 分页查看文件
head -n 20 file.txt # 查看文件前20行
tail -f /var/log/syslog # 实时查看日志文件
grep -r "error" /var/log # 递归搜索错误信息

高级文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 文件权限管理
chmod 755 script.sh # 设置文件权限
chmod u+x,g+r,o-w file # 符号方式设置权限
chown user:group file # 更改文件所有者
chgrp group file # 更改文件组

# 文件链接
ln -s /path/to/file link # 创建软链接
ln file hardlink # 创建硬链接

# 文件压缩和解压
tar -czf backup.tar.gz /home/user # 创建压缩包
tar -xzf backup.tar.gz # 解压文件
zip -r archive.zip directory # 创建zip压缩包
unzip archive.zip # 解压zip文件

# 文件同步
rsync -av source/ dest/ # 同步目录
rsync -av --delete source/ dest/ # 同步并删除目标多余文件
rsync -av -e ssh source/ user@host:/dest/ # 远程同步

# 磁盘使用情况
df -h # 查看磁盘使用情况
du -sh /var/log # 查看目录大小
du -h --max-depth=1 / # 查看根目录下各目录大小
lsof +D /path # 查看目录下被打开的文件

文件系统监控脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/bin/bash
# 文件系统监控脚本

# 设置阈值
DISK_THRESHOLD=80
INODE_THRESHOLD=80

# 检查磁盘使用率
check_disk_usage() {
echo "=== 磁盘使用情况检查 ==="
df -h | awk 'NR>1 {
usage = substr($5, 1, length($5)-1)
if (usage > '$DISK_THRESHOLD') {
print "警告: " $6 " 磁盘使用率达到 " $5
}
}'
}

# 检查inode使用率
check_inode_usage() {
echo "=== Inode使用情况检查 ==="
df -i | awk 'NR>1 {
if ($5 != "-") {
usage = substr($5, 1, length($5)-1)
if (usage > '$INODE_THRESHOLD') {
print "警告: " $6 " inode使用率达到 " $5
}
}
}'
}

# 查找大文件
find_large_files() {
echo "=== 查找大文件 (>100MB) ==="
find / -type f -size +100M -exec ls -lh {} \; 2>/dev/null | \
awk '{print $5 "\t" $9}' | sort -hr | head -10
}

# 清理临时文件
cleanup_temp_files() {
echo "=== 清理临时文件 ==="

# 清理/tmp目录中7天前的文件
find /tmp -type f -mtime +7 -delete 2>/dev/null

# 清理日志文件
find /var/log -name "*.log" -size +100M -mtime +30 -delete 2>/dev/null

# 清理缓存文件
find /var/cache -type f -mtime +7 -delete 2>/dev/null

echo "临时文件清理完成"
}

# 主函数
main() {
echo "开始文件系统检查 - $(date)"
echo "================================"

check_disk_usage
echo

check_inode_usage
echo

find_large_files
echo

# 如果磁盘使用率过高,执行清理
high_usage=$(df | awk 'NR>1 {usage = substr($5, 1, length($5)-1); if (usage > 85) print $6}')
if [ ! -z "$high_usage" ]; then
echo "检测到磁盘使用率过高,开始清理..."
cleanup_temp_files
fi

echo "文件系统检查完成 - $(date)"
}

# 执行主函数
main

进程管理

进程查看和控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 查看进程
ps aux # 查看所有进程
ps -ef # 显示进程树
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu # 按CPU使用率排序

# 实时进程监控
top # 实时查看进程
htop # 增强版top(需要安装)
top -p 1234 # 监控特定进程

# 查找进程
pgrep nginx # 查找nginx进程ID
pgrep -f "python app.py" # 根据完整命令查找进程
pidof nginx # 查找进程ID

# 进程控制
kill 1234 # 终止进程
kill -9 1234 # 强制终止进程
killall nginx # 终止所有nginx进程
pkill -f "python" # 根据名称终止进程

# 后台进程管理
nohup command & # 后台运行命令
jobs # 查看后台任务
bg %1 # 将任务放到后台
fg %1 # 将任务调到前台
disown %1 # 脱离shell控制

# 进程优先级
nice -n 10 command # 以低优先级运行命令
renice 5 1234 # 调整进程优先级

系统服务管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# systemd服务管理
systemctl start nginx # 启动服务
systemctl stop nginx # 停止服务
systemctl restart nginx # 重启服务
systemctl reload nginx # 重新加载配置
systemctl enable nginx # 开机自启
systemctl disable nginx # 禁用自启
systemctl status nginx # 查看服务状态
systemctl list-units --type=service # 列出所有服务

# 查看服务日志
journalctl -u nginx # 查看服务日志
journalctl -u nginx -f # 实时查看日志
journalctl -u nginx --since "2024-01-01" # 查看指定时间后的日志
journalctl -u nginx -n 50 # 查看最近50行日志

# 创建自定义服务
cat > /etc/systemd/system/myapp.service << EOF
[Unit]
Description=My Application
After=network.target

[Service]
Type=simple
User=myuser
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/start.sh
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload # 重新加载systemd配置
systemctl enable myapp # 启用服务
systemctl start myapp # 启动服务

进程监控脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/bin/bash
# 进程监控和自动重启脚本

# 配置文件
CONFIG_FILE="/etc/process-monitor.conf"

# 默认配置
declare -A PROCESSES=(
["nginx"]="systemctl restart nginx"
["mysql"]="systemctl restart mysql"
["redis"]="systemctl restart redis"
)

# 读取配置文件
load_config() {
if [ -f "$CONFIG_FILE" ]; then
source "$CONFIG_FILE"
fi
}

# 检查进程是否运行
check_process() {
local process_name=$1
pgrep -x "$process_name" > /dev/null
return $?
}

# 检查服务是否运行
check_service() {
local service_name=$1
systemctl is-active --quiet "$service_name"
return $?
}

# 发送告警
send_alert() {
local message=$1
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')

# 记录到日志
echo "[$timestamp] ALERT: $message" >> /var/log/process-monitor.log

# 发送邮件(如果配置了)
if [ ! -z "$ALERT_EMAIL" ]; then
echo "$message" | mail -s "Process Monitor Alert" "$ALERT_EMAIL"
fi

# 发送到Slack(如果配置了)
if [ ! -z "$SLACK_WEBHOOK" ]; then
curl -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"$message\"}" \
"$SLACK_WEBHOOK"
fi
}

# 重启进程
restart_process() {
local process_name=$1
local restart_cmd=${PROCESSES[$process_name]}

if [ ! -z "$restart_cmd" ]; then
echo "重启进程: $process_name"
eval "$restart_cmd"

# 等待进程启动
sleep 5

# 验证重启是否成功
if check_service "$process_name"; then
send_alert "进程 $process_name 重启成功"
else
send_alert "进程 $process_name 重启失败"
fi
fi
}

# 监控进程
monitor_processes() {
for process_name in "${!PROCESSES[@]}"; do
if ! check_service "$process_name"; then
echo "检测到进程 $process_name 未运行"
send_alert "进程 $process_name 已停止,正在尝试重启"
restart_process "$process_name"
else
echo "进程 $process_name 运行正常"
fi
done
}

# 系统资源检查
check_system_resources() {
# 检查CPU使用率
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
if (( $(echo "$cpu_usage > 80" | bc -l) )); then
send_alert "CPU使用率过高: ${cpu_usage}%"
fi

# 检查内存使用率
mem_usage=$(free | grep Mem | awk '{printf "%.2f", $3/$2 * 100.0}')
if (( $(echo "$mem_usage > 80" | bc -l) )); then
send_alert "内存使用率过高: ${mem_usage}%"
fi

# 检查磁盘使用率
disk_usage=$(df / | tail -1 | awk '{print $5}' | cut -d'%' -f1)
if [ "$disk_usage" -gt 80 ]; then
send_alert "磁盘使用率过高: ${disk_usage}%"
fi
}

# 主函数
main() {
echo "开始进程监控 - $(date)"

# 加载配置
load_config

# 监控进程
monitor_processes

# 检查系统资源
check_system_resources

echo "进程监控完成 - $(date)"
}

# 如果作为脚本直接运行
if [ "${BASH_SOURCE[0]}" == "${0}" ]; then
main "$@"
fi

网络管理

网络配置和诊断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 网络接口管理
ip addr show # 查看网络接口
ip link show # 查看网络设备
ip route show # 查看路由表
ip neigh show # 查看ARP表

# 配置网络接口
ip addr add 192.168.1.100/24 dev eth0 # 添加IP地址
ip link set eth0 up # 启用网络接口
ip route add default via 192.168.1.1 # 添加默认路由

# 网络连接查看
netstat -tuln # 查看监听端口
netstat -tupln # 查看所有网络连接
ss -tuln # 现代版netstat
ss -tulpn # 显示进程信息

# 网络诊断
ping -c 4 google.com # 测试网络连通性
traceroute google.com # 跟踪路由
mtr google.com # 网络诊断工具
nslookup google.com # DNS查询
dig google.com # DNS查询工具

# 网络流量监控
iftop # 实时网络流量监控
nethogs # 按进程显示网络使用
iotop # IO使用监控
tcpdump -i eth0 # 抓包分析

# 防火墙管理
ufw enable # 启用防火墙
ufw allow 22 # 允许SSH端口
ufw allow from 192.168.1.0/24 # 允许特定网段
ufw deny 80 # 拒绝HTTP端口
ufw status # 查看防火墙状态

# iptables规则
iptables -L # 查看防火墙规则
iptables -A INPUT -p tcp --dport 80 -j ACCEPT # 允许HTTP
iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT # 允许内网
iptables-save > /etc/iptables/rules.v4 # 保存规则

网络监控脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/bin/bash
# 网络监控脚本

# 配置
PING_HOSTS=("8.8.8.8" "google.com" "github.com")
PORT_CHECKS=("80:HTTP" "443:HTTPS" "22:SSH")
INTERFACE="eth0"
LOG_FILE="/var/log/network-monitor.log"

# 记录日志
log_message() {
local message=$1
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] $message" | tee -a "$LOG_FILE"
}

# 检查网络连通性
check_connectivity() {
log_message "=== 网络连通性检查 ==="

for host in "${PING_HOSTS[@]}"; do
if ping -c 3 -W 5 "$host" > /dev/null 2>&1; then
log_message "✓ $host 连通正常"
else
log_message "✗ $host 连通失败"
fi
done
}

# 检查端口状态
check_ports() {
log_message "=== 端口状态检查 ==="

for port_info in "${PORT_CHECKS[@]}"; do
port=$(echo "$port_info" | cut -d':' -f1)
service=$(echo "$port_info" | cut -d':' -f2)

if netstat -tuln | grep ":$port " > /dev/null; then
log_message "✓ $service (端口 $port) 正在监听"
else
log_message "✗ $service (端口 $port) 未监听"
fi
done
}

# 检查网络接口状态
check_interface() {
log_message "=== 网络接口状态检查 ==="

if ip link show "$INTERFACE" | grep "state UP" > /dev/null; then
log_message "✓ 网络接口 $INTERFACE 状态正常"

# 获取IP地址
ip_addr=$(ip addr show "$INTERFACE" | grep "inet " | awk '{print $2}' | head -1)
if [ ! -z "$ip_addr" ]; then
log_message " IP地址: $ip_addr"
fi

# 获取网络统计
rx_bytes=$(cat /sys/class/net/$INTERFACE/statistics/rx_bytes)
tx_bytes=$(cat /sys/class/net/$INTERFACE/statistics/tx_bytes)
log_message " 接收: $(numfmt --to=iec $rx_bytes)B, 发送: $(numfmt --to=iec $tx_bytes)B"
else
log_message "✗ 网络接口 $INTERFACE 状态异常"
fi
}

# 检查DNS解析
check_dns() {
log_message "=== DNS解析检查 ==="

test_domains=("google.com" "github.com" "stackoverflow.com")

for domain in "${test_domains[@]}"; do
if nslookup "$domain" > /dev/null 2>&1; then
log_message "✓ $domain DNS解析正常"
else
log_message "✗ $domain DNS解析失败"
fi
done
}

# 网络性能测试
network_performance_test() {
log_message "=== 网络性能测试 ==="

# 测试下载速度(使用curl)
test_url="http://speedtest.tele2.net/1MB.zip"

log_message "开始下载测试..."
download_time=$(curl -o /dev/null -s -w "%{time_total}" "$test_url" 2>/dev/null)

if [ $? -eq 0 ]; then
# 计算速度 (1MB / 时间)
speed=$(echo "scale=2; 1 / $download_time" | bc)
log_message "下载速度: ${speed} MB/s"
else
log_message "下载测试失败"
fi
}

# 检查网络安全
check_network_security() {
log_message "=== 网络安全检查 ==="

# 检查异常连接
suspicious_connections=$(netstat -tupln | grep ESTABLISHED | wc -l)
log_message "当前建立的连接数: $suspicious_connections"

# 检查监听端口
listening_ports=$(netstat -tuln | grep LISTEN | wc -l)
log_message "监听端口数量: $listening_ports"

# 检查防火墙状态
if command -v ufw > /dev/null; then
ufw_status=$(ufw status | head -1)
log_message "防火墙状态: $ufw_status"
fi
}

# 生成网络报告
generate_report() {
log_message "=== 网络监控报告 ==="

# 系统信息
log_message "系统: $(uname -a)"
log_message "运行时间: $(uptime)"

# 网络配置摘要
log_message "网络配置摘要:"
ip addr show | grep -E "(inet |UP)" | while read line; do
log_message " $line"
done
}

# 主函数
main() {
log_message "开始网络监控 - $(date)"
log_message "================================"

check_connectivity
echo

check_ports
echo

check_interface
echo

check_dns
echo

network_performance_test
echo

check_network_security
echo

generate_report

log_message "网络监控完成 - $(date)"
}

# 执行主函数
main

系统性能监控

性能指标监控

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# CPU监控
top -bn1 | grep "Cpu(s)" # CPU使用率
mpstat 1 5 # CPU统计信息
sar -u 1 5 # CPU使用率历史

# 内存监控
free -h # 内存使用情况
cat /proc/meminfo # 详细内存信息
vmstat 1 5 # 虚拟内存统计

# 磁盘IO监控
iostat -x 1 5 # 磁盘IO统计
iotop # 实时IO监控
lsof | grep deleted # 查找已删除但仍被占用的文件

# 系统负载
uptime # 系统负载
w # 当前用户和负载
cat /proc/loadavg # 负载平均值

# 进程资源使用
ps aux --sort=-%cpu | head -10 # CPU使用最高的进程
ps aux --sort=-%mem | head -10 # 内存使用最高的进程

综合性能监控脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#!/bin/bash
# 系统性能监控脚本

# 配置
ALERT_CPU_THRESHOLD=80
ALERT_MEM_THRESHOLD=80
ALERT_DISK_THRESHOLD=80
ALERT_LOAD_THRESHOLD=5.0
LOG_FILE="/var/log/performance-monitor.log"
REPORT_FILE="/var/log/performance-report.html"

# 记录日志
log_message() {
local message=$1
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] $message" | tee -a "$LOG_FILE"
}

# 发送告警
send_alert() {
local alert_type=$1
local message=$2
log_message "ALERT [$alert_type]: $message"

# 这里可以添加邮件、短信等告警方式
# echo "$message" | mail -s "Performance Alert: $alert_type" admin@example.com
}

# CPU监控
monitor_cpu() {
log_message "=== CPU监控 ==="

# 获取CPU使用率
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
cpu_usage_int=${cpu_usage%.*}

log_message "CPU使用率: ${cpu_usage}%"

if [ "$cpu_usage_int" -gt "$ALERT_CPU_THRESHOLD" ]; then
send_alert "HIGH_CPU" "CPU使用率过高: ${cpu_usage}%"
fi

# 获取CPU负载
load_avg=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | tr -d ',')
log_message "系统负载: $load_avg"

if (( $(echo "$load_avg > $ALERT_LOAD_THRESHOLD" | bc -l) )); then
send_alert "HIGH_LOAD" "系统负载过高: $load_avg"
fi

# 显示CPU使用最高的进程
log_message "CPU使用最高的进程:"
ps aux --sort=-%cpu | head -6 | tail -5 | while read line; do
log_message " $line"
done
}

# 内存监控
monitor_memory() {
log_message "=== 内存监控 ==="

# 获取内存使用情况
mem_info=$(free | grep Mem)
total_mem=$(echo $mem_info | awk '{print $2}')
used_mem=$(echo $mem_info | awk '{print $3}')
mem_usage=$(echo "scale=2; $used_mem * 100 / $total_mem" | bc)
mem_usage_int=${mem_usage%.*}

log_message "内存使用率: ${mem_usage}%"
log_message "总内存: $(numfmt --to=iec --from-unit=1024 $total_mem)B"
log_message "已用内存: $(numfmt --to=iec --from-unit=1024 $used_mem)B"

if [ "$mem_usage_int" -gt "$ALERT_MEM_THRESHOLD" ]; then
send_alert "HIGH_MEMORY" "内存使用率过高: ${mem_usage}%"
fi

# 显示内存使用最高的进程
log_message "内存使用最高的进程:"
ps aux --sort=-%mem | head -6 | tail -5 | while read line; do
log_message " $line"
done

# 检查swap使用情况
swap_info=$(free | grep Swap)
if [ ! -z "$swap_info" ]; then
swap_used=$(echo $swap_info | awk '{print $3}')
if [ "$swap_used" -gt 0 ]; then
log_message "警告: Swap正在使用 $(numfmt --to=iec --from-unit=1024 $swap_used)B"
fi
fi
}

# 磁盘监控
monitor_disk() {
log_message "=== 磁盘监控 ==="

# 检查磁盘使用率
df -h | grep -E '^/dev/' | while read line; do
usage=$(echo $line | awk '{print $5}' | cut -d'%' -f1)
mount_point=$(echo $line | awk '{print $6}')

log_message "磁盘 $mount_point 使用率: ${usage}%"

if [ "$usage" -gt "$ALERT_DISK_THRESHOLD" ]; then
send_alert "HIGH_DISK" "磁盘 $mount_point 使用率过高: ${usage}%"
fi
done

# 检查磁盘IO
if command -v iostat > /dev/null; then
log_message "磁盘IO统计:"
iostat -x 1 1 | grep -E '^(Device|[a-z])' | while read line; do
if [[ $line == Device* ]]; then
log_message " $line"
else
log_message " $line"
fi
done
fi

# 查找大文件
log_message "最大的文件 (前5个):"
find / -type f -size +100M -exec ls -lh {} \; 2>/dev/null | \
sort -k5 -hr | head -5 | while read line; do
log_message " $line"
done
}

# 网络监控
monitor_network() {
log_message "=== 网络监控 ==="

# 网络连接统计
connections=$(netstat -tupln | grep ESTABLISHED | wc -l)
log_message "当前网络连接数: $connections"

# 网络流量统计
for interface in $(ls /sys/class/net/ | grep -v lo); do
if [ -f "/sys/class/net/$interface/statistics/rx_bytes" ]; then
rx_bytes=$(cat /sys/class/net/$interface/statistics/rx_bytes)
tx_bytes=$(cat /sys/class/net/$interface/statistics/tx_bytes)

log_message "网络接口 $interface:"
log_message " 接收: $(numfmt --to=iec $rx_bytes)B"
log_message " 发送: $(numfmt --to=iec $tx_bytes)B"
fi
done

# 检查网络错误
for interface in $(ls /sys/class/net/ | grep -v lo); do
if [ -f "/sys/class/net/$interface/statistics/rx_errors" ]; then
rx_errors=$(cat /sys/class/net/$interface/statistics/rx_errors)
tx_errors=$(cat /sys/class/net/$interface/statistics/tx_errors)

if [ "$rx_errors" -gt 0 ] || [ "$tx_errors" -gt 0 ]; then
log_message "网络接口 $interface 错误: RX=$rx_errors, TX=$tx_errors"
fi
fi
done
}

# 系统服务监控
monitor_services() {
log_message "=== 系统服务监控 ==="

# 关键服务列表
critical_services=("ssh" "nginx" "mysql" "redis")

for service in "${critical_services[@]}"; do
if systemctl is-active --quiet "$service"; then
log_message "✓ 服务 $service 运行正常"
else
log_message "✗ 服务 $service 未运行"
send_alert "SERVICE_DOWN" "关键服务 $service 未运行"
fi
done

# 检查失败的服务
failed_services=$(systemctl list-units --failed --no-legend | wc -l)
if [ "$failed_services" -gt 0 ]; then
log_message "发现 $failed_services 个失败的服务"
systemctl list-units --failed --no-legend | while read line; do
log_message " 失败服务: $line"
done
fi
}

# 生成HTML报告
generate_html_report() {
cat > "$REPORT_FILE" << EOF
<!DOCTYPE html>
<html>
<head>
<title>系统性能监控报告</title>
<meta charset="UTF-8">
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.header { background-color: #f0f0f0; padding: 10px; border-radius: 5px; }
.section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
.alert { background-color: #ffebee; border-left: 4px solid #f44336; }
.normal { background-color: #e8f5e8; border-left: 4px solid #4caf50; }
.warning { background-color: #fff3e0; border-left: 4px solid #ff9800; }
pre { background-color: #f5f5f5; padding: 10px; border-radius: 3px; overflow-x: auto; }
</style>
</head>
<body>
<div class="header">
<h1>系统性能监控报告</h1>
<p>生成时间: $(date)</p>
<p>主机名: $(hostname)</p>
<p>系统: $(uname -a)</p>
</div>
EOF

# 添加CPU信息
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
cpu_class="normal"
if [ "${cpu_usage%.*}" -gt "$ALERT_CPU_THRESHOLD" ]; then
cpu_class="alert"
fi

cat >> "$REPORT_FILE" << EOF
<div class="section $cpu_class">
<h2>CPU使用情况</h2>
<p>CPU使用率: ${cpu_usage}%</p>
<p>系统负载: $(uptime | awk -F'load average:' '{print $2}')</p>
<pre>$(ps aux --sort=-%cpu | head -6)</pre>
</div>
EOF

# 添加内存信息
mem_usage=$(free | grep Mem | awk '{printf "%.1f", $3/$2 * 100.0}')
mem_class="normal"
if [ "${mem_usage%.*}" -gt "$ALERT_MEM_THRESHOLD" ]; then
mem_class="alert"
fi

cat >> "$REPORT_FILE" << EOF
<div class="section $mem_class">
<h2>内存使用情况</h2>
<p>内存使用率: ${mem_usage}%</p>
<pre>$(free -h)</pre>
<pre>$(ps aux --sort=-%mem | head -6)</pre>
</div>
EOF

# 添加磁盘信息
cat >> "$REPORT_FILE" << EOF
<div class="section">
<h2>磁盘使用情况</h2>
<pre>$(df -h)</pre>
</div>

</body>
</html>
EOF

log_message "HTML报告已生成: $REPORT_FILE"
}

# 主函数
main() {
log_message "开始系统性能监控 - $(date)"
log_message "========================================"

monitor_cpu
echo

monitor_memory
echo

monitor_disk
echo

monitor_network
echo

monitor_services
echo

# 生成HTML报告
generate_html_report

log_message "系统性能监控完成 - $(date)"
}

# 执行主函数
main

日志管理

日志查看和分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 系统日志
journalctl # 查看所有日志
journalctl -f # 实时查看日志
journalctl -u nginx # 查看特定服务日志
journalctl --since "1 hour ago" # 查看最近1小时日志
journalctl --until "2024-01-01" # 查看指定时间前的日志

# 传统日志文件
tail -f /var/log/syslog # 实时查看系统日志
grep "error" /var/log/nginx/error.log # 搜索错误信息
zcat /var/log/nginx/access.log.gz | grep "404" # 查看压缩日志

# 日志轮转
logrotate -d /etc/logrotate.conf # 测试日志轮转配置
logrotate -f /etc/logrotate.conf # 强制执行日志轮转

# 日志分析
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr # 统计IP访问次数
grep "$(date '+%d/%b/%Y')" /var/log/nginx/access.log | wc -l # 统计今日访问量

自动化日志分析脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/bin/bash
# 日志分析脚本

# 配置
NGINX_ACCESS_LOG="/var/log/nginx/access.log"
NGINX_ERROR_LOG="/var/log/nginx/error.log"
SYSTEM_LOG="/var/log/syslog"
REPORT_DIR="/var/log/analysis"
DATE=$(date '+%Y-%m-%d')

# 创建报告目录
mkdir -p "$REPORT_DIR"

# 分析Nginx访问日志
analyze_nginx_access() {
echo "=== Nginx访问日志分析 ===" > "$REPORT_DIR/nginx-access-$DATE.txt"

if [ -f "$NGINX_ACCESS_LOG" ]; then
# 今日访问统计
today_visits=$(grep "$(date '+%d/%b/%Y')" "$NGINX_ACCESS_LOG" | wc -l)
echo "今日访问量: $today_visits" >> "$REPORT_DIR/nginx-access-$DATE.txt"

# IP访问统计
echo -e "\n访问IP统计 (前10):" >> "$REPORT_DIR/nginx-access-$DATE.txt"
awk '{print $1}' "$NGINX_ACCESS_LOG" | sort | uniq -c | sort -nr | head -10 >> "$REPORT_DIR/nginx-access-$DATE.txt"

# 状态码统计
echo -e "\n状态码统计:" >> "$REPORT_DIR/nginx-access-$DATE.txt"
awk '{print $9}' "$NGINX_ACCESS_LOG" | sort | uniq -c | sort -nr >> "$REPORT_DIR/nginx-access-$DATE.txt"

# 访问页面统计
echo -e "\n访问页面统计 (前10):" >> "$REPORT_DIR/nginx-access-$DATE.txt"
awk '{print $7}' "$NGINX_ACCESS_LOG" | sort | uniq -c | sort -nr | head -10 >> "$REPORT_DIR/nginx-access-$DATE.txt"

# 用户代理统计
echo -e "\n用户代理统计 (前5):" >> "$REPORT_DIR/nginx-access-$DATE.txt"
awk -F'"' '{print $6}' "$NGINX_ACCESS_LOG" | sort | uniq -c | sort -nr | head -5 >> "$REPORT_DIR/nginx-access-$DATE.txt"
fi
}

# 分析Nginx错误日志
analyze_nginx_error() {
echo "=== Nginx错误日志分析 ===" > "$REPORT_DIR/nginx-error-$DATE.txt"

if [ -f "$NGINX_ERROR_LOG" ]; then
# 今日错误统计
today_errors=$(grep "$(date '+%Y/%m/%d')" "$NGINX_ERROR_LOG" | wc -l)
echo "今日错误数量: $today_errors" >> "$REPORT_DIR/nginx-error-$DATE.txt"

# 错误类型统计
echo -e "\n错误类型统计:" >> "$REPORT_DIR/nginx-error-$DATE.txt"
grep "$(date '+%Y/%m/%d')" "$NGINX_ERROR_LOG" | awk '{print $4}' | sort | uniq -c | sort -nr >> "$REPORT_DIR/nginx-error-$DATE.txt"

# 最新错误
echo -e "\n最新错误 (最近10条):" >> "$REPORT_DIR/nginx-error-$DATE.txt"
tail -10 "$NGINX_ERROR_LOG" >> "$REPORT_DIR/nginx-error-$DATE.txt"
fi
}

# 分析系统日志
analyze_system_log() {
echo "=== 系统日志分析 ===" > "$REPORT_DIR/system-$DATE.txt"

# 今日系统事件
echo "今日系统重要事件:" >> "$REPORT_DIR/system-$DATE.txt"
journalctl --since "today" --priority=err >> "$REPORT_DIR/system-$DATE.txt"

# 登录失败统计
echo -e "\n登录失败统计:" >> "$REPORT_DIR/system-$DATE.txt"
journalctl --since "today" | grep "Failed password" | wc -l >> "$REPORT_DIR/system-$DATE.txt"

# 服务重启统计
echo -e "\n服务重启事件:" >> "$REPORT_DIR/system-$DATE.txt"
journalctl --since "today" | grep -i "restart\|reload" >> "$REPORT_DIR/system-$DATE.txt"
}

# 生成综合报告
generate_summary() {
echo "=== 日志分析综合报告 ===" > "$REPORT_DIR/summary-$DATE.txt"
echo "生成时间: $(date)" >> "$REPORT_DIR/summary-$DATE.txt"
echo "分析日期: $DATE" >> "$REPORT_DIR/summary-$DATE.txt"
echo "" >> "$REPORT_DIR/summary-$DATE.txt"

# 汇总各项统计
if [ -f "$REPORT_DIR/nginx-access-$DATE.txt" ]; then
echo "Nginx访问统计:" >> "$REPORT_DIR/summary-$DATE.txt"
head -5 "$REPORT_DIR/nginx-access-$DATE.txt" >> "$REPORT_DIR/summary-$DATE.txt"
echo "" >> "$REPORT_DIR/summary-$DATE.txt"
fi

if [ -f "$REPORT_DIR/nginx-error-$DATE.txt" ]; then
echo "Nginx错误统计:" >> "$REPORT_DIR/summary-$DATE.txt"
head -5 "$REPORT_DIR/nginx-error-$DATE.txt" >> "$REPORT_DIR/summary-$DATE.txt"
echo "" >> "$REPORT_DIR/summary-$DATE.txt"
fi

if [ -f "$REPORT_DIR/system-$DATE.txt" ]; then
echo "系统事件统计:" >> "$REPORT_DIR/summary-$DATE.txt"
head -10 "$REPORT_DIR/system-$DATE.txt" >> "$REPORT_DIR/summary-$DATE.txt"
fi
}

# 清理旧报告
cleanup_old_reports() {
# 删除30天前的报告
find "$REPORT_DIR" -name "*.txt" -mtime +30 -delete
}

# 主函数
main() {
echo "开始日志分析 - $(date)"

analyze_nginx_access
analyze_nginx_error
analyze_system_log
generate_summary
cleanup_old_reports

echo "日志分析完成,报告保存在: $REPORT_DIR"
echo "综合报告: $REPORT_DIR/summary-$DATE.txt"
}

# 执行主函数
main

系统安全管理

安全检查和加固

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 用户和权限管理
who # 查看当前登录用户
last # 查看登录历史
lastlog # 查看用户最后登录时间
passwd -S username # 查看用户密码状态
chage -l username # 查看密码策略

# 文件权限检查
find / -perm -4000 -type f # 查找SUID文件
find / -perm -2000 -type f # 查找SGID文件
find / -perm -1000 -type d # 查找sticky bit目录
find /home -type f -perm 777 # 查找777权限文件

# 网络安全
netstat -tupln | grep LISTEN # 查看监听端口
ss -tupln # 现代版netstat
lsof -i # 查看网络连接
iptables -L # 查看防火墙规则

# 进程安全
ps aux | grep -v "^\[.*\]$" # 查看非内核进程
lsof -p PID # 查看进程打开的文件
pstree # 显示进程树

安全检查脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#!/bin/bash
# 系统安全检查脚本

REPORT_FILE="/var/log/security-check-$(date +%Y%m%d).txt"

# 记录日志
log_security() {
local message=$1
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] $message" | tee -a "$REPORT_FILE"
}

# 检查用户账户安全
check_user_security() {
log_security "=== 用户账户安全检查 ==="

# 检查空密码账户
empty_password_users=$(awk -F: '($2 == "") {print $1}' /etc/shadow 2>/dev/null)
if [ ! -z "$empty_password_users" ]; then
log_security "警告: 发现空密码账户: $empty_password_users"
else
log_security "✓ 未发现空密码账户"
fi

# 检查UID为0的账户
root_users=$(awk -F: '($3 == 0) {print $1}' /etc/passwd)
log_security "UID为0的账户: $root_users"

# 检查可登录的系统账户
system_login_users=$(awk -F: '($3 < 1000 && $7 != "/usr/sbin/nologin" && $7 != "/bin/false") {print $1}' /etc/passwd)
if [ ! -z "$system_login_users" ]; then
log_security "警告: 可登录的系统账户: $system_login_users"
fi

# 检查最近登录的用户
log_security "最近登录的用户:"
last -n 10 | while read line; do
log_security " $line"
done
}

# 检查文件权限
check_file_permissions() {
log_security "=== 文件权限检查 ==="

# 检查关键文件权限
critical_files=("/etc/passwd" "/etc/shadow" "/etc/group" "/etc/gshadow")

for file in "${critical_files[@]}"; do
if [ -f "$file" ]; then
perms=$(stat -c "%a" "$file")
owner=$(stat -c "%U:%G" "$file")
log_security "$file: 权限=$perms, 所有者=$owner"
fi
done

# 检查SUID/SGID文件
log_security "SUID文件检查:"
find /usr /bin /sbin -perm -4000 -type f 2>/dev/null | head -10 | while read file; do
log_security " SUID: $file"
done

# 检查世界可写文件
world_writable=$(find /etc /usr /bin /sbin -perm -002 -type f 2>/dev/null | wc -l)
if [ "$world_writable" -gt 0 ]; then
log_security "警告: 发现 $world_writable 个世界可写文件"
find /etc /usr /bin /sbin -perm -002 -type f 2>/dev/null | head -5 | while read file; do
log_security " 世界可写: $file"
done
fi
}

# 检查网络安全
check_network_security() {
log_security "=== 网络安全检查 ==="

# 检查监听端口
log_security "监听端口:"
netstat -tupln | grep LISTEN | while read line; do
log_security " $line"
done

# 检查外部连接
external_connections=$(netstat -tupln | grep ESTABLISHED | grep -v "127.0.0.1\|::1" | wc -l)
log_security "外部连接数: $external_connections"

# 检查防火墙状态
if command -v ufw > /dev/null; then
ufw_status=$(ufw status 2>/dev/null | head -1)
log_security "UFW防火墙状态: $ufw_status"
fi

if command -v iptables > /dev/null; then
iptables_rules=$(iptables -L | grep -c "^Chain")
log_security "iptables规则链数: $iptables_rules"
fi
}

# 检查进程安全
check_process_security() {
log_security "=== 进程安全检查 ==="

# 检查以root运行的进程
root_processes=$(ps aux | awk '$1 == "root" && $11 !~ /^\[.*\]$/ {count++} END {print count+0}')
log_security "以root运行的进程数: $root_processes"

# 检查可疑进程
suspicious_processes=$(ps aux | grep -E "(nc|netcat|telnet|ftp)" | grep -v grep | wc -l)
if [ "$suspicious_processes" -gt 0 ]; then
log_security "警告: 发现可疑网络进程"
ps aux | grep -E "(nc|netcat|telnet|ftp)" | grep -v grep | while read line; do
log_security " 可疑进程: $line"
done
fi

# 检查高CPU使用进程
log_security "CPU使用最高的进程:"
ps aux --sort=-%cpu | head -6 | tail -5 | while read line; do
log_security " $line"
done
}

# 检查日志安全
check_log_security() {
log_security "=== 日志安全检查 ==="

# 检查登录失败
failed_logins=$(journalctl --since "24 hours ago" | grep -i "failed\|failure" | wc -l)
log_security "24小时内登录失败次数: $failed_logins"

if [ "$failed_logins" -gt 10 ]; then
log_security "警告: 登录失败次数过多"
journalctl --since "24 hours ago" | grep -i "failed\|failure" | tail -5 | while read line; do
log_security " $line"
done
fi

# 检查sudo使用
sudo_usage=$(journalctl --since "24 hours ago" | grep -i "sudo" | wc -l)
log_security "24小时内sudo使用次数: $sudo_usage"

# 检查系统错误
system_errors=$(journalctl --since "24 hours ago" --priority=err | wc -l)
log_security "24小时内系统错误数: $system_errors"
}

# 检查系统完整性
check_system_integrity() {
log_security "=== 系统完整性检查 ==="

# 检查关键目录
critical_dirs=("/bin" "/sbin" "/usr/bin" "/usr/sbin" "/etc")

for dir in "${critical_dirs[@]}"; do
if [ -d "$dir" ]; then
file_count=$(find "$dir" -type f | wc -l)
log_security "$dir 目录文件数: $file_count"
fi
done

# 检查系统文件修改时间
recent_changes=$(find /etc -type f -mtime -1 2>/dev/null | wc -l)
if [ "$recent_changes" -gt 0 ]; then
log_security "最近24小时内修改的/etc文件数: $recent_changes"
find /etc -type f -mtime -1 2>/dev/null | head -5 | while read file; do
log_security " 最近修改: $file"
done
fi
}

# 生成安全建议
generate_security_recommendations() {
log_security "=== 安全建议 ==="

# 检查SSH配置
if [ -f "/etc/ssh/sshd_config" ]; then
if grep -q "^PermitRootLogin yes" /etc/ssh/sshd_config; then
log_security "建议: 禁用SSH root登录"
fi

if ! grep -q "^PasswordAuthentication no" /etc/ssh/sshd_config; then
log_security "建议: 禁用SSH密码认证,使用密钥认证"
fi
fi

# 检查自动更新
if ! command -v unattended-upgrades > /dev/null; then
log_security "建议: 安装并配置自动安全更新"
fi

# 检查防火墙
if ! command -v ufw > /dev/null && ! command -v iptables > /dev/null; then
log_security "建议: 安装并配置防火墙"
fi

log_security "建议: 定期更新系统和软件包"
log_security "建议: 使用强密码策略"
log_security "建议: 定期备份重要数据"
log_security "建议: 监控系统日志"
}

# 主函数
main() {
log_security "开始系统安全检查 - $(date)"
log_security "主机名: $(hostname)"
log_security "系统: $(uname -a)"
log_security "========================================"

check_user_security
echo

check_file_permissions
echo

check_network_security
echo

check_process_security
echo

check_log_security
echo

check_system_integrity
echo

generate_security_recommendations

log_security "========================================"
log_security "系统安全检查完成 - $(date)"
log_security "报告文件: $REPORT_FILE"
}

# 执行主函数
main

总结

Linux系统管理是一个涵盖面广、实践性强的技能领域。通过本文的实战指南,我们系统地学习了:

核心技能要点

  1. 文件系统管理:掌握文件操作、权限管理、磁盘监控等基础技能
  2. 进程管理:熟练使用进程控制命令,理解系统服务管理
  3. 网络管理:掌握网络配置、诊断和监控技巧
  4. 性能监控:建立完整的系统性能监控体系
  5. 日志管理:有效的日志分析和管理策略
  6. 安全管理:系统安全检查和加固措施

实践建议

  • 自动化优先:将重复性工作编写成脚本自动执行
  • 监控告警:建立完善的监控和告警机制
  • 文档记录:详细记录系统配置和操作过程
  • 定期维护:制定系统维护计划并严格执行
  • 安全意识:始终将安全放在首位

进阶方向

  • 容器技术:Docker、Kubernetes等容器编排
  • 自动化运维:Ansible、Puppet等配置管理工具
  • 云平台管理:AWS、阿里云等云服务管理
  • DevOps实践:CI/CD流水线、基础设施即代码

Linux系统管理是一个需要持续学习和实践的领域。随着技术的发展,新的工具和方法不断涌现,但基础的系统管理原理和技能始终是核心。掌握这些技能不仅能提高工作效率,更能为职业发展奠定坚实基础。