This little script notifies me by email when a system restarts, I use it on a couple of machines with different email content to tell me which system has restarted.
It relies upon having the packages sendemail and dnsutils installed and also uses wget which is usually installed by default with most distributions
#!/bin/bash a=0 b=0 thetime=`date '+%D @ %T'` $(exit 1) while [ $? != 0 ] do sleep 5 ((a++)) wget -q -O /home/dai/googletest.txt --tries=10 --timeout=20 http://google.com done rm /home/dai/googletest.txt myip=`dig +short myip.opendns.com @resolver2.opendns.com` $(exit 1) while [ $? != 0 ] do if [ $b == 0 ]; then : else sleep 30 fi ((b++)) sendemail -f email@example.com -t firstname.lastname@example.org -u "This system has Started" -m "This script was started on $thetime \n i am currently on $myip \n I have made $a attempts to get ip address \n and $b attempts to send this email.\n The time now is `date '+%D @ %T'`" -s smtp.gmail.com:587 -o tls=yes -xu email@example.com -xp email1accountpassword done
I start with the shebang, and then set two variables to 0. Next I put the current time into another variable (thetime).
The next section creates a loop that runs until it completes successfully, this is to ensure I have a connection to the internet, otherwise I cannot send an email and the script would be futile. Once this is complete I remove the temporary file that is saved
Once I am sure I have a gateway I use the dig command to retrieve my ip address from opendns and save it to another variable (myip).
Next is another loop that once again runs until it gets a successful result, upon failure it will wait 30 seconds and then try again.
The sendemail command creates the email I want to send to myself and gives some information that I might want to know, that is the ip address the machine is currently on, the time of reboot, how many attempts it took to get both the ip address and to send the email and the time the email was finally sent.
I have found this useful to alert me to the system either coming back online after being rebooted by somebody else, or after a power failure (if the BIOS is set to start immediately) and I sometimes want to log in to the system to check everything is up and running correctly so I need to have the IP address.
I usually have this script in cron and the entry looks like this:
The biggest downside to this script is having the email password available in clear text, I am sure there are better ways to accomplish this but I created a separate email account that I only use for machine sent mails so I can always change it easily, and I did write this script some years ago now and it has become one of my most regularly used ones.