本文完整阅读约需 11 分钟,如时间较长请考虑收藏后慢慢阅读~

监控在日常运维中非常重要,有助于提前发现问题,并及时进行系统优化。通常我们会使用第三方工具来对系统进行监控,但在个别场景下(例如Gravitational Teleport等工具所提供的动态label,可以自动执行Shell命令)使用Shell会更加灵活,只可惜相关资料太少,且大量谬误。本文将整理使用Shell Script输出CPU、内存、磁盘占用百分比的命令,方便读者查阅与使用。

输出CPU占用百分比

对于安装了sysstat工具的服务器

mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
$ 0.37%
mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 - $12}' | tr -s "n" | awk '{print $1 "%"}'
$ 0.44%

对于未安装sysstat工具的服务器

echo $(echo "$(ps -A -o pcpu | tail -n+2 | paste -sd+ | bc)/$(cat /proc/cpuinfo | grep processor | wc -l)" | bc -l | awk '{printf "%.2f", $1}')%
$ 47.22%
grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {printf "%.2f%", usage}'
$ 23.41%
cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{printf "%.2f%\n", ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'
$ 3.23%
top -bn2 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | paste -sd+ | bc | awk '{print 100 - $1/2}' | awk '{printf "%.2f%", $1}'
$ 23.13%

输出内存占用

使用free命令

CentOS 6

echo `free -m | grep 'buffers/cache' | awk '{print $3}'`/`free -m | grep 'Mem' | awk '{print $2}'`MB
$ 7651/32057MB
echo `free -m | grep 'buffers/cache' | awk '{print $3}'` `free -m | grep 'Mem' | awk '{print $2}'` | awk '{printf "%.2f%", $1*100/$2}'

CentOS 7

echo `free -m | grep 'Mem' | awk '{print $3}'`/`free -m | grep 'Mem' | awk '{print $2}'`MB
$ 2341/4022MB
echo `free -m | grep 'Mem' | awk '{print $3}'` `free -m | grep 'Mem' | awk '{print $2}'` | awk '{printf "%.2f%", $1*100/$2}'
$ 55.31%

各发行版free命令与输出格式各有不同,具体需要依照你所使用的发行版来修改

输出磁盘占用

输出每个磁盘占用

df -l | grep "^/dev" | awk '{printf "%-20s (%.2f/%.2fG)\n", $6, $3/1024/1024, $2/1024/1024}'
$ /                    (1.76/34.98G)
  /boot                (0.17/0.99G)
df -l | grep "^/dev" | awk '{printf "%-20s %.2f%\n", $6, $3*100/$2}'
$ /                    5.04%
  /boot                17.28%

输出总磁盘占用

echo $(df -l | grep "^/dev" | awk '{print $3}' | paste -sd+ | bc) $(df -l | grep "^/dev" | awk '{print $2}' | paste -sd+ | bc) | awk '{printf "%.2f/%.2fG", $1/1024/1024, $2/1024/1024}'
$ 1.93/35.97G
echo $(df -l | grep "^/dev" | awk '{print $3}' | paste -sd+ | bc) $(df -l | grep "^/dev" | awk '{print $2}' | paste -sd+ | bc) | awk '{printf "%.2f%", $1*100/$2}'
$ 5.38%

输出每个磁盘吞吐率

iostat -m -x -d | grep -v "^dm" | grep -v '^$' | awk 'NR > 1 {printf "%-15s %-8s %-8s %-8s %-8s\n", $1, $4, $5, $6, $7}'