1. Unix 哲学的浪漫实践
Linux 命令行界面(CLI)的魅力在于其简洁而强大的设计哲学。Unix 哲学强调"一个工具只做一件事,并把它做好",这种理念造就了众多小巧而专注的命令行工具。当这些工具通过管道(Pipe)和重定向组合使用时,就能产生惊人的效果。
提示:管道符
|的本质是将前一个命令的标准输出(stdout)作为后一个命令的标准输入(stdin)。理解这一点对构建复杂命令组合至关重要。
1.1 命令组合的核心要素
构建高效命令行组合需要掌握几个关键概念:
-
标准流:Linux 系统为每个进程提供三个标准流:
- stdin(标准输入,文件描述符0)
- stdout(标准输出,文件描述符1)
- stderr(标准错误,文件描述符2)
-
重定向:
>覆盖输出到文件>>追加输出到文件2>重定向错误输出&>重定向所有输出
-
过滤器命令:
grep:模式匹配awk:文本处理sed:流编辑器sort:排序uniq:去重
2. 生产力提升实战
2.1 系统监控与进程管理
2.1.1 精准定位资源占用进程
传统 top 命令虽然直观,但在自动化处理方面有所欠缺。以下命令组合可以更精确地识别资源占用情况:
bash复制# 内存占用前5的进程(带完整命令行)
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head -n 6
# CPU占用前5的进程(带用户信息)
ps -eo user,pid,ppid,cmd,%cpu --sort=-%cpu | head -n 6
参数解析:
-e:显示所有进程-o:自定义输出字段--sort:指定排序字段(-表示降序)head -n 6:显示前6行(含标题行)
2.1.2 进程树可视化
理解进程间关系对排查问题很有帮助:
bash复制pstree -p -a -U -n | less -S
参数说明:
-p:显示PID-a:显示完整命令-U:使用UTF-8字符绘制树形-n:按PID排序而非按名称
2.2 批量操作技巧
2.2.1 安全删除特定文件
bash复制find /path/to/files -name "*.log" -mtime +30 -type f -print0 | xargs -0 rm -v
安全要点:
-print0和xargs -0组合可以正确处理含空格/特殊字符的文件名-v参数显示删除过程,便于审计- 执行前可先用
-exec echo {} \;预览将被删除的文件
2.2.2 并行处理加速任务
bash复制find . -name "*.jpg" -print0 | xargs -0 -P 4 -I {} convert {} -resize 50% {}_resized.jpg
性能优化:
-P 4:使用4个并行进程-I {}:指定替换字符串- 适用于CPU密集型任务(如图像处理)
3. 数据分析高级技巧
3.1 日志分析实战
3.1.1 实时监控日志变化
bash复制tail -f /var/log/nginx/access.log | awk '{print $1, $7, $9}' | column -t
增强版(带时间戳和状态码统计):
bash复制tail -f access.log | awk '{
print strftime("%Y-%m-%d %H:%M:%S"), $1, $7, $9;
status[$9]++; total++
}
END {
print "\nStatus Code Summary:";
for (code in status)
printf "%s: %.2f%%\n", code, (status[code]/total)*100
}'
3.1.2 复杂日志聚合分析
bash复制cat access.log | awk '{
# 按小时和IP统计
split($4, datetime, ":");
hour = datetime[2];
ip_hour = $1 SUBSEP hour;
count[ip_hour]++;
total++
}
END {
# 输出每个IP每小时访问量占比
for (key in count) {
split(key, parts, SUBSEP);
ip = parts[1];
hour = parts[2];
printf "%s\t%s\t%d\t%.2f%%\n",
ip, hour, count[key], (count[key]/total)*100
}
}' | sort -k3nr | head -20
3.2 文本处理进阶
3.2.1 CSV文件处理
bash复制# 计算CSV第二列平均值
awk -F',' 'NR>1 {sum+=$2; count++} END {print "Average:", sum/count}' data.csv
# 提取特定列并转换格式
awk -F',' '{print $1 "\t" $3 "\t" $5/1000 "K"}' data.csv | column -t
3.2.2 JSON数据处理
bash复制# 使用jq工具解析JSON
curl -s https://api.example.com/data | jq '.items[] | select(.value > 100) | {name, id}'
# 无jq环境下的替代方案
grep -oP '"name": "\K[^"]+' data.json
4. 系统维护与安全
4.1 磁盘空间管理
4.1.1 可视化磁盘使用
bash复制du -h --max-depth=1 / | sort -h
增强版(带百分比显示):
bash复制du -sk /* 2>/dev/null | sort -n | awk '
BEGIN {
total = 0;
printf "%-50s %10s %8s\n", "Directory", "Size", "Percent"
}
{
total += $1;
sizes[$2] = $1
}
END {
for (dir in sizes) {
percent = (sizes[dir]/total)*100;
printf "%-50s %10dK %7.2f%%\n", dir, sizes[dir], percent
}
printf "%-50s %10dK %7s\n", "TOTAL", total, "100%"
}'
4.2 网络监控
4.2.1 实时网络连接监控
bash复制watch -n 1 "netstat -tunapl | awk '{print \$5}' | cut -d: -f1 | sort | uniq -c | sort -n"
增强版(带地理位置信息):
bash复制netstat -tunapl | awk '/^tcp|udp/{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n |
while read count ip; do
if [[ $ip != "0.0.0.0" ]]; then
country=$(whois $ip | grep -i country | head -1 | awk '{print $2}');
echo "$count $ip $country";
fi;
done
5. 极客创意与实用工具
5.1 终端增强
5.1.1 自定义命令提示符
bash复制# 在~/.bashrc中添加
PS1='\[\e[1;32m\]\u@\h \[\e[1;34m\]\w \[\e[1;31m\]$(git branch 2>/dev/null | grep "^*" | colrm 1 2)\n\[\e[1;36m\]\$ \[\e[0m\]'
功能说明:
- 显示用户名、主机名
- 当前工作目录
- Git分支信息(如果当前是Git仓库)
- 多行显示更清晰
5.1.2 历史命令智能搜索
bash复制# 在~/.bashrc中添加
bind '"\e[A": history-search-backward'
bind '"\e[B": history-search-forward'
使用技巧:
- 输入部分命令后按↑/↓键可搜索历史命令
- 比
Ctrl+R更直观
5.2 实用小工具
5.2.1 随机密码生成
bash复制# 生成16位随机密码
tr -dc 'A-Za-z0-9!@#$%^&*()' < /dev/urandom | head -c 16; echo
# 带特殊字符检查的密码生成
while true; do
pass=$(tr -dc 'A-Za-z0-9!@#$%^&*()' < /dev/urandom | head -c 16)
[[ $pass =~ [A-Z] && $pass =~ [a-z] && $pass =~ [0-9] && $pass =~ [!@#$%^&*()] ]] && break
done
echo $pass
5.2.2 文件差异对比
bash复制# 彩色化diff输出
diff -u file1 file2 | colordiff | less -R
# 目录对比
diff -qr dir1 dir2 | awk '/^Files/{print $2, $4}'
6. 性能调优与故障排查
6.1 系统性能分析
6.1.1 快速性能快照
bash复制(echo "===== DATE ====="; date; echo "\n===== UPTIME ====="; uptime;
echo "\n===== MEMORY ====="; free -h; echo "\n===== DISK ====="; df -h;
echo "\n===== TOP ====="; top -b -n 1 | head -20) > system_snapshot_$(date +%Y%m%d_%H%M%S).log
6.1.2 网络延迟测试
bash复制ping -c 10 example.com | awk -F'/' 'END{print "Avg RTT: "$5"ms"}'
6.2 故障排查流程
6.2.1 服务故障检查清单
bash复制# 检查服务状态
systemctl status servicename
# 检查端口监听
ss -tulnp | grep servicename
# 检查日志
journalctl -u servicename -n 50 --no-pager
# 检查依赖
systemctl list-dependencies servicename
6.2.2 内存泄漏排查
bash复制# 监控进程内存变化
watch -n 1 "ps -eo pid,cmd,%mem --sort=-%mem | head -n 10"
# 生成内存快照对比
valgrind --leak-check=full ./your_program
7. 自动化与脚本技巧
7.1 安全脚本编写
7.1.1 脚本安全最佳实践
bash复制#!/bin/bash
set -euo pipefail # 严格模式
IFS=$'\n\t' # 安全的分隔符设置
# 参数检查
if [[ $# -eq 0 ]]; then
echo "Usage: $0 <input_file>"
exit 1
fi
# 文件存在性检查
if [[ ! -f "$1" ]]; then
echo "Error: File $1 not found" >&2
exit 2
fi
# 临时文件安全处理
tempfile=$(mktemp /tmp/backup_XXXXXX)
trap 'rm -f "$tempfile"' EXIT ERR
# 主处理逻辑
process_data() {
# 函数内局部变量
local input=$1
local output=$2
# 实际处理代码
grep "pattern" "$input" > "$output"
}
7.2 定时任务管理
7.2.1 高级crontab技巧
bash复制# 每月1号凌晨检查磁盘空间
0 0 1 * * /usr/bin/df -h > /var/log/disk_usage.log 2>&1
# 工作日每2小时执行一次备份
0 */2 * * 1-5 /path/to/backup_script.sh
# 复杂的执行时间控制
0 8-18/2 * * * [ $(date +\%u) -le 5 ] && /path/to/work_hour_task.sh
注意事项:
- 使用完整路径避免环境变量问题
- 重定向输出便于调试
- 复杂逻辑建议封装到脚本中
8. 终端艺术与彩蛋
8.1 ASCII艺术生成
bash复制# 文本转ASCII艺术
figlet "Hello World"
# 彩色日历
cal | grep --color -E "|$(date +%d)|"
# 终端屏保
cmatrix -ab
8.2 实用别名集合
bash复制# 在~/.bashrc中添加
alias ll='ls -alFh --color=auto'
alias grep='grep --color=auto'
alias df='df -h'
alias du='du -h'
alias mkdir='mkdir -pv'
alias hg='history | grep'
alias ports='netstat -tulanp'
alias myip='curl ifconfig.me'
alias weather='curl wttr.in'
9. 命令组合设计模式
9.1 常见组合模式
-
过滤-处理-输出模式:
bash复制
input_command | filter_command | processing_command | output_formatter -
并行处理模式:
bash复制
xargs -P 4 -I {} command_to_run {} -
实时监控模式:
bash复制watch -n 1 "command_to_monitor" -
数据聚合模式:
bash复制awk '{count[$1]++} END {for (item in count) print item, count[item]}'
9.2 调试技巧
bash复制# 逐步执行检查
echo "Raw output:"; cmd1
echo "After first pipe:"; cmd1 | cmd2
echo "Final output:"; cmd1 | cmd2 | cmd3
# 使用tee检查中间结果
complex_command | tee debug.log | next_command
# 设置调试模式
set -x # 开启命令打印
complex_pipeline
set +x # 关闭命令打印
10. 资源管理与优化
10.1 系统资源监控
10.1.1 实时资源仪表盘
bash复制watch -n 1 "echo 'CPU:'; mpstat -P ALL 1 1 | tail -n +4; echo; echo 'Memory:'; free -h; echo; echo 'Disk:'; df -h /"
10.1.2 进程资源限制
bash复制# 限制CPU使用
cpulimit -l 50 -p 1234
# 限制内存使用
ulimit -v 500000 # 限制为500MB虚拟内存
10.2 命令性能优化
10.2.1 减少管道使用
bash复制# 低效方式
cat file | grep pattern | awk '{print $1}'
# 高效方式
awk '/pattern/{print $1}' file
10.2.2 使用更高效的工具
bash复制# 替代grep的快速搜索
ag "pattern" /path/to/search
# 替代find的快速文件查找
fd "pattern" /path/to/search
11. 跨平台兼容技巧
11.1 兼容不同Unix系统
bash复制# 检测系统类型
case "$(uname -s)" in
Linux*) machine=Linux;;
Darwin*) machine=Mac;;
CYGWIN*) machine=Cygwin;;
MINGW*) machine=MinGw;;
*) machine="UNKNOWN"
esac
# 系统特定命令处理
if [[ "$machine" == "Linux" ]]; then
alias ls='ls --color=auto'
elif [[ "$machine" == "Mac" ]]; then
alias ls='ls -G'
fi
11.2 处理不同Shell环境
bash复制# 检测当前Shell
current_shell="$(ps -p $$ -o comm=)"
# 兼容性函数定义
function path_append() {
if [[ ":$PATH:" != *":$1:"* ]]; then
if [[ "$current_shell" == "bash" ]]; then
export PATH="$PATH:$1"
elif [[ "$current_shell" == "zsh" ]]; then
path+=("$1")
fi
fi
}
12. 安全增强实践
12.1 安全审计命令
bash复制# 检查SUID文件
find / -perm -4000 -type f -exec ls -ld {} \; 2>/dev/null
# 检查可写目录
find / -type d -perm -o+w -exec ls -ld {} \; 2>/dev/null
# 检查无属主文件
find / -nouser -o -nogroup -exec ls -ld {} \; 2>/dev/null
12.2 安全传输技巧
bash复制# 加密文件传输
tar czf - /path/to/data | openssl enc -aes-256-cbc -salt -out data.tar.gz.enc
13. 版本控制集成
13.1 Git增强命令
bash复制# 查看简洁状态
git status -sb
# 交互式添加补丁
git add -p
# 美化日志
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
13.2 批量Git操作
bash复制# 多仓库更新
find . -name .git -type d | while read dir; do
(cd "${dir%/*}" && echo "Updating $(pwd)" && git pull)
done
14. 数据库命令行操作
14.1 MySQL快速查询
bash复制mysql -u user -p -e "SELECT table_name, table_rows FROM information_schema.tables WHERE table_schema = 'database'"
14.2 PostgreSQL元数据查询
bash复制psql -U user -d dbname -c "\dt+"
15. 容器与虚拟化集成
15.1 Docker快捷命令
bash复制# 清理无用容器
docker ps -aq --no-trunc | xargs docker rm
# 清理无用镜像
docker images -q --filter dangling=true | xargs docker rmi
15.2 Kubernetes常用操作
bash复制# 查看Pod资源使用
kubectl top pod --all-namespaces
# 查看节点资源
kubectl describe nodes | grep -A 5 "Allocated resources"
16. 性能基准测试
16.1 磁盘I/O测试
bash复制# 写入测试
dd if=/dev/zero of=./testfile bs=1G count=1 oflag=direct
# 读取测试
dd if=./testfile of=/dev/null bs=1G count=1 iflag=direct
16.2 网络带宽测试
bash复制# 简单测速
curl -o /dev/null http://speedtest.example.com/1GB.zip
# 使用iperf3
iperf3 -c server.example.com
17. 系统信息收集
17.1 硬件信息汇总
bash复制lshw -short 2>/dev/null | grep -E "system|processor|memory|disk"
17.2 系统配置快照
bash复制(echo "===== SYSTEM ====="; uname -a;
echo "\n===== CPU ====="; lscpu;
echo "\n===== MEMORY ====="; free -h;
echo "\n===== DISK ====="; lsblk;
echo "\n===== NETWORK ====="; ip a) > system_info_$(date +%Y%m%d).log
18. 实用正则表达式集
18.1 常用正则模式
bash复制# 提取IP地址
grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}'
# 提取邮箱地址
grep -Eio '[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}'
# 提取URL
grep -Eo 'https?://[^" ]+'
18.2 复杂文本转换
bash复制# 转换日期格式
sed -E 's/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/\3-\2-\1/g'
# 缩进调整
awk '{printf "%" (length($0)+4) "s\n", $0}'
19. 远程管理技巧
19.1 SSH高级用法
bash复制# 通过跳板机连接
ssh -J user@jump_host user@target_host
# 持久化连接
ssh -o ControlMaster=auto -o ControlPath=~/.ssh/%r@%h:%p -o ControlPersist=1h user@host
19.2 批量执行命令
bash复制parallel-ssh -i -h hosts.txt "command_to_run"
20. 命令行界面美化
20.1 终端主题配置
bash复制# 设置LS_COLORS
export LS_COLORS="di=1;36:ln=35:so=32:pi=33:ex=31:bd=34;46:cd=34;43:su=30;41:sg=30;46:tw=30;42:ow=30;43"
20.2 进度条显示
bash复制# 复制文件带进度条
pv input_file > output_file
# 处理大量文件
find . -type f | pv -l | xargs -I {} process_file {}
21. 实用函数库
21.1 常用函数定义
bash复制# 计算目录大小
dsize() { du -sh "${1:-.}"; }
# 创建并进入目录
mkcd() { mkdir -p "$1" && cd "$1"; }
# 查找并编辑
fe() { find . -type f -name "*$1*" | fzf | xargs ${EDITOR:-vim}; }
21.2 系统管理函数
bash复制# 杀死匹配进程
killp() { ps aux | grep -i "$1" | awk '{print $2}' | xargs kill -9; }
# 端口占用查询
port() { lsof -i :"$1"; }
# 提取压缩文件
extract() {
if [ -f "$1" ]; then
case "$1" in
*.tar.bz2) tar xvjf "$1" ;;
*.tar.gz) tar xvzf "$1" ;;
*.bz2) bunzip2 "$1" ;;
*.rar) unrar x "$1" ;;
*.gz) gunzip "$1" ;;
*.tar) tar xvf "$1" ;;
*.tbz2) tar xvjf "$1" ;;
*.tgz) tar xvzf "$1" ;;
*.zip) unzip "$1" ;;
*.Z) uncompress "$1" ;;
*.7z) 7z x "$1" ;;
*) echo "Unknown archive format: $1" ;;
esac
else
echo "File not found: $1"
fi
}
22. 文件处理技巧
22.1 批量重命名
bash复制# 使用rename工具
rename 's/\.jpeg$/\.jpg/' *.jpeg
# 使用mmv工具
mmv '*.old' '#1.new'
22.2 文件内容处理
bash复制# 批量替换文本
find . -type f -name "*.txt" -exec sed -i 's/old/new/g' {} +
# 删除空行
sed -i '/^$/d' file.txt
23. 时间与日期处理
23.1 日期计算
bash复制# 获取昨天日期
date -d "yesterday" +%Y-%m-%d
# 获取30天前的日期
date -d "30 days ago" +%Y-%m-%d
23.2 执行时间测量
bash复制# 简单计时
time command_to_measure
# 高精度计时
start=$(date +%s.%N)
command_to_measure
end=$(date +%s.%N)
runtime=$(echo "$end - $start" | bc)
echo "Runtime: $runtime seconds"
24. 数学计算技巧
24.1 命令行计算器
bash复制# 使用bc
echo "scale=2; 100/3" | bc
# 使用awk
awk 'BEGIN {print 100/3}'
24.2 统计计算
bash复制# 计算平均值
awk '{sum+=$1; count++} END {print sum/count}' data.txt
# 计算标准差
awk '{sum+=$1; sumsq+=$1*$1} END {print sqrt(sumsq/NR - (sum/NR)^2)}' data.txt
25. 多媒体处理
25.1 图像处理
bash复制# 批量调整图片大小
mogrify -resize 50% *.jpg
# 转换格式
convert input.png output.jpg
25.2 音频处理
bash复制# 转换音频格式
ffmpeg -i input.mp3 output.ogg
# 提取音频片段
ffmpeg -i input.mp3 -ss 00:01:30 -t 00:00:30 output.mp3
26. 文档处理
26.1 PDF操作
bash复制# 合并PDF
gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=merged.pdf *.pdf
# 提取文本
pdftotext input.pdf output.txt
26.2 Markdown处理
bash复制# 转换Markdown为HTML
pandoc -f markdown -t html input.md -o output.html
# 检查死链接
grep -oP '\[.*?\]\(.*?\)' *.md | awk -F'[()]' '{print $2}' | xargs -I {} sh -c 'curl -s -o /dev/null -w "%{http_code} %{url_effective}\n" {}' | grep -v "^200"
27. 网络诊断
27.1 连接测试
bash复制# 测试端口连通性
nc -zv example.com 80
# 跟踪路由
mtr example.com
27.2 网络性能
bash复制# 测量下载速度
curl -o /dev/null -w "%{speed_download}\n" http://example.com/file
# 测量延迟
ping -c 10 example.com | tail -1 | awk -F'/' '{print $5}'
28. 系统维护自动化
28.1 自动更新
bash复制# 安全更新
apt-get update && apt-get upgrade -y --only-upgrade security
# 自动清理
apt-get autoremove -y && apt-get clean
28.2 日志轮转
bash复制# 手动轮转日志
logrotate -f /etc/logrotate.conf
29. 加密与安全
29.1 文件加密
bash复制# 加密文件
openssl aes-256-cbc -salt -in file.txt -out file.txt.enc
# 解密文件
openssl aes-256-cbc -d -in file.txt.enc -out file.txt
29.2 密码管理
bash复制# 生成密码哈希
openssl passwd -1 "yourpassword"
# 安全删除文件
shred -u -z -n 10 sensitive_file
30. 终端复用技巧
30.1 tmux高级用法
bash复制# 创建命名会话
tmux new -s session_name
# 分割窗口
tmux split-window -h
tmux split-window -v
30.2 screen实用技巧
bash复制# 创建命名窗口
screen -S session_name
# 共享会话
screen -x existing_session
31. 系统启动分析
31.1 启动时间优化
bash复制# 分析启动时间
systemd-analyze blame
systemd-analyze critical-chain
31.2 服务依赖分析
bash复制# 查看服务依赖图
systemd-analyze dot | dot -Tsvg > deps.svg
32. 硬件监控
32.1 温度监控
bash复制# CPU温度
sensors | grep Core
# 磁盘温度
hddtemp /dev/sd?
32.2 电源管理
bash复制# 电池状态
upower -i /org/freedesktop/UPower/devices/battery_BAT0
# CPU频率
cpupower frequency-info
33. 用户管理
33.1 批量用户操作
bash复制# 批量创建用户
newusers user_list.txt
# 批量修改密码
chpasswd < passwords.txt
33.2 权限管理
bash复制# 递归修改权限
find /path -type d -exec chmod 755 {} \;
find /path -type f -exec chmod 644 {} \;
34. 备份策略
34.1 增量备份
bash复制rsync -avz --delete --link-dest=/path/to/last_backup /source /path/to/new_backup
34.2 数据库备份
bash复制mysqldump -u user -p database | gzip > backup_$(date +%Y%m%d).sql.gz
35. 系统调优
35.1 内核参数调整
bash复制# 查看当前参数
sysctl -a
# 临时修改
sysctl -w net.core.somaxconn=4096
35.2 文件系统优化
bash复制# 调整ext4日志模式
tune2fs -o journal_data_writeback /dev/sdX1
36. 容器优化
36.1 Docker存储清理
bash复制# 清理无用数据
docker system prune -af
# 清理特定资源
docker volume prune
docker network prune
36.2 镜像构建优化
bash复制# 多阶段构建
docker build --target builder -t intermediate .
docker build --target runtime -t final .
37. 云服务集成
37.1 AWS CLI技巧
bash复制# 列出所有EC2实例
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,State.Name,PublicIpAddress]' --output text
# 上传文件到S3
aws s3 cp file.txt s3://bucket/path/
37.2 云存储管理
bash复制# 同步本地目录到云存储
rclone sync /local/path remote:bucket/path
38. 持续集成
38.1 Jenkins CLI
bash复制# 触发构建
java -jar jenkins-cli.jar -s http://jenkins.example.com build job-name
# 获取构建状态
java -jar jenkins-cli.jar -s http://jenkins.example.com console job-name lastBuild
38.2 GitLab API
bash复制# 获取项目信息
curl --header "PRIVATE-TOKEN: your_token" "https://gitlab.example.com/api/v4/projects"
39. 监控告警
39.1 Prometheus查询
bash复制# 查询CPU使用率
curl -G http://prometheus.example.com/api/v1/query --data-urlencode 'query=100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)'
39.2 告警测试
bash复制# 发送测试告警
curl -X POST -H 'Content-Type: application/json' -d '{"status":"firing","alerts":[{"status":"firing","labels":{"alertname":"TestAlert","severity":"warning"},"annotations":{"description":"This is a test alert"}}]}' http://alertmanager.example.com/api/v1/alerts
40. 日志分析
40.1 实时日志处理
bash复制# 提取错误并统计
tail -f app.log | grep -i error | awk '{count[$5]++} END {for (err in count) print err, count[err]}'
40.2 日志时间分析
bash复制# 统计每小时请求量
cat access.log | awk '{split($4,time,":"); print time[2]}' | sort | uniq -c
41. 性能剖析
41.1 CPU剖析
bash复制# 采样CPU使用
perf record -F 99 -ag -- sleep 30
perf report
41.2 内存剖析
bash复制# 检测内存泄漏
valgrind --leak-check=full ./your_program
42. 系统审计
42.1 安全审计
bash复制# 检查登录失败
lastb | head -20
# 检查认证日志
grep -i "failed" /var/log/auth.log
42.2 配置审计
bash复制# 检查敏感文件权限
find /etc -type f -perm -o+w -exec ls -la {} \;
43. 网络配置
43.1 接口管理
bash复制# 绑定多个IP
ip addr add 192.168.1.100/24 dev eth0 label eth0:1
43.2 路由管理
bash复制# 添加静态路由
ip route add 10.0.0.0/8 via 192.168.1.1
44. 防火墙管理
44.1 iptables规则
bash复制# 允许已建立的连接
iptables -A INPUT -m conntrack --ct