Another useful python script

Today I was helping a colleague debug a program and I found myself doing the same thing over and over. I would download the log from the server, zip the file and then e-mail the zipped file to him. The second time doing this I decided this is too much work so I wrote a little python program to do all the steps. Here's how it's run:

sendFile.py --mailto "Bob Jones" --comment "Here's the log you wanted" testserver:/aplic/jboss/server/default/log/server.log
It gets the file via scp (10 lines), zips it up (another 10 lines), mails it (11 lines using a helper class). and then cleans up the temporary files (3 lines).

Here's the code minus the stuff for talking to outlook (via win32com).

#!/usr/bin/env python

from subprocess import call
import os
import zipfile
import OutlookMail

class SendFile:
def __init__(self, dbInfo):
self.tempfilename = None
self.zippedfile = None

def getFile(self, filename):
fname = os.path.basename(filename)
outname = os.path.join('/temp/', fname)
args = ['scp', filename, outname]
print ' '.join(args)
if 0 != call(args):
print "Problem getting file '%s'" % (filename)

self.tempfilename = outname
return self.tempfilename

def zipFile(self, filename = None):
if filename == None:
filename = self.tempfilename

zippedfile = filename + ".zip"
zf = zipfile.ZipFile(zippedfile, 'w', zipfile.ZIP_DEFLATED)
zf.write(filename, os.path.basename(filename), zipfile.ZIP_DEFLATED)
zf.close()

self.zippedfile = zippedfile
return self.zippedfile

def mailTo(self, mailto, strComment = None, zipfilename = None):
if zipfilename == None:
zipfilename = self.zippedfile

print "Mailing %s to %s" % (zipfilename , options.strMailTo)

if strComment == None:
strComment = 'Em anexo'

shortzipfilename = os.path.basename(zipfilename)
OutlookMail.sendToOutlook(strTos=options.strMailTo, strSubject=shortzipfilename, strBody=strComment, files = [zipfilename])

def cleanup(self):
os.remove(self.tempfilename)
os.remove(self.zippedfile)

if __name__ == "__main__":
import optparse

parser = optparse.OptionParser()
parser.add_option("", "--mail", "--mailto", dest="strMailTo", default=None,
help="Who to send mail to")
parser.add_option("-c", "--comment", dest="strComment", default=None,
help = "Some info on the file")
(options, args) = parser.parse_args()

sf = SendFile(options.strMailTo)
sf.getFile(args[0])
sf.zipFile()
sf.mailTo(options.strMailTo, options.strComment)
sf.cleanup()

It's missing the ability to set the subject and to send multiple files, and maybe it should have some intelligence not to zip file which are already small or already compressed, but it's usable. Taking a 15 minute break to make a little utility like this is a lot more fun repeating the same boring button clicks over and over again.

Comments

Popular posts from this blog

Shortest Sudoku solver in Python

Seven Segment Display in Inkscape

Dot to Png