This Script is used to delete the Cache Files if the Size exceeds the limit 2.5 GB.
Note:
This script could be used as an auto-remediation procedure for the below custom monitoring script.
https://scripts.itarian.com/frontend/web/topic/script-to-monitor-squid-cache-file-size
Run as System User
Tested in Windows 8 Machine
import os
import ctypes
import time
from subprocess import PIPE, Popen
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)
def getfoldersize(path):
total_size = 0
spath = path
for path, dirs, files in os.walk(spath):
for f in files:
fp = os.path.join(path, f)
total_size += os.path.getsize(fp)
return str(total_size)
def ecmd(command, output=False):
with disable_file_system_redirection():
objt = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
out, err = objt.communicate()
ret = objt.returncode
if not out:
return ret
else:
return '%s\n%s' % (out, err)
Squid_Path = r"{0}\Squid_ITarian\var\cache".format(os.environ['systemdrive'])
if os.path.exists(Squid_Path):
print("Squid cache folder is present on the system")
filesize = getfoldersize(Squid_Path)
if int(filesize) > 2684354560:
print("The 2.5 GB quota for the Squid cache folder is exceeded")
print("Folder size in bytes: {0}".format(filesize))
print("The cache folder will be deleted")
command1 = 'net stop squidsrv'
with disable_file_system_redirection():
os.popen(command1)
time.sleep(3)
command2 = 'sc query squidsrv | findstr STATE'
with disable_file_system_redirection():
servicestatus = os.popen(command2).read()
print("Squid service status:")
print(servicestatus)
command3 = 'RD /S /Q "C:\\Squid_ITarian\\var\\cache"'
with disable_file_system_redirection():
os.popen(command3)
time.sleep(3)
command5 = '"C:\\Squid_ITarian\\bin\\squid.exe" -z'
ecmd(command5,True)
time.sleep(10)
command6 = 'net start squidsrv'
with disable_file_system_redirection():
os.popen(command6)
time.sleep(20)
filesize2 = getfoldersize(Squid_Path)
print("Results:")
print("Folder size in bytes: {0}".format(filesize2))
command7 = 'sc query squidsrv | findstr STATE'
with disable_file_system_redirection():
servicestatus2 = os.popen(command7).read()
print("Squid service status:")
print(servicestatus2)
else:
print("The 2.5 GB quota for the Squid cache folder is NOT exceeded")
else:
print("Squid cache folder is NOT present on the system !!!")
print("This procedure will stop")
Comments