DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Automate Defrag Of Windows Host Via Python

04.27.2007
| 5164 views |
  • submit to reddit
        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.

#*****************************************************************#
#                                                                 #
# 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')