引言 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 find /home -user john -size +100M find /tmp -empty -delete cat file.txt less file.txt head -n 20 file.txt 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 unzip archive.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 } }' } 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 "=== 清理临时文件 ===" 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 top htop top -p 1234 pgrep nginx pgrep -f "python app.py" pidof nginx kill 1234 kill -9 1234 killall nginx pkill -f "python" nohup command & jobs bg %1 fg %1 disown %1 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 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 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 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 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_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 ip addr add 192.168.1.100/24 dev eth0 ip link set eth0 up ip route add default via 192.168.1.1 netstat -tuln netstat -tupln ss -tuln ss -tulpn ping -c 4 google.com traceroute google.com mtr google.com nslookup google.com dig google.com iftop nethogs iotop tcpdump -i eth0 ufw enable ufw allow 22 ufw allow from 192.168.1.0/24 ufw deny 80 ufw status iptables -L iptables -A INPUT -p tcp --dport 80 -j ACCEPT 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_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 } 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 "=== 网络性能测试 ===" 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 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 top -bn1 | grep "Cpu(s)" mpstat 1 5 sar -u 1 5 free -h cat /proc/meminfo vmstat 1 5 iostat -x 1 5 iotop lsof | grep deleted uptime w cat /proc/loadavg ps aux --sort =-%cpu | head -10 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 " } monitor_cpu () { log_message "=== 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 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 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_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 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 } 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_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 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" 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 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 " 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" 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 } 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 () { 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 find / -perm -2000 -type f find / -perm -1000 -type d find /home -type f -perm 777 netstat -tupln | grep LISTEN ss -tupln 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 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 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_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 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_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 "=== 安全建议 ===" 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系统管理是一个涵盖面广、实践性强的技能领域。通过本文的实战指南,我们系统地学习了:
核心技能要点
文件系统管理 :掌握文件操作、权限管理、磁盘监控等基础技能
进程管理 :熟练使用进程控制命令,理解系统服务管理
网络管理 :掌握网络配置、诊断和监控技巧
性能监控 :建立完整的系统性能监控体系
日志管理 :有效的日志分析和管理策略
安全管理 :系统安全检查和加固措施
实践建议
自动化优先 :将重复性工作编写成脚本自动执行
监控告警 :建立完善的监控和告警机制
文档记录 :详细记录系统配置和操作过程
定期维护 :制定系统维护计划并严格执行
安全意识 :始终将安全放在首位
进阶方向
容器技术 :Docker、Kubernetes等容器编排
自动化运维 :Ansible、Puppet等配置管理工具
云平台管理 :AWS、阿里云等云服务管理
DevOps实践 :CI/CD流水线、基础设施即代码
Linux系统管理是一个需要持续学习和实践的领域。随着技术的发展,新的工具和方法不断涌现,但基础的系统管理原理和技能始终是核心。掌握这些技能不仅能提高工作效率,更能为职业发展奠定坚实基础。