Recently, I needed to find out the free space on the physical disks of some of my windows servers programmatically. There doesn’t seem to be an easy way to do this without installing other libraries and I didn’t want to do that since I was going to be deploying this script to a good number of servers.
So I started poking around and I found we can figure out the local hard disks via windows wmic commands and our friend the subprocess library:
import subprocess import ctypes #Get the fixed drives #wmic logicaldisk get name,description drivelist = subprocess.check_output(['wmic', 'logicaldisk', 'get', 'name,description']) driveLines = drivelist.split('\n') for line in driveLines: if line.startswith("Local Fixed Disk"): elements = line.split() driveLetter = elements[-1] free_bytes = ctypes.c_ulonglong(0) total_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(driveLetter), None, ctypes.pointer(total_bytes), ctypes.pointer(free_bytes)) print "Drive %s" % driveLetter print free_bytes.value print total_bytes.value print str(int(float(free_bytes.value) / float(total_bytes.value) * 100.00)) + "% Free"
What we do is call the command wmic logicaldisk get name,description with subprocess and then parse the local disks out of that. Afterwords we pull the used and free bytes using ctypes with the Windows command GetDiskFreeSpaceExW
More on wmic http://www.computerhope.com/wmic.htm
The Stackoverflow question on using GetDiskFreeSpaceExW to get free disk space. http://stackoverflow.com/questions/51658/cross-platform-space-remaining-on-volume-using-python