I thought a useful addition to our blog might be a running series of handy scripts. Just for the sake of things (and because I couldn't find a better title), I'm calling the series "David's Handy Scripts". I'll get this show on the road with a quick script I put together to track 2 things that can get you into a mess if they're not monitored - disk usage and bandwidth usage.
There are easier ways to track bandwidth usage (vnstat comes to mind), but where's the fun in that? I'm using iptables to track packets. You can do a lot with iptables and it's really quite simple to track bandwidth by port/protocol if you wanted some granularity.
We need to setup a few rules to record our stats. Execute each of these:
iptables -N output iptables -A OUTPUT -j output iptables -N input iptables -A INPUT -j input
You can pop those 4 commands in /etc/rc.local to make them persistent or integrate them into any existing firewall ruleset you're currently using. After those are in place, you're basically all set. Just edit the top of the following script to indicate when you want to receive alerts. Pop that in a cronjob to run daily and you'll get an alert when those thresholds are exceeded.
#!/bin/bash ##### # script to monitor badnwidth and disk space usage # bandwidth - send alert if usage > X # disk - send alert if used space > Y ##### MAILTO="address@example.com" HOSTNAME=`hostname` #BANDWIDTH THRESHOLD BANDWIDTHLIMIT=42949672960 #40GB (1 GB = 1073741824 bytes) #DISK SPACE THRESHOLD USEDDISKLIMIT=85 #80% ### # BANDWIDTH CHECK #reset counter if it is first of month & create log if it does not exist let DATE=`date +%d` if [ $DATE -eq 0 ] || [ ! -e /root/bandwidth.log ]; then echo "0" > /root/bandwidth.log fi #calculate usage let OLDTOTAL=`cat /root/bandwidth.log` let IN=`iptables -L INPUT -v -x | grep input | awk '{print $2}'` let OUT=`iptables -L OUTPUT -v -x | grep output | awk '{print $2}'` let TOTAL=IN+OUT let NEWTOTAL=OLDTOTAL+$TOTAL #write updated total out to counter log echo $NEWTOTAL > /root/bandwidth.log #check if total exceeds our warning threshold and send alert if it does if [ $NEWTOTAL -gt $BANDWIDTHLIMIT ]; then echo $HOSTNAME "$NEWTOTAL bytes used this month" | mail -s "$HOSTNAME bandwidth warning" $MAILTO fi #clear counters iptables -L INPUT -Z -v > /dev/null iptables -L OUTPUT -Z -v > /dev/null ### # DISK UTILIZATION CHECK #grab disk usage let DISKUSAGE=`df | grep xvda1 | awk '{print $5}' | cut -d'%' -f1` #check if usage exceeds threshold and send alert if it does if [ $DISKUSAGE -gt $USEDDISKLIMIT ]; then echo $HOSTNAME "current disk usage - $DISKUSAGE%" | mail -s "$HOSTNAME disk usage warning" $MAILTO fi exit 0

How do I pop them in a cron job?
Um, don't worry. I found this tut:
https://help.ubuntu.com/community/CronHowto