#*****************************************************************# # # # Filename: autodefrag.py # # Date Written: 4/27/2007 # # # # Purpose: Intelligent interface to Windows defrag # # command. Emails results when complete. # # Can handle multiple volumes. Add this # # script to Windows task scheduler to # # fully automate defragmentation. # # # # OS: Windows 2003, XP # # # #*****************************************************************# import smtplib, sys, MimeWriter, StringIO, base64, os, time ##VARIABLES######################################################## drives = ["C:","D:","E:"] # list of volumes to defragment SMTP_server = "somemailserver.com" #SMTP email server email_to = "someone@example.com" email_from = "someone2@example.com" logfile_path = "c:/" #path to where logfile is saved ##END_VARIABLES#################################################### def mail(serverURL=None, sender='', to='', subject='', text=''): message = StringIO.StringIO() writer = MimeWriter.MimeWriter(message) writer.addheader('Subject', subject) writer.startmultipartbody('mixed') # start off with a text/plain part part = writer.nextpart() body = part.startbody('text/plain') body.write(text) # now add an attachment part = writer.nextpart() part.addheader('Content-Transfer-Encoding', 'base64') body = part.startbody('text/plain') base64.encode(open(filename, 'rb'), body) # finish off writer.lastpart() # send the mail smtp = smtplib.SMTP(serverURL) smtp.sendmail(sender, to, message.getvalue()) smtp.quit() def timestamp(): #mytime = time.asctime(time.localtime()) mytime = time.strftime("%Y%m%d", time.localtime()) return mytime ##MAIN############################################################# #get the host name hs = os.popen('hostname') computer_name = hs.read() hs.close() mytime = timestamp() filename = logfile_path + "DEFRAG" + mytime + ".log" #execute the defrag command for each drive for d in drives: cmd = "defrag.exe -v " + d + " >>" + filename print "Starting defragment: ", cmd errorlevel = os.system(cmd) if errorlevel == 0: print "Emailing results" mail(SMTP_server,email_from,email_to,'Disk Defrag of ' + computer_name + ' Complete','Disk defragmentation finished\n') else: print "Error occurred! Emailing results" mail(SMTP_server,email_from,email_to,'Disk Defrag of ' + computer_name + ' Error','Disk defragmentation encountered an error') #hold the cmd window open if error occurred - remove this if you want window to exit hold = raw_input('\nPress ENTER to exit')
You need to create an account or log in to post comments to this site.