def GetDriveObject(index): """ドライブ情報を調べて、browsableObjectsで返す。Aドライブが0、Zドライブが25。""" letter = chr(index + 65) path = letter + ":\\" type = win32file.GetDriveType(path) f = -1 t = -1 n = "" try: volumeInfo = win32api.GetVolumeInformation(path) n = volumeInfo[0] freeSpace = win32api.GetDiskFreeSpaceEx(path) f = freeSpace[0] t = freeSpace[1] except pywintypes.error as err: pass # エラーは無視 d = browsableObjects.Drive() if type != win32file.DRIVE_REMOTE or t != -1: ret, shfileinfo = shell.SHGetFileInfo(letter + ":\\", 0, shellcon.SHGFI_ICON) d.Initialize(letter, f, t, type, n, shfileinfo[0]) else: d.Initialize(letter, f, t, type, n, -1) return d
def get_free_space_at_path(path): """ Given a path on the file system, return the (best approximation of the) free space at the filesystem mounted at that path. @param path: The path which filesystem needs to be checked for free space. @rtype: numbers.Integral >>> # Just validate the function being called. >>> bool(get_free_space_at_path('.')) True """ path = os.path.abspath(path) # We have a path to test for free space; but if the path itself does not # exist yet, we should browse higher and higher from that path # until we find out the path that exists if not os.path.exists(path): parent = os.path.dirname(path) if parent == path: # Oopsie, cannot browse to the parent anymore. return 0 else: return get_free_space_at_path(parent) else: if sys.platform == 'win32': n_free_user, n_total, n_free = win32api.GetDiskFreeSpaceEx(path) return n_free_user elif sys.platform.startswith('linux') or sys.platform == 'darwin': _statvfs = os.statvfs(path) return _statvfs.f_frsize * _statvfs.f_bavail else: raise NotImplementedError(sys.platform)
def diskspace_base(dir_to_check: str) -> Tuple[float, float]: """ Return amount of free and used diskspace in GBytes """ # Find first folder level that exists in the path x = "x" while x and not os.path.exists(dir_to_check): dir_to_check, x = os.path.split(dir_to_check) if sabnzbd.WIN32: # windows diskfree try: available, disk_size, total_free = win32api.GetDiskFreeSpaceEx( dir_to_check) return disk_size / GIGI, available / GIGI except: return 0.0, 0.0 elif hasattr(os, "statvfs"): # posix diskfree try: s = os.statvfs(dir_to_check) if s.f_blocks < 0: disk_size = float(sys.maxsize) * float(s.f_frsize) else: disk_size = float(s.f_blocks) * float(s.f_frsize) if s.f_bavail < 0: available = float(sys.maxsize) * float(s.f_frsize) else: available = float(s.f_bavail) * float(s.f_frsize) return disk_size / GIGI, available / GIGI except: return 0.0, 0.0 else: return 20.0, 10.0
def getDisksUsage(self): usages = list() try: drives_mask = win32api.GetLogicalDrives() path = 'a' while drives_mask > 0: path_name = path + ':\\' if (drives_mask & 1): try: res = win32api.GetDiskFreeSpaceEx(path_name) (free, total) = res[:2] fs = win32api.GetVolumeInformation(path_name)[4] used = total - free usages.append({ 'path': path_name, 'fs': fs, 'total': total, 'used': used }) except: pass drives_mask >>= 1 path = chr(ord(path) + 1) except: logging.exception("Error retrieving disks usages.") return usages
def diskspace_base(_dir): """ Return amount of free and used diskspace in GBytes """ _dir = find_dir(_dir) try: available, disk_size, total_free = win32api.GetDiskFreeSpaceEx(_dir) return disk_size / GIGI, available / GIGI except: return 0.0, 0.0
def disktotal(_dir): """ Return amount of free diskspace in GBytes """ try: available, disk_size, total_free = win32api.GetDiskFreeSpaceEx(_dir) return disk_size / GIGI except: return 0.0
def statevfs(path): import win32api import os.path path = os.path.normpath(path) if path[-1]=='\\': path = path[:-1] try: f,all,user = win32api.GetDiskFreeSpaceEx(path) return all,user except:return 0,0
def test_disk_usage(self): for disk in psutil.disk_partitions(): sys_value = win32api.GetDiskFreeSpaceEx(disk.mountpoint) psutil_value = psutil.disk_usage(disk.mountpoint) self.assertAlmostEqual(sys_value[0], psutil_value.free, delta=1024 * 1024) self.assertAlmostEqual(sys_value[1], psutil_value.total, delta=1024 * 1024) self.assertEqual(psutil_value.used, psutil_value.total - psutil_value.free)
def volume_space_free_for_current_user(directory): """Return the free disk space, in bytes, available for the current user on the volume that ``directory`` is mounted on, if available. If that information is not available then None is returned.""" try: import win32api info = win32api.GetDiskFreeSpaceEx(directory) return info[0] if info else None except ImportError: return None
def DiskSize(): import win32api import sys minDiskSizeGB = 50 if len(sys.argv) > 1: minDiskSizeGB = float(sys.argv[1]) _, diskSizeBytes, _ = win32api.GetDiskFreeSpaceEx() diskSizeGB = diskSizeBytes/1073741824 if diskSizeGB > minDiskSizeGB: return False else: return True
def run_test(self): try: if self.use_statvfs: result = os.statvfs(self.partition) space = result.f_bavail * result.f_frsize percent = float(result.f_bavail) / float(result.f_blocks) * 100 else: result = win32api.GetDiskFreeSpaceEx(self.partition) space = result[2] percent = float(result[2]) / float(result[1]) * 100 except Exception, e: self.record_fail("Couldn't get free disk space: %s" % e) return False
def test_disk_usage(self): for disk in psutil.disk_partitions(): if 'cdrom' in disk.opts: continue sys_value = win32api.GetDiskFreeSpaceEx(disk.mountpoint) psutil_value = psutil.disk_usage(disk.mountpoint) self.assertAlmostEqual(sys_value[0], psutil_value.free, delta=TOLERANCE_DISK_USAGE) self.assertAlmostEqual(sys_value[1], psutil_value.total, delta=TOLERANCE_DISK_USAGE) self.assertEqual(psutil_value.used, psutil_value.total - psutil_value.free)
def main(root=None, edict=None): if not root: root = Tk() if not edict: edict = ReadEnvSettings(root) c, p, a = get_size_all(edict) need = (c + p + a) / 1000000000.0 while 1: query = 'I need %.1fGB for new backup' % need dest = getwhere(root, query) if dest == '': return 4 sv = os.stat(dest) tup = win32api.GetDiskFreeSpaceEx(dest) if tup[0] > (c + p + a): break ans = tkMessageBox.askyesno( 'dest is ' + dest, 'Backup cannot be halted once started \n Really want to continue?') if not ans: return 9 # now to save version vline = open('C:/EEGer/BIN/Econfig', 'r').readline().strip() if vline == '': return 10 #now copy other stuff there if othercopy(dest, edict, vline): tkMessageBox.showerror('Backup EEGer data', 'Failure copying misc settings/keys,etc.') return 3 # ok, now archive clients there if clientarchive(dest, edict): tkMessageBox.showerror('Backup EEGer data', 'Failure client backups') return 1 # now copy archives there if archivecopy(dest, edict): tkMessageBox.showerror('Backup EEGer data', 'Failure copying archived clients') return 2 # report backup made if all ok return 0
def run_test(self) -> bool: try: if self.use_statvfs: result = os.statvfs(self.partition) space = result.f_bavail * result.f_frsize percent = float(result.f_bavail) / float(result.f_blocks) * 100 else: win_result = win32api.GetDiskFreeSpaceEx(self.partition) space = win_result[2] percent = float(win_result[2]) / float(win_result[1]) * 100 except Exception as e: return self.record_fail("Couldn't get free disk space: %s" % e) if self.limit and space <= self.limit: return self.record_fail("%s free (%d%%)" % (_bytes_to_size_string(space), percent)) return self.record_success("%s free (%d%%)" % (_bytes_to_size_string(space), percent))
def usage(): ''' Return usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.usage ''' drives = [] ret = {} drive_bitmask = ctypes.windll.kernel32.GetLogicalDrives() for letter in UPPERCASE: if drive_bitmask & 1: drives.append(letter) drive_bitmask >>= 1 for drive in drives: try: (available_bytes, total_bytes, total_free_bytes) = win32api.GetDiskFreeSpaceEx( '{0}:\\'.format(drive) ) used = total_bytes - total_free_bytes capacity = used / float(total_bytes) * 100 ret['{0}:\\'.format(drive)] = { 'filesystem': '{0}:\\'.format(drive), '1K-blocks': total_bytes / 1024, 'used': used / 1024, 'available': total_free_bytes / 1024, 'capacity': '{0:.0f}%'.format(capacity), } except Exception: ret['{0}:\\'.format(drive)] = { 'filesystem': '{0}:\\'.format(drive), '1K-blocks': None, 'used': None, 'available': None, 'capacity': None, } return ret
def usage(): """ Return usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.usage """ drives = [] ret = {} drive_bitmask = ctypes.windll.kernel32.GetLogicalDrives() for letter in UPPERCASE: if drive_bitmask & 1: drives.append(letter) drive_bitmask >>= 1 for drive in drives: try: ( available_bytes, total_bytes, total_free_bytes, ) = win32api.GetDiskFreeSpaceEx("{}:\\".format(drive)) used = total_bytes - total_free_bytes capacity = used / float(total_bytes) * 100 ret["{}:\\".format(drive)] = { "filesystem": "{}:\\".format(drive), "1K-blocks": total_bytes / 1024, "used": used / 1024, "available": total_free_bytes / 1024, "capacity": "{:.0f}%".format(capacity), } except Exception: # pylint: disable=broad-except ret["{}:\\".format(drive)] = { "filesystem": "{}:\\".format(drive), "1K-blocks": None, "used": None, "available": None, "capacity": None, } return ret
def do_check(self): try: import win32api except ImportError: return [] cmd = ['df', '-lP'] r = [] for drive in get_drives(): try: n_free_user, n_total, n_free = win32api.GetDiskFreeSpaceEx( drive + ':\\') except: continue pct = 100 * (n_total - n_free) // n_total r.append({ "instance": drive, "value": str(pct), "path": self.find_svc(drive), }) return r
# # Minimum disk size checker (default: 50 GB), Python # Module written by Brandon Arvanaghi # Website: arvanaghi.com # Twitter: @arvanaghi # Edited for use in winpayloads import win32api import sys minDiskSizeGB = 50 _, diskSizeBytes, _ = win32api.GetDiskFreeSpaceEx() diskSizeGB = diskSizeBytes / 1073741824 if diskSizeGB > minDiskSizeGB: pass else: sys.exit()
def get_disk_size(self): print ("which size of data do you prefer to recieve the information in:\n1)bytes\n2)kilobytes\n3)megabytes\n4)gigabytes") num = int(raw_input("press the number of the size you want")) n_free_user, self.disk_C_size, n_free = win32api.GetDiskFreeSpaceEx(r"C:\\") self.sizechose(num) return self.disk_C_size
Drives[letter] = Maps[letter] pass elif target.startswith("UNC\\"): # `subst`-mapped network disk #Maps[letter] = pass else: Drives[letter] = GetMountVolume(letter) for letter in Letters: isMapped = letter in Maps if isMapped: target = Maps[letter] type = -1 free, total, diskfree = Api.GetDiskFreeSpaceEx(letter) used = 100 - (100 * diskfree / total) else: root = Drives[letter] if root in Printed: continue Printed.append(root) pathnames = Volumes[root]["pathnames"][:] isReady = Volumes[root]["ready"] if isReady: type = GetDriveType(root) info = GetVolumeInformation(root)
def main(argv): lpmap = {} counters, instances = win32pdh.EnumObjectItems(None, None, 'PhysicalDisk', win32pdh.PERF_DETAIL_WIZARD) for instance in instances: instance = instance.encode('utf-8') if instance != '_Total': plist = instance.split() if len(plist) > 1: p_id = plist[0] llist = plist[1:] for l in llist: lpmap[l + '\\'] = 'Disk %s :' % p_id partitions = psutil.disk_partitions() out_list = [] fs_all_mb = 0.0 fs_used_mb = 0.0 fs_free_mb = 0.0 max_fs_usert = 0.0 ntp_checked, timestamp = get_ntp_time() for sdiskpart in partitions: if not sdiskpart.fstype or sdiskpart.fstype == 'CDFS': continue dimensions = { 'dev_nm': lpmap[sdiskpart.device], 'mnt_nm': sdiskpart.mountpoint, 'fs_type_nm': sdiskpart.fstype, 'mnt_stat_cd': 1 } sys_value = win32api.GetDiskFreeSpaceEx(sdiskpart.mountpoint) all_byt_cnt = sys_value[1] free_byt_cnt = sys_value[2] used_byt_cnt = all_byt_cnt - free_byt_cnt fs_usert = used_byt_cnt * 100.0 / all_byt_cnt metrics = { 'all_byt_cnt': all_byt_cnt / 1024 / 1024.0, 'used_byt_cnt': used_byt_cnt / 1024 / 1024.0, 'free_byt_cnt': free_byt_cnt / 1024 / 1024.0, 'fs_usert': fs_usert } fs_all_mb += all_byt_cnt fs_used_mb += used_byt_cnt fs_free_mb += free_byt_cnt if fs_usert > max_fs_usert: max_fs_usert = fs_usert out = { 'dimensions': dimensions, 'metrics': metrics, 'timestamp': timestamp, 'ntp_checked': ntp_checked } out_list.append(out) metrics = {} metrics['fs_all_mb'] = fs_all_mb / 1024 / 1024.0 metrics['fs_used_mb'] = fs_used_mb / 1024 / 1024.0 metrics['fs_free_mb'] = fs_free_mb / 1024 / 1024.0 metrics['avg_fs_usert'] = fs_used_mb * 100 / fs_all_mb metrics['max_fs_usert'] = max_fs_usert out = { 'dimensions': { 'schema_type': 'svr' }, 'metrics': metrics, 'timestamp': timestamp, 'ntp_checked': ntp_checked } out_list.append(out) print(json.dumps(out_list)) sys.stdout.flush()
def get_disk_size(self): n_free_user, self.disk_C_size, n_free = win32api.GetDiskFreeSpaceEx( r"C:\\") # self.sizechose(Config.SIZE) self.sizechose(1) return self.disk_C_size
def Drive_Free(Path): return win32api.GetDiskFreeSpaceEx(Path)[0]
def getFreeSpaceGB(driveLetter): result = win32api.GetDiskFreeSpaceEx(driveLetter) freeGB, totalGB = map(lambda x: x / 2**30, result[0:2]) return (freeGB, totalGB)
def get_free_space(letter): size = win32api.GetDiskFreeSpaceEx(letter) free_bytes = size[0] total_space = size[1] return free_bytes, total_space
def main(root=None, edict=None): if not root: root = Tk() if not edict: edict = ReadEnvSettings(root) busy = BusyBox.BusyBox(root, 'Determining amount of backup space needed...') c, p, a = get_size_all(edict) need = (c + p + a) / 1000000000.0 busy = None tkMessageBox.showinfo( 'Backup EEGer data', 'After selecting a destination folder\nsub-folders that are date-stamped will be created:\n Other-datestamp\n Setup-datestamp\n Archive-datestamp\n Clients-datestamp' ) while 1: query = 'I need %.1fGB for new backup \nand NOT in EEGer folder' % need dest = getwhere(root, query) if dest == '': return 4 herex = os.getcwd() here2 = os.path.split(herex) maybe = os.path.normpath(dest.upper()) here = os.path.normpath(here2[0].upper()) ans = maybe.find(here) ##print ans,'here:',here,' maybe:',maybe,here2 if ans != -1: tkMessageBox.showerror( 'Backup EEGer data', 'Destination folder CANNOT be within EEGer path') continue if os.path.exists(dest): if not os.path.isdir(dest): continue else: try: os.makedirs(dest) except: continue try: sv = os.stat(dest) except: #print dest continue tup = win32api.GetDiskFreeSpaceEx(dest) if tup[0] > (c + p + a): break ans = tkMessageBox.askyesno( 'dest is ' + dest, 'Backup cannot be halted once started \n Really want to continue?') if not ans: return 9 busy = BusyBox.BusyBox(root, 'Backing up to ' + dest) # now to save version vline = open('C:/EEGer/BIN/Econfig', 'r').readline().strip() if vline == '': return 10 #now copy other stuff there busy.newstatus('Misc files') if othercopy(dest, edict, vline): busy = None tkMessageBox.showerror('Backup EEGer data', 'Failure copying misc settings/keys,etc.') return 3 # ok, now archive clients there busy.newstatus('Client files') if clientarchive(dest, edict, busy): busy = None tkMessageBox.showerror('Backup EEGer data', 'Failure client backups') return 1 # now copy archives there busy.newstatus('Archives') if archivecopy(dest, edict): busy = None tkMessageBox.showerror('Backup EEGer data', 'Failure copying archived clients') return 2 # report backup made if all ok busy = None return 0
def get_free_space(self, path): import win32api available, x, x = win32api.GetDiskFreeSpaceEx(path) return available
def getDiskFreeSpace(volumeLetter): freeBytes, totalBytes, totalFreeBytes = win32api.GetDiskFreeSpaceEx( volumeLetter) return totalFreeBytes
root.grid_rowconfigure(0, weight=1) # включаем реагирование столбцов/строк окна на его масштабирование root.grid_columnconfigure(0, weight=1) root.grid_columnconfigure(1, weight=1) button_choose_dir.grid(row=0, column=0, pady=10, padx=10, sticky='nw') # размещаем элементы button_exit.grid(row=0, column=1, pady=10, padx=10, sticky='n') #button_save.grid(row=1, column=1, pady=10, padx=10, sticky='es') sctext_logCreated.grid(row=2, column=0, pady=10, padx=10, sticky='w') sctext_logDeleted.grid(row=4, column=0, pady=10, padx=10, sticky='w') sctext_logModified.grid(row=2, column=1, pady=10, padx=10, sticky='e') sctext_logMoved.grid(row=4, column=1, pady=10, padx=10, sticky='e') labelCreated.grid(row=1, column=0, pady=10, padx=10, sticky='w') labelDeleted.grid(row=3, column=0, pady=10, padx=10, sticky='w') labelModified.grid(row=1, column=1, pady=10, padx=10, sticky='e') labelMoved.grid(row=3, column=1, pady=10, padx=10, sticky='e') drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] i = 0 for disk in drives: a, b, c = win32api.GetDiskFreeSpaceEx(drives[i]) name = drives[i] print(drives[i], 'Всего Мегабайт:', b / 1000000, 'Свободно Мегабайт:', a / 1000000, round(a / b * 100, 2), '%') i += 1 frame = tk.Frame(master=root, relief=tk.RAISED, borderwidth=1) frame.grid(row=0, column=i + 1) label = tk.Label(master=frame, text=f"Диск:{name}\nВсего Мегабайт {b}\nСвободно Мегабайт {a}") label.pack() root.mainloop() # запускаем работу основного потока программы