Have your computer email you when an action completes

I can’t imagine doing distributed or large batch work without an easy-to-use script that emails me once a command terminates. Before that, I was just going insane with checking on them all the time to see if my process was done or if an error has occurred, leaving the computer idle. I’ve called it notify (linked here, or pasted at end), and you can use it as a shell script to quickly call with other commands.

I issue it in the terminal like this:
$ python ~/reallylongscript.py; notify
The semicolon separates lines, and as soon as the first statement terminates (whether it terminates with success or with error), the notification script will be called.

You’ll get an email with a body like:

New notification from brunonia.

Where “brunonia” is the name of my computer (this script will determine the computer’s name automatically, which is very helpful when you need to know which of several computers needs attention!).

It’s been really useful for:

  • Running a long action on a remote machine, even if it’s as simple as deleting all the files in a large directory to free up space, so I don’t have to keep checking to see when it’s done.
  • Running a command on several machines over ssh (usually with screen in zombie mode) to let me know if a process fails and needs to be investigated and/or restarted. (The only downside for me so far is that if the filesystem croaks or some similar problem affects all nodes at once, my inbox needs a bit of clean-up work!).

This is where I got the base code from, and they have a few other ideas on how to use it. This strategy can be easily integrated into already-existing scripts to keep you in the loop as they run. I suppose one could also write a shell script using Python’s os.system() method (or similar newer ones) and sys.argv list that takes as parameters commands to run, and sends the email after all commands in sys.argv have finished.

#!/usr/bin/python

import smtplib, platform

me = platform.node()

fromaddr = 'myusername@gmail.com'
toaddrs  = 'myusername@gmail.com'
msg = 'New notification from '+me+'.'  

# Credentials (if needed)
username = 'myusername'
password = 'mypassword'  

# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()