Automation script to defrag a Windows machine. The defrag results will be emailed to specified email address. This script can also handle running defrag over multiple volumes. NOTE: if you are running this on Windows 2003 64-bit you have to place a copy of defrag.exe in the same directory as the python script. Otherwise Windows will barf and say it doesn't know what defrag is. Don't know why this happens.
import smtplib, sys, MimeWriter, StringIO, base64, os, time
drives = ["C:","D:","E:"]
SMTP_server = "somemailserver.com"
email_to = "someone@example.com"
email_from = "someone2@example.com"
logfile_path = "c:/"
def mail(serverURL=None, sender='', to='', subject='', text=''):
message = StringIO.StringIO()
writer = MimeWriter.MimeWriter(message)
writer.addheader('Subject', subject)
writer.startmultipartbody('mixed')
part = writer.nextpart()
body = part.startbody('text/plain')
body.write(text)
part = writer.nextpart()
part.addheader('Content-Transfer-Encoding', 'base64')
body = part.startbody('text/plain')
base64.encode(open(filename, 'rb'), body)
writer.lastpart()
smtp = smtplib.SMTP(serverURL)
smtp.sendmail(sender, to, message.getvalue())
smtp.quit()
def timestamp():
mytime = time.strftime("%Y%m%d", time.localtime())
return mytime
hs = os.popen('hostname')
computer_name = hs.read()
hs.close()
mytime = timestamp()
filename = logfile_path + "DEFRAG" + mytime + ".log"
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 = raw_input('\nPress ENTER to exit')