Simple Bash Script To Email Server Status

I didn’t want to constantly have to log into my servers in order to check on key performance indicators so I decided to write a simple script that would do the checking for me. After collecting results, the script emails them to me.

There are a few tools called within the script you might need to install. I also convert any tabs into spaces in order to make sure things line up nicely inside my email.

#!/bin/bash

SERVER="myserver001"
TOEMAIL="admin@myservers.com"
FROMEMAIL="myserver001@myserverscom"
# Who is logged in and what are they up to
WHO=`w`
# Hows my processor doing
MPSTAT=`mpstat`
# Hows my virtual memory doing
VMSTAT=`vmstat`
# Top 10 memory consumers
PS_MEM=`ps -A -o pid,pcpu,pmem,start_time,state,time,comm | perl -e '($_ = join "",<>) =~ s/(\t)/     /g; print;' |sort -g -k 3 -r | head -10`
# Top 10 cpu consumers
PS_CPU=`ps -A -o pid,pcpu,pmem,start_time,state,time,comm | perl -e '($_ = join "",<>) =~ s/(\t)/     /g; print;' | sort -g -k 2 -r | head -10`
#  Memory usage in MB
FREE=`free -m`
# Procinfo
PROCINFO=`procinfo`
# IPTables status
IPTABLES=`iptables -nL`
# Established connections
NETSTAT=`netstat -na |grep -i esta |grep -v 127.0.0.1 |sort -n -t. -k2`
# Filesystem space
FILESYSTEM=`df -h`
# Line divider
DL="~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
# Put the email together
BODY="${DL}
`date`
${DL}
${SERVER}
${DL}
${WHO}
${DL}
${FREE}
${DL}
${MPSTAT}
${DL}
${VMSTAT}
${DL}
${PROCINFO}
${DL}
Top 10 CPU processes
${PS_CPU}
${DL}
Top 10 Memory processes
${PS_MEM}
${DL}
${IPTABLES}
${DL}
${NETSTAT}
${DL}
${FILESYSTEM}
${DL}
"

echo "${BODY}" | perl -e '($_ = join "",<>) =~ s/(\t)/     /g; print;' | sendEmail -f "${FROMEMAIL}" -u "${SERVER} Status Update" -t ${TOEMAIL}

Adding the script to cron, I now get a daily update on how my server is doing.

One thought on “Simple Bash Script To Email Server Status

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>