Wednesday, August 15, 2007

Shell Script: 每日檢查硬碟的使用量,當到達90%時寄出Alert mail給root

1. 至/root/bin目錄下,新增一shell script的檔案,名為diskspace.sh,內容如下:
#!/bin/bash
df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge 90 ]; then
echo "Running out of space "$partition $usep%" on $(hostname) as on $(date)" | mail -s "Alert: Almost out of disk space $usep%" root
fi
done

2. # chmod 755 diskspace.sh

3. # crontab -e
-> 10 5 * * * /root/bin/diskspace.sh

這個範例用了grep,awk與cut指令來實作,可以見得它們有多好用了 :)

參考來源: http://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html

No comments: