Description:
This script files deletes temp files,internet temp files ,disk clean up ,fix disk error and smart failure test.
smart failure test doesn't work on virtual machine
Note:
Run as Local system user
import os
from subprocess import PIPE,Popen
import re
import shutil
import sys
import time
import ctypes
########################################Packages##############################################
start=time.time()
def permissions(dirpath):
mode=0o777
if os.path.isdir(dirpath):
try:
for root,dirs,files in os.walk(dirpath,topdown=False):
for dircs in [os.path.join(root,d) for d in dirs]:
os.chmod(dircs,mode)
for s_file in [os.path.join(root,f) for f in files]:
os.chmod(s_file,mode)
except Exception as E:
print "File being Used %s"%E
def delete(src):
try:
if os.path.exists(src):
if os.path.isdir(src):
shutil.rmtree(src)
elif os.path.isfile(src):
os.remove(src)
else:
print '\t*)',"Error in the Source path"
except:
pass
def oscmd(command):
class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)
with disable_file_system_redirection():
obj = os.popen(command).read()
return obj.strip()
########################################Funtions##############################################
process=Popen('wmic logicaldisk get size,freespace,caption',stdout=PIPE,stderr=PIPE)
res,err=process.communicate()
harddisk=re.findall("C:.+",res)[0].split()
caption=harddisk[0]
freespace=int(harddisk[1])
#totalspace=int(harddisk[2])
try :
print "Removing Users Temp Files"
users=os.popen("net user").read().split()[5:-5]
fil_users=[i for i in users if i!='Guest' and i!='DefaultAccount']
fil_user_temp_path=["C:\\Users\\"+i+"\\AppData\\Local\\Temp" for i in fil_users ]
for i in fil_user_temp_path:
if os.path.exists(i):
print "Providing permission %s "%i
permissions(i)
print "Cleaning %s"%i
shutil.rmtree(i,ignore_errors=True)
else:
pass
print "Provinding Permission C:\Windows\Temp"
permissions("C:\Windows\Temp")
print("Cleaning C:\Windows\Temp")
shutil.rmtree("C:\Windows\Temp",ignore_errors=True)
print "Cleared Temp Files\n"
##############################################################################################################
print "Removing Internet Temp Files"
print "Chrome"
for i in fil_users:
chrome_path="C:\\Users\\"+i+"\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cache"
if os.path.exists(chrome_path):
print 'clearing files on the "%s" folder started:\n'%chrome_path
f3=os.listdir(chrome_path)
if f3:
for i1 in f3:
delete(os.path.join(chrome_path,i1))
print "%s Cleared successfully"%chrome_path
else:
print 'No files found in the "%s"'%chrome_path
chrome_code_cache_path="C:\\Users\\"+i+"\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cache\\js"
print chrome_code_cache_path
if os.path.exists(chrome_code_cache_path):
print 'clearing files on the "%s" folder started:\n'%chrome_code_cache_path
f3=os.listdir(chrome_code_cache_path)
if f3:
for i1 in f3:
delete(os.path.join(chrome_code_cache_path,i1))
print "%s Cleared successfully"%chrome_code_cache_path
else:
print 'No files found in the "%s"'%chrome_code_cache_path
print "Opera"
for i in fil_users:
opera_path="C:\\Users\\"+i+"\\AppData\\Local\\Opera Software\\Opera Stable\\Cache"
if os.path.exists(opera_path):
print 'clearing files on the "%s" folder started:\n'%opera_path
f3=os.listdir(opera_path)
if f3:
for i1 in f3:
delete(os.path.join(opera_path,i1))
print "%s Cleared successfully"%opera_path
else:
print 'No files found in the "%s"'%opera_path
print "Firefox"
for i in fil_users:
fox_path="C:\\Users\\"+i+"\\AppData\\Local\\Mozilla\\Firefox\\Profiles"
if os.path.exists(fox_path):
print 'clearing files on the "%s" folder started:'%fox_path
f4=os.listdir(fox_path)
if f4:
for i2 in f4:
delete(os.path.join(fox_path,i2))
print "%s Cleared successfully"%fox_path
else:
print 'No files found in the "%s" \n'%fox_path
print "IE"
for i in fil_users:
ie_path="C:\\Users\\"+i+"\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files\\Low"
if os.path.exists(ie_path):
print 'clearing files on the "%s" folder started:\n'%ie_path
f5=os.listdir(ie_path)
if f5:
for i3 in f5:
delete(os.path.join(ie_path,i3))
print "%s Cleared successfully"%ie_path
else:
print 'No files found in the "%s"'%ie_path
print "Edge"
for i in fil_users:
ie_path="C:\\Users\\"+i+"\\AppData\\Local\\Packages\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\\AC\\MicrosoftEdge\\Cache"
if os.path.exists(ie_path):
print 'clearing files on the "%s" folder started:\n'%ie_path
f5=os.listdir(ie_path)
if f5:
for i3 in f5:
delete(os.path.join(ie_path,i3))
print "%s Cleared successfully"%ie_path
else:
print 'No files found in the "%s"'%ie_path
############################################################################################################
print "DNS reset"
out=os.popen('ipconfig /flushdns').read()
print out
############################################################################################################
result=''
detected_drives=oscmd('wmic logicaldisk get name')
required_drive_letters=[i.strip() for i in detected_drives.split('\n') if i.strip()][1:]
os_drive=os.environ['SYSTEMDRIVE']
required_drive_letters.remove(os_drive)
if required_drive_letters:
for i in required_drive_letters:
other_drive_fix=oscmd('chkdsk %s /f'%i)
trimed_other_drive_fix=''
if other_drive_fix:
for a in other_drive_fix.split('\r'):
if 'progress' not in a.lower() and 'percent' not in a.lower():
if a.strip():
trimed_other_drive_fix+=a
result+='%s\n%s\n%s\n\n'%('Result of [%s] Drive: '%i, '.'*30, trimed_other_drive_fix)
osdrive_fix=oscmd('echo yes | chkdsk %s /f'%os_drive)
trimed_osdrive_fix=''
for a in osdrive_fix.split('\r'):
if 'progress' not in a.lower() and 'percent' not in a.lower():
if a.strip():
trimed_osdrive_fix+=a
result+='%s\n%s\n%s'%('Result of [%s] Drive: '%os_drive, '.'*30, osdrive_fix)
print result
######################################################################################################
print "Disk Clean up"
import getpass
temp=os.environ['PROGRAMDATA']+r'\c1_temp'
if not os.path.exists(temp):
os.makedirs(temp)
if 'PROGRAMW6432' in os.environ.keys():
path=r'C:\Program Files (x86)\Wise\Wise Disk Cleaner'
URL=r'http://downloads.wisecleaner.com/soft/WDCFree.exe'
else:
path=r'C:\Program Files\Wise\Wise Disk Cleaner'
URL=r'http://downloads.wisecleaner.com/soft/WDCFree.exe'
FileName=r'WiseDiskCleaner'
Extension=r'.exe'
SilentCommand='/VERYSILENT'
arch=os.environ['PROCESSOR_ARCHITECTURE']
print "Deploying " +FileName+ " begins"
def Download(path, URL, FileName, Extension):
import urllib2
import os
print "Download started"
fn = FileName+Extension
fp = os.path.join(path, fn)
req = urllib2.Request(URL, headers={'User-Agent' : "Magic Browser"})
con = urllib2.urlopen(req)
with open(fp, 'wb') as f:
while True:
chunk=con.read(100*1000*1000)
if chunk:
f.write(chunk)
else:
break
return fp
print "Download Completed"
def ExecuteCMD(CMD, OUT = False):
import ctypes
class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)
from subprocess import PIPE, Popen
with disable_file_system_redirection():
OBJ = Popen(CMD, shell = True, stdout = PIPE, stderr = PIPE)
out, err = OBJ.communicate()
RET = OBJ.returncode
if RET == 0:
if OUT == True:
if out != '':
return True
else:
return True
else:
return True
return False
def Install(fb, SilentCommand):
if (ExecuteCMD('"'+fb+'" '+SilentCommand,True)):
print FileName+ " Installed sucessfully in the system "
if os.path.exists(r'C:\Program Files\Wise\Wise Disk Cleaner\WiseDiskCleaner.exe'):
return r'C:\Program Files\Wise\Wise Disk Cleaner\WiseDiskCleaner.exe'
else:
return r'C:\Program Files\Wise\Wise Disk Cleaner\WiseDiskCleaner.exe'
else:
print FileName+' not installed properly. Please try again'
sys.exit()
def get_path():
if 'PROGRAMW6432' in os.environ.keys():
return r'C:\Program Files (x86)\Wise\Wise Disk Cleaner'
else:
return r'C:\Program Files\Wise\Wise Disk Cleaner'
def un_path():
if 'PROGRAMW6432' in os.environ.keys():
return r'C:\Program Files (x86)'
else:
return r'C:\Program Files'
def Clean(path):
s=get_path()
os.chdir(s)
a=os.popen('WiseDiskCleaner.exe -a -adv').read()
def uninstall(path):
if arch == 'AMD64':
rem_reg_1=os.popen('reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Wise Disk Cleaner_is1" /f').read()
print rem_reg_1
else:
rem_reg=os.popen('reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Wise Disk Cleaner_is1" /f').read()
print rem_reg
rem=os.popen(r"C:\Program Files\Wise\Wise Disk Cleaner\unins000.exe /SILENT").read()
print rem
print 'wise disk cleaner uninstalled'
fn = FileName+Extension
fp = os.path.join(path, fn)
a=un_path()
os.chdir(a)
if a == r'C:\Program Files' :
os.chdir(r'C:\Program Files')
shutil.rmtree(r'C:\Program Files\Wise')
shutil.rmtree(temp)
print 'File removed from your system'
elif a == (r'C:\Program Files (x86)'):
os.chdir(r'C:\Program Files (x86)')
shutil.rmtree(r'C:\Program Files (x86)\Wise')
shutil.rmtree(temp)
print 'File removed from your system'
else:
print 'file not removed from your system'
wise_status=Install(Download(temp, URL, FileName, Extension),SilentCommand)
if wise_status:
Clean(wise_status)
uninstall(path)
################################################################################################################
print "SFC scan"
command=r'sfc /scannow'
obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
out, err = obj.communicate()
if out:
data = out.replace(' ', ' ')[::2]
for i in data.split('\r'):
print i
else:
print err
################################################################################################################
print "SMART"
print "Process Test 1 SMART Status Check"
process1=Popen("wmic diskdrive get status,caption",stdout=PIPE,stderr=PIPE)
r1,e1=process1.communicate()
if e1:
print e1
else:
r1=r1.splitlines()
print r1[0]
for i in r1[1:]:
print i
print "Process Test 2 SMART Drive Predictive Failure"
process2=Popen(r"wmic /namespace:\\root\wmi path MSStorageDriver_FailurePredictStatus",stdout=PIPE,stderr=PIPE)
r2,e2=process2.communicate()
if e2:
print e2
else:
print r2
r2=r2.splitlines()
for i in r2[1:]:
if not i:
pass
else:
check=i.split()[1:]
if check[1]=='FALSE':
print "Hard Drive is working no failure or error in %s"%check[0]
else:
print "Failure In Disk %s"%check[0]
except Exception as E:
print E
finally:
print "Executed in %s seconds "%(time.time()-start)
Comments