近來常有朋友問起伺服器監控的問題:除了 Cacti、Nagios 這類開源方案,能不能自己寫 Shell 腳本來做監控?答案是肯定的。依照自身需求量身打造的腳本,往往更能貼合實際情境,把主機監控做得更細緻、更全面。以下分享幾個我常用的監控腳本,各位可依實際環境調整使用。
#!/bin/bash
#network
while : ; do
time='date +%m"-"%d" "%k":"%M'
rx_before='ifconfig eth0|sed -n "8"p|awk '{print $2}'|cut -c7-'
tx_before='ifconfig eth0|sed -n "8"p|awk '{print $6}'|cut -c7-'
sleep 2
rx_after='ifconfig eth0|sed -n "8"p|awk '{print $2}'|cut -c7-'
tx_after='ifconfig eth0|sed -n "8"p|awk '{print $6}'|cut -c7-'
rx_result=$[(rx_after-rx_before)/256]
tx_result=$[(tx_after-tx_before)/256]
echo "$time Now_In_Speed: "$rx_result"kbps Now_Out_Speed: "$tx_result"kbps"
sleep 2
done
#!/bin/sh
#systemstat.sh
IP=192.168.1.227
top -n 2| grep "Cpu" 》./temp/cpu.txt
free -m | grep "Mem" 》 ./temp/mem.txt
df -k | grep "sda1" 》 ./temp/drive_sda1.txt
df -k | grep "/mnt/storage_0" 》 ./temp/mnt_storage_0.txt
time=`date +%m"."%d" "%k":"%M`
connect=`netstat -na | grep "219.238.148.30:80" | wc -l`
echo "$time $connect" 》 ./temp/connect_count.txt
#!/bin/bash
#monitor available disk space
SPACE='df | sed -n '/ \ / $ / p' | gawk '{print $5}' | sed 's/%//'
if [ $SPACE -ge 90 ]
then
fty89@163.com
fi
#!/bin/bash
#script to capture system statistics
OUTFILE=/home/xu/capstats.csv
DATE='date +%m/%d/%Y'
TIME='date +%k:%m:%s'
TIMEOUT='uptime'
VMOUT='vmstat 1 2'
USERS='echo $TIMEOUT | gawk '{print $4}' '
LOAD='echo $TIMEOUT | gawk '{print $9}' | sed "s/,//' '
FREE='echo $VMOUT | sed -n '/[0-9]/p' | sed -n '2p' | gawk '{print $4} ' '
IDLE='echo $VMOUT | sed -n '/[0-9]/p' | sed -n '2p' |gawk '{print $15}' '
echo "$DATE,$TIME,$USERS,$LOAD,$FREE,$IDLE" 》 $OUTFILE
#!/bin/bash
# check_host.sh
# 0 * * * * /home/check_host.sh
DAT="`date +%Y%m%d`"
HOUR="`date +%H`"
DIR="/home/oslog/host_${DAT}/${HOUR}"
DELAY=60
COUNT=60
if ! test -d ${DIR}
then
/bin/mkdir -p ${DIR}
fi
export TERM=linux
/usr/bin/top -b -d ${DELAY} -n ${COUNT} > ${DIR}/top_${DAT}.log 2>&1 &
/usr/bin/sar -u ${DELAY} ${COUNT} > ${DIR}/cpu_${DAT}.log 2>&1 &
/usr/bin/vmstat ${DELAY} ${COUNT} > ${DIR}/vmstat_${DAT}.log 2>&1 &
/usr/bin/iostat ${DELAY} ${COUNT} > ${DIR}/iostat_${DAT}.log 2>&1 &
/usr/bin/sar -n DEV ${DELAY} ${COUNT} > ${DIR}/net_${DAT}.log 2>&1 &
將它放進 crontab 每小時自動執行:
0 * * * * /home/check_host.sh
如此一來,便會在 /home/oslog/host_yyyymmdd/hh 目錄下,按小時生成 CPU、記憶體、網路與 IO 的統計資料。一旦某個時段出問題,就能回頭翻查對應的日誌,還原當時的主機效能狀況。