中频工具 - 每周使用
这些工具不是每天都用,但每周都会碰到,是后端开发者必须掌握的
一、服务管理(systemd/systemctl)
1.1 systemd 是什么?
systemd 是现代 Linux 系统的初始化系统和服务管理器。它取代了传统的 SysVinit,负责:
- 系统启动和初始化
- 服务管理(启动、停止、重启)
- 依赖关系管理
- 日志管理(通过 journald)
- 设备管理、挂载管理等
几乎所有主流 Linux 发行版都使用 systemd:Ubuntu 15.04+、CentOS 7+、Debian 8+ 等。
1.2 systemctl 基本命令
# 查看服务状态
systemctl status nginx
systemctl status nginx.service # 完整写法
# 启动/停止/重启服务
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # 重新加载配置(不中断服务)
# 设置开机启动
sudo systemctl enable nginx
sudo systemctl disable nginx
sudo systemctl enable --now nginx # 启用并立即启动
# 查看是否启用
systemctl is-enabled nginx
systemctl is-active nginx
# 列出服务
systemctl list-units --type=service # 活跃的服务
systemctl list-units --type=service --all # 所有服务
systemctl list-units --type=service --state=failed # 失败的服务
systemctl list-unit-files --type=service # 所有服务文件
# 查看依赖
systemctl list-dependencies nginx
systemctl list-dependencies --reverse nginx # 反向依赖
# 查看服务日志
journalctl -u nginx
journalctl -u nginx -f # 实时跟踪
journalctl -u nginx --since "1 hour ago"
# 屏蔽/解除屏蔽服务
sudo systemctl mask nginx # 屏蔽(无法启动)
sudo systemctl unmask nginx # 解除屏蔽
# 重新加载 systemd 配置
sudo systemctl daemon-reload
1.3 创建自定义服务
服务文件位于 /etc/systemd/system/:
# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network.target
[Service]
Type=simple
User=deploy
WorkingDirectory=/home/deploy/app
ExecStart=/home/deploy/app/myapp
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
常用服务类型:
simple: 默认,主进程就是 ExecStart 指定的进程forking: 传统 daemon 方式oneshot: 执行一次就退出notify: 服务就绪后发送通知
1.4 service 命令(传统方式)
虽然现在主要用 systemctl,但 service 命令仍然可用:
sudo service nginx start
sudo service nginx stop
sudo service nginx restart
sudo service nginx status
二、归档与压缩
2.1 tar - 归档工具
# 创建归档
tar -cvf archive.tar files/
# 创建压缩归档
tar -czvf archive.tar.gz files/ # gzip
tar -cjvf archive.tar.bz2 files/ # bzip2
tar -cJvf archive.tar.xz files/ # xz
# 查看内容
tar -tvf archive.tar.gz
# 解压
tar -xvf archive.tar
tar -xzvf archive.tar.gz
tar -xzvf archive.tar.gz -C /dest/ # 指定目录
# 排除文件
tar -czvf archive.tar.gz --exclude='*.log' files/
2.2 gzip/gunzip
gzip file.txt # 压缩
gunzip file.txt.gz # 解压
gzip -k file.txt # 保留原文件
gzip -9 file.txt # 最高压缩
2.3 zip/unzip
zip -r archive.zip directory/
unzip archive.zip
unzip archive.zip -d /dest/
unzip -l archive.zip # 查看内容
三、定时任务
3.1 cron 基础
# 编辑 crontab
crontab -e
# 查看 crontab
crontab -l
# 删除 crontab
crontab -r
3.2 crontab 格式
# 分 时 日 月 周 命令
# * * * * * command
# 每分钟
* * * * * /path/to/script.sh
# 每5分钟
*/5 * * * * /path/to/script.sh
# 每天凌晨2点
0 2 * * * /path/to/script.sh
# 每周一凌晨3点
0 3 * * 1 /path/to/script.sh
# 每月1日凌晨4点
0 4 1 * * /path/to/script.sh
# 工作日9点
0 9 * * 1-5 /path/to/script.sh
3.3 crontab 最佳实践
# 设置环境变量
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=admin@example.com
# 重定向输出
0 2 * * * /path/to/script.sh >> /var/log/cron.log 2>&1
# 防止重复执行
*/5 * * * * flock -n /tmp/script.lock /path/to/script.sh
3.4 at - 一次性任务
at 10:30 # 今天10:30
at now + 1 hour # 1小时后
at now + 30 minutes # 30分钟后
# 查看任务
atq
# 删除任务
atrm <job_id>
四、日志管理
4.1 journalctl - systemd 日志
# 查看所有日志
journalctl
# 查看最近日志
journalctl -n 100 # 最近100行
journalctl --since "1 hour ago"
journalctl --since today
journalctl --since "2025-01-20" --until "2025-01-21"
# 查看特定服务日志
journalctl -u nginx
journalctl -u nginx -f # 实时追踪
# 查看特定优先级
journalctl -p err # 错误级别
journalctl -p warning # 警告级别
# 查看内核日志
journalctl -k
# 查看本次启动日志
journalctl -b
journalctl -b -1 # 上次启动
# 磁盘占用
journalctl --disk-usage
# 清理旧日志
sudo journalctl --vacuum-time=7d # 保留7天
sudo journalctl --vacuum-size=500M # 限制500M
4.2 传统日志文件
# 系统日志
/var/log/syslog # Ubuntu
/var/log/messages # CentOS
# 认证日志
/var/log/auth.log # Ubuntu
/var/log/secure # CentOS
# 内核日志
/var/log/kern.log
dmesg
# 应用日志
/var/log/nginx/access.log
/var/log/nginx/error.log
/var/log/mysql/error.log
4.3 logrotate - 日志轮转
配置文件:/etc/logrotate.d/
# /etc/logrotate.d/myapp
/var/log/myapp/*.log {
daily # 每天轮转
rotate 7 # 保留7份
compress # 压缩旧日志
delaycompress # 延迟一次压缩
missingok # 文件不存在不报错
notifempty # 空文件不轮转
create 644 www-data www-data
postrotate
systemctl reload myapp > /dev/null 2>&1 || true
endscript
}
# 测试配置
sudo logrotate -d /etc/logrotate.d/myapp
# 强制执行
sudo logrotate -f /etc/logrotate.d/myapp
五、性能监控
5.1 free - 内存使用
free
free -h # 人类可读
free -m # MB 单位
free -g # GB 单位
free -s 1 # 每秒刷新
输出解读:
total used free shared buff/cache available
Mem: 15Gi 5.2Gi 2.1Gi 412Mi 8.1Gi 9.5Gi
Swap: 2.0Gi 0B 2.0Gi
total: 总内存used: 已使用(不含 buff/cache)free: 空闲buff/cache: 缓存(可回收)available: 实际可用(free + 可回收的 buff/cache)
5.2 vmstat - 虚拟内存统计
vmstat
vmstat 1 # 每秒刷新
vmstat 1 10 # 每秒刷新,共10次
vmstat -S M # MB 单位
输出解读:
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 0 0 2149760 251136 8316288 0 0 1 8 2 2 1 0 99 0 0
关键指标:
r: 运行队列中的进程数b: 阻塞的进程数si/so: swap in/out(理想为0)bi/bo: 块设备 I/Ous: 用户态 CPUsy: 系统态 CPUid: 空闲 CPUwa: I/O 等待
5.3 iostat - I/O 统计
# 安装
sudo apt install sysstat
iostat
iostat -x # 扩展信息
iostat -x 1 # 每秒刷新
iostat -d # 只显示磁盘
iostat -p sda # 指定设备
关键指标:
%util: 设备繁忙程度(>70% 可能是瓶颈)await: 平均等待时间(ms)r/s,w/s: 每秒读写次数rkB/s,wkB/s: 每秒读写量
5.4 mpstat - CPU 统计
mpstat
mpstat 1 # 每秒刷新
mpstat -P ALL # 每个 CPU
5.5 sar - 系统活动报告
sar 可以收集和报告系统活动信息:
# CPU 使用率
sar -u 1 5 # 每秒采样,共5次
# 内存使用
sar -r 1 5
# 磁盘 I/O
sar -d 1 5
# 网络
sar -n DEV 1 5 # 网络接口
sar -n TCP 1 5 # TCP 统计
# 查看历史数据
sar -f /var/log/sysstat/sa20 # 查看20日的数据
5.6 iotop - I/O 监控
sudo apt install iotop
sudo iotop
sudo iotop -o # 只显示有 I/O 的进程
sudo iotop -P # 显示进程而非线程
5.7 nload/iftop - 网络流量监控
# nload - 带宽监控
sudo apt install nload
nload
nload eth0
# iftop - 连接流量监控
sudo apt install iftop
sudo iftop
sudo iftop -i eth0
六、网络配置
6.1 ip 命令(现代方式)
ip 命令是 ifconfig 的现代替代品:
# 查看网络接口
ip addr # 或 ip a
ip addr show eth0
# 查看路由表
ip route # 或 ip r
# 启用/禁用接口
sudo ip link set eth0 up
sudo ip link set eth0 down
# 配置 IP 地址
sudo ip addr add 192.168.1.100/24 dev eth0
sudo ip addr del 192.168.1.100/24 dev eth0
# 添加路由
sudo ip route add 10.0.0.0/8 via 192.168.1.1
sudo ip route del 10.0.0.0/8
# 添加默认网关
sudo ip route add default via 192.168.1.1
# 查看邻居(ARP)
ip neigh # 或 ip n
# 查看链路信息
ip link # 或 ip l
6.2 ifconfig(传统方式)
ifconfig # 所有接口
ifconfig eth0 # 指定接口
ifconfig eth0 up/down # 启用/禁用
ifconfig eth0 192.168.1.100 netmask 255.255.255.0
6.3 永久网络配置
Ubuntu/Debian (Netplan)
# /etc/netplan/01-netcfg.yaml
network:
version: 2
ethernets:
eth0:
dhcp4: no
addresses:
- 192.168.1.100/24
gateway4: 192.168.1.1
nameservers:
addresses:
- 8.8.8.8
- 8.8.4.4
sudo netplan apply
CentOS/RHEL
# /etc/sysconfig/network-scripts/ifcfg-eth0
TYPE=Ethernet
BOOTPROTO=static
IPADDR=192.168.1.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=8.8.8.8
ONBOOT=yes
sudo systemctl restart network
6.4 DNS 配置
# 查看当前 DNS
cat /etc/resolv.conf
resolvectl status # systemd-resolved
# 临时修改
sudo vim /etc/resolv.conf
nameserver 8.8.8.8
nameserver 8.8.4.4
# 永久修改(systemd-resolved)
sudo vim /etc/systemd/resolved.conf
[Resolve]
DNS=8.8.8.8 8.8.4.4
sudo systemctl restart systemd-resolved
6.5 hostname 配置
# 查看主机名
hostname
hostnamectl
# 临时修改
hostname newhostname
# 永久修改
sudo hostnamectl set-hostname newhostname
# 修改 hosts 文件
sudo vim /etc/hosts
127.0.0.1 localhost
127.0.1.1 newhostname
七、防火墙
7.1 ufw (Ubuntu 推荐)
ufw(Uncomplicated Firewall)是 Ubuntu 默认的防火墙管理工具:
# 启用/禁用
sudo ufw enable
sudo ufw disable
sudo ufw status
sudo ufw status verbose
# 默认策略
sudo ufw default deny incoming
sudo ufw default allow outgoing
# 允许端口
sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 443
sudo ufw allow 22/tcp
sudo ufw allow 3000:3010/tcp # 端口范围
# 允许服务
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
# 允许特定 IP
sudo ufw allow from 192.168.1.100
sudo ufw allow from 192.168.1.0/24
sudo ufw allow from 192.168.1.100 to any port 22
# 拒绝
sudo ufw deny 3306
sudo ufw deny from 10.0.0.0/8
# 删除规则
sudo ufw delete allow 80
sudo ufw status numbered # 显示规则编号
sudo ufw delete 3 # 按编号删除
# 重置
sudo ufw reset
7.2 firewalld (CentOS/RHEL 推荐)
# 启动服务
sudo systemctl start firewalld
sudo systemctl enable firewalld
# 查看状态
sudo firewall-cmd --state
sudo firewall-cmd --list-all
# 添加服务
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
# 添加端口
sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --permanent --add-port=3000-3010/tcp
# 删除规则
sudo firewall-cmd --permanent --remove-port=3000/tcp
# 重新加载
sudo firewall-cmd --reload
# 查看可用服务
sudo firewall-cmd --get-services
# 区域管理
sudo firewall-cmd --get-zones
sudo firewall-cmd --get-default-zone
sudo firewall-cmd --set-default-zone=public
7.3 iptables (底层工具)
iptables 是 Linux 内核防火墙的用户空间工具:
# 查看规则
sudo iptables -L
sudo iptables -L -n -v # 详细信息
# 允许端口
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# 允许已建立的连接
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# 允许本地回环
sudo iptables -A INPUT -i lo -j ACCEPT
# 默认策略
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
# 删除规则
sudo iptables -D INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -L --line-numbers
sudo iptables -D INPUT 3 # 按行号删除
# 清空规则
sudo iptables -F
# 保存规则
sudo iptables-save > /etc/iptables.rules
sudo iptables-restore < /etc/iptables.rules
# Ubuntu 永久保存
sudo apt install iptables-persistent
sudo netfilter-persistent save
八、系统信息
8.1 uname - 系统信息
uname -a # 所有信息
uname -r # 内核版本
uname -m # 架构
8.2 查看发行版信息
cat /etc/os-release
lsb_release -a
cat /etc/issue
8.3 硬件信息
# CPU
lscpu
cat /proc/cpuinfo
nproc # CPU 核数
# 内存
free -h
cat /proc/meminfo
# 磁盘
lsblk
fdisk -l
df -h
# PCI 设备
lspci
# USB 设备
lsusb
# 综合信息
sudo dmidecode
sudo lshw
sudo lshw -short
8.4 uptime - 运行时间
uptime
# 输出:10:30:00 up 7 days, 2:30, 3 users, load average: 0.15, 0.10, 0.05
# load average 解读(1分钟、5分钟、15分钟平均值)
# 对于单核 CPU,1.0 表示满载
# 对于多核 CPU,核数就是满载值
九、文件系统管理
9.1 挂载管理
# 查看挂载
mount
mount | grep sda
findmnt
# 挂载
sudo mount /dev/sdb1 /mnt/data
sudo mount -t ext4 /dev/sdb1 /mnt/data
sudo mount -o ro /dev/sdb1 /mnt/data # 只读
# 卸载
sudo umount /mnt/data
sudo umount -l /mnt/data # 延迟卸载
# 开机自动挂载
# /etc/fstab
# <设备> <挂载点> <类型> <选项> <dump> <fsck>
# /dev/sdb1 /mnt/data ext4 defaults 0 2
# UUID=xxx /mnt/data ext4 defaults 0 2
9.2 swap 管理
# 查看 swap
swapon --show
free -h
# 创建 swap 文件
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# 永久生效
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
# 关闭 swap
sudo swapoff /swapfile
sudo swapoff -a
# 调整 swappiness
cat /proc/sys/vm/swappiness
sudo sysctl vm.swappiness=10
# 永久修改
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
9.3 磁盘配额
# 安装
sudo apt install quota
# 编辑 /etc/fstab,添加 usrquota,grpquota 选项
# 重新挂载
sudo mount -o remount /home
# 创建配额文件
sudo quotacheck -cum /home
sudo quotaon /home
# 设置用户配额
sudo edquota -u username
# 查看配额
quota -u username
repquota -a
十、环境管理
10.1 alternatives - 管理多版本
# 查看 Python 版本
sudo update-alternatives --display python
# 配置 Python 版本
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.8 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.10 2
# 选择版本
sudo update-alternatives --config python
# Java 版本
sudo update-alternatives --config java
10.2 时区管理
# 查看时区
timedatectl
# 列出时区
timedatectl list-timezones
timedatectl list-timezones | grep Asia
# 设置时区
sudo timedatectl set-timezone Asia/Shanghai
# 同步时间
sudo timedatectl set-ntp true
10.3 locale 管理
# 查看当前 locale
locale
# 查看可用 locale
locale -a
# 生成 locale
sudo locale-gen zh_CN.UTF-8
# 设置默认 locale
sudo localectl set-locale LANG=en_US.UTF-8
# 或编辑 /etc/default/locale
LANG=en_US.UTF-8
LC_ALL=en_US.UTF-8
总结
本章介绍了后端开发者每周都可能用到的工具:
- 服务管理:systemctl 是现代 Linux 服务管理的核心
- 归档压缩:tar + gzip 是最常用的组合
- 定时任务:cron 是生产环境定时任务的标准
- 日志管理:journalctl + logrotate 确保日志可控
- 性能监控:free、vmstat、iostat 是排查性能问题的基础
- 网络配置:ip 命令是现代 Linux 网络配置的标准
- 防火墙:ufw 或 firewalld 让防火墙管理更简单
下一章将介绍低频但重要的工具,包括容器、性能分析、安全工具等。