Got a little idea to write this up after seeing a question over on Photo Matt. He asked about having a script that could take commands sent by email and execute them remotely, then return the results via email.
So I decided to hack something up in Python, and give it a try. Read the rest of the post to see how I did it.
Or you can cheat and just look at the script itself. Click Here for the script.
First off, you will need access to the *nix server. Probably root access.
This method uses a standard python script, and the sendmail smrsh facility.
You will want to start by making sure sendmail has smrsh support included.
You can tell if it does by looking at /etc/mail/sendmail.mc and looking for a line –FEATURE(`smrsh’,`/usr/sbin/smrsh’)
If you get that far, you are in good shape.
Onto configuring smrsh:
- Create a new user account that will recieve the email. Ex: adduser my_secret_user
- Then edit /etc/aliases and add a line like:
- Then run the newaliases command
- Now, all you need to do is create the script. You will need it to be named whatever you called it when adding the line to the /etc/aliases file, and it needs to be in the /etc/smrsh directory. The example script below is the one I wrote in python. You can copy the script, and alter it for your needs. And if any python zealots see this, I know it is not well formed, and could be written much better.
#!/usr/local/bin/python # Change the fromaddr and toaddr values below, # and change path to python above import sys,os,re,string,smtplib #who the response comes from fromaddr = 'secret@localhost' #who to send the email to toaddr = 'firstname.lastname@example.org' input = sys.stdin mail = input.readlines() for x in mail: # is string to denote start of command. # change it below to suit your needs. if re.search('*cmd*',x): cmd = string.replace(x,'*cmd*','') cmd = string.strip(cmd) cmd_in,cmd_out = os.popen4(cmd) msg = 'Subject: Output from " + cmd + '\r\n' msg = msg + cmd_out.read() #Optional-- this will send email to whoever sent the original, # un-comment out next 7 lines --otherwise, this will #only send emails to address configured above # if re.search('From:',x): # if re.search('@',x): # who = string.split(x,' ') # toaddr = who # toaddr = string.replace(x,'< ','') # toaddr = string.replace(x,'>','') #send email if msg: server = smtplib.SMTP('localhost') server.sendmail(fromaddr,toaddr,msg) server.quit()
Caveats: This is probably not safe to do. Make sure the email address is obscure enough, so it could not be guessed.
Also, this will run any command the exec’ing user has rights to. So if the script is owned by root, you can do some damage.
Use caution, and don’t say I didn’t warn you.