<Previous | Next>

Run Scripts by Email or SMS

Posted by Tom on the 25th of January, 2012, at 7:15 am.

  1. Put a few prepared script or executables in /home/tsbertalan/bin/emailclibin/ and chmod +x them.
  2. Make a new gmail account with cli_inbox and cli_archive IMAP folders, and a new filter that puts messages from your approved senders (say, number@vtext.com, for Verizon phones) in that cli_inbox folder.
  3. Run python emailcli.py with nohup or screen or something.
  4. Text the name of one of your prepared scripts to EMAIL@gmail.com

I can already see certain, possibly quite atrocious security holes here, but this could be fun when combined with, say, an Arduino that's interfaced with a coffeemaker or garage door.

#!/usr/bin/env python
# This file should be called emailcli.py (or something like that).

''' emailcli.py : Scan mailbox for cli messages, and then execute specific bound commands.
'''
import os, sys, imaplib, rfc822, re, StringIO

server  ='imap.gmail.com'
username='EMAIL@gmail.com'
password='PASSWORD'

def connect(email,password):
    imap = imaplib.IMAP4_SSL("imap.gmail.com")
    imap.login(email, password)
    return imap

def disconnect(imap):
    imap.logout()

pattern_uid = re.compile('\d+ \(UID (?P\d+)\)')
def parse_uid(data):
    match = pattern_uid.match(data)
    return match.group('uid')

imap = connect(username,password)
print "Listening for approved commands at %s..." % username
while True:
    imap.select("cli_inbox")
    resp, items = imap.search(None, 'ALL')
    email_ids  = items[0].split()
    for num in email_ids:
        resp, data = imap.fetch(num, "(UID)")
        typ, msg_data = imap.fetch(num, '(uid BODY[TEXT])')
        try:
            msg_uid = parse_uid(data[0])
            message = msg_data[0][1]
            result = imap.uid('COPY', msg_uid, 'cli_archive')
            if result[0] == 'OK':
                mov, data = imap.uid('STORE', msg_uid , '+FLAGS', '(\Deleted)')
                imap.expunge()
            command = message.rstrip().lstrip()
            print "%s$ %s" % (os.getcwd(), command)
            binpath = "/home/tsbertalan/bin/emailclibin/"
            dirlist = os.listdir(binpath)
            shortcommand = command.split()[0].rstrip()
            if shortcommand in dirlist:
                system_command = "~/bin/emailclibin/"
                system_command += command
                movit = os.system('cd ~/')
                result=os.system(system_command).rstrip().lstrip()
            else:
                print "Command '%s' is not on the pre-approved list." % command
        except:
            done = 1;

Tom's Picasa Web Albums

Bookmark and Share