编辑 2021 关于MacOS
不要使用截图进行监控!
位图图形截图需要处理很多字节,压缩它们等等,用它们来监控是一个不太好的想法!
即使您阅读包含屏幕截图的邮件,您也无法直接从邮件中读取值...(再次使用具有大量资源的 OCR 工具)...
关于top语法
在批处理模式下运行top仅一个镜头语法是:
top -bn 1
在 MacOS 下,你会运行:
top -l 1
有关更多信息,请随时在您的控制台中点击man top,然后点击 rtfm!
当cpu负载变高时通过邮件发送top
这个小脚本将通过邮件发送top 结果,如果CPU 负载超过70%,使用bash。这可以由crontab 运行,例如...
#!/bin/bash
{
declare -a out=()
read; out+=("$REPLY")
read; out+=("$REPLY")
read; out+=("$REPLY")
read foo user foo system foo <<<"$REPLY"
((tot=(${user//.}+${system//.}),tot>700))&& {
tot=000$tot
printf -v pct "%.1f\n" ${tot:0:${#tot}-1}.${tot:${#tot}-1}
(
printf "%s\n" "${out[@]}"
cat
) |
mail -s "$HOSTNAME's CPU load: $pct tot, $user us, $system sy!" user@host
}
} < <(top -bn1);
这将读取并存储top 命令的前 3 行,计算 user 和 system 百分比的总和,然后如果该总和大于 70 %,为邮件主题渲染$pct,然后在STDIN上使用cat发送3个存储的行和top命令的其余部分。
...(语法${user//.} 将删除点,然后乘以top 命令的10 输出)...
Mac 版本:
#!/bin/bash
{
declare -a out=()
for i in {1..4} ;do
read; out+=("$REPLY")
done
read foo{,} user foo system foo <<<"${REPLY//%}"
printf -v user %.2f $user
printf -v system %.2f $system
((tot=(${user//.}+${system//.}),tot>7000))&& {
tot=000$tot
printf -v pct "%.2f\n" ${tot:0:${#tot}-2}.${tot:${#tot}-2}
(
printf "%s\n" "${out[@]}"
cat
) |
mail -s "$HOSTNAME's CPU load: $pct tot, $user us, $system sy!" user@host
}
} < <(top -l1);
存储空间已满时发送邮件
#!/bin/bash
{
read headline
declare -a over=()
while read;do
read filesys size use avail pct mpnt <<<"$REPLY"
((${pct%%%}>70)) && over+=("$REPLY")
done
((${#over[@]}>0))&&{
printf "%s\n" "$headline" "${over[@]}" |
mail -s "$HOSTNAME: ${#over[@]} disks over limit!" user@host
}
} < <(LANG=C df -h / )
这将发送一封主题为:“MyHost: N disks over limit!” 的邮件,其中N 作为磁盘数,内容输出为df -h,仅用于@987654342 @ 磁盘。
这个脚本在 MacOS 下测试过,看起来也很好用!
为了防止打印出无用的值,您必须将要调查的设备列为df 参数:
...
} < <(LANG=C df -h / /usr /home /etc )