def _get_logical_disks_win32api( include_fs: list = None, exclude_unknown_fs: bool = False ): """ include_fs: list of which filesystems to include, example ['NTFS', 'ReFS'] exclude_unknown_fs: shall we exclude unknown filesystems Returns list of drives, does include network drives GetLogicalDriveStrings Returns \0 separated list of drives, eg r'C:\\0Z:\', also includes network drives """ drives = win32api.GetLogicalDriveStrings() drives = drives.split("\000")[:-1] if include_fs: filtered_drives = [] for drive in drives: # volname, volsernum, maxfilenamlen, sysflags, filesystemtype = win32api.GetVolumeInformation(DrivePath) # We may have floppy drives (eg: A:) in drives list, especially for virtualized platforms # so win32api.GetVolumeInformation(drive) would fail with # pywintypes.error: (21, 'GetVolumeInformation', 'The device is not ready.') try: filesystem = win32api.GetVolumeInformation(drive)[4] if filesystem in include_fs: filtered_drives.append(drive) # We'll use bare exception here because pywintypes exceptions aren't always used except Exception as exc: # pylint: disable=W0702 if not exclude_unknown_fs: filtered_drives.append(drive) drives = filtered_drives # Remove antislash from drives drives = [drive.rstrip("\\") for drive in drives] return drives
def get_max_filesize(path): fs_name = None # optimistic if we can't tell max_filesize = 2**64 if os.name == 'nt': drive, path = os.path.splitdrive(os.path.abspath(path)) if len(drive) > 0: # might be a network path if drive[-1] != '\\': drive += '\\' volumename, serialnumber, maxpath, fsflags, fs_name = win32api.GetVolumeInformation( drive) if fs_name == "FAT32": max_filesize = 2**32 - 1 elif (fs_name == "FAT" or fs_name == "FAT16"): # information on this varies, so I chose the description from # MS: http://support.microsoft.com/kb/q118335/ # which happens to also be the most conservative. max_clusters = 2**16 - 11 max_cluster_size = 2**15 max_filesize = max_clusters * max_cluster_size else: path = os.path.realpath(path) # not implemented yet #fsname = crawl_path_for_mount_entry(path) return fs_name, max_filesize
def input_code(self, event=None): # 输入:文本 # 第三个参数表示显示类型,可选,有正常(QLineEdit.Normal)、密碼( QLineEdit. Password)、不显示( QLineEdit. NoEcho)三种情况 value, ok = QInputDialog.getText(self, u"激活后才能使用", u"软件未激活\n\n请输入激活码:", QLineEdit.Normal, u"这是默认值") if not ok: return False code = value # QString # b61129731b5ec530755a61815366ca29 一年有效的激活码 # 3c90f6a7073d20a56efecd68074fb441 12月6号前有效 if code: prp = prpcrypt('123454536f667445454d537973576562', '1234577290ABCDEF1264147890ACAE45'[0:16]) try: code = unicode(code) t = prp.decrypt(code) print t if int(t) < time.time() - 60 * 15: QtGui.QMessageBox.information(self, u"激活失败", u"激活失败,激活码已过期") else: pan_code = str(win32api.GetVolumeInformation("C:\\")[1]) with open(CODE_FILE_PATH, 'w') as f: f.write(pan_code) QtGui.QMessageBox.information( self, u"激活成功", u"激活成功,生成激活文件jihuoma.tmp,请勿删除") return True except Exception, e: print str(e) QtGui.QMessageBox.information(self, u"激活失败", u"激活失败")
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 c_volume_serial_number(cls): try: import win32api c_volume_serial_number = win32api.GetVolumeInformation("C:\\")[1] return str(c_volume_serial_number) except ImportError: return 0
def _get_logical_disks_win32api(include_non_ntfs_refs: bool = False): """ Returns \0 separated list of drives, eg r'C:\\0Z:\', also includes network drives """ drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] if not include_non_ntfs_refs: filtered_drives = [] for drive in drives: # volname, volsernum, maxfilenamlen, sysflags, filesystemtype = win32api.GetVolumeInformation(DrivePath) # We may have floppy drives (eg: A:) in drives list, especially for virtualized platforms # so win32api.GetVolumeInformation(drive) would fail with # pywintypes.error: (21, 'GetVolumeInformation', 'The device is not ready.') try: filesystem = win32api.GetVolumeInformation(drive)[4] if filesystem in ['NTFS', 'ReFS']: filtered_drives.append(drive) # We'll use bare exception here because pywintypes exceptions aren't always used except Exception: # pylint: disable=W0702 pass drives = filtered_drives # Remove antislash from drives drives = [drive.rstrip('\\') for drive in drives] return drives
def checksd(drive): global cd if len(drive) != 2 or drive[-1] != ':': return 1 if drive.upper()[0] == 'C': return 2 ans,lns=_checksdhdr(drive) if ans: return ans #now try the directory cname=rot13(lns[1][:-1]) try: cd=IniAid.LoadConfig(drive+'\\'+cname+'\\CLIENT.') except: return 5 if cd['client.clientid'] != cname: cd={} return 6 t=win32api.GetVolumeInformation(drive) if str(t[1]) != rot13(lns[2])[:-1]: return 7 # not on same drive as original #so far its valid, now look for some data rdlist=glob.glob(drive+'/'+cname+'/*') for each in rdlist: if os.path.isdir(each): for subs in '/*.RAW','/*.SUM': rx=glob.glob(each+subs) if len(rx): return -1 # quit on first something return 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 check_device(self): status_message = "No connected devices found" drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] self.device_status = 'none' self.device_drive = '' for drive in drives: try: label = win32api.GetVolumeInformation(drive)[0] if label == "CIRCUITPY": status_message = 'Found running device on ' self.device_status = 'run' self.device_drive = drive elif label == "TRINKETBOOT": status_message = 'Found a trinket in boot mode on ' self.device_drive = drive self.device_status = 'boot' except: pass self.ui.statusbar.showMessage(status_message + self.device_drive) if self.device_status == 'none': self.ui.textEdit_status.setText('Connect a Tinker Kit device') self.ui.pushButton_init_device.setEnabled(False) self.ui.pushButton_reset_projects.setEnabled(False) elif self.device_status == 'run': self.ui.textEdit_status.setText( 'To flash the devices firmware double press the reset button') self.ui.pushButton_init_device.setEnabled(False) self.ui.pushButton_reset_projects.setEnabled(True) elif self.device_status == 'boot': self.ui.textEdit_status.setText( 'You can now flash the devices firmware') self.ui.pushButton_init_device.setEnabled(True) self.ui.pushButton_reset_projects.setEnabled(False)
def makedrivesd(drive,clientid,clfullname): if len(drive) != 2 or drive[-1] != ':': return 1 if drive.upper()[0] == 'C': return 2 # for safety # create what I need in root of drive vname=clfullname[:11] try: win32file.SetVolumeLabel(drive+'\\',vname) except: pass t=win32api.GetVolumeInformation(drive) #make hidden file identifying this as an SD f=rot13(clfullname+'\n') f=f+rot13(clientid+'\n') f=f+rot13(str(t[1])+'\n') now=time.strftime('%Y%m%d') f=f+'Created=%s\n'%now m=md5.new() m.update(f) f=f+'Check='+m.hexdigest() f=f+'\n' try: win32file.SetFileAttributes(drive+'\\sd.sys',win32file.FILE_ATTRIBUTE_NORMAL) except: pass # ignore error if not there try: fd=open(drive+'\\sd.sys','w') fd.write(f) fd.close() except: return 3 win32file.SetFileAttributes(drive+'\\sd.sys',win32file.FILE_ATTRIBUTE_READONLY | win32file.FILE_ATTRIBUTE_SYSTEM | win32file.FILE_ATTRIBUTE_HIDDEN) return 0
def take_sample(self): disk_stats = {} disk_partitions = psutil.disk_partitions(all=True) mops.logger.log.debug('disk partitions: %s' % str(disk_partitions)) for disk in disk_partitions: disk_path = disk[0] volume_name = None used = 0 total = 0 info_ok = True try: total, used, free, percent = psutil.disk_usage(disk_path) except: info_ok = False mops.logger.log.debug('psutil.disk_usage(%s)' % str(disk_path)) try: volume_name, serial_number, max_len, flags, fs_name = win32api.GetVolumeInformation(disk_path) except: info_ok = False mops.logger.log.debug('win32api.GetVolumeInformation(%s)' % str(disk_path)) mops.logger.log.debug('disk_path: %s, volume_name: %s, used: %s, total: %s' % (disk_path, volume_name, str(used), str(total))) if info_ok: disk_name = volume_name + ' (' + disk_path[0] + ')' disk_stats[disk_name] = {} # disk_stats[disk_name]['volume'] = volume_name disk_stats[disk_name]['used'] = str(used) disk_stats[disk_name]['total'] = str(total) used_ratio = float(used)/float(total) disk_stats[disk_name]['value'] = '{:.1%}'.format(used_ratio) disk_stats[disk_name]['severity'] = ratio_to_severity_level(used_ratio, 0.85, 0.75) self.metrics = disk_stats
def volumeInformation(driveLetter): if len(driveLetter) != 1: raise ValueError('Driver letter must be a single char.') volumeName, volumeSerialNumber, maxComponentLen, sysFlags, fileSystemName = \ win32api.GetVolumeInformation(r'%c:\\' % driveLetter) return (volumeName, volumeSerialNumber, maxComponentLen, sysFlags, fileSystemName)
def getCVolumeSerialNumber(): CVolumeSerialNumber = win32api.GetVolumeInformation("C:\\")[1] # print(CVolumeSerialNumber) if CVolumeSerialNumber: return str(CVolumeSerialNumber) else: return 0
def scan(self): if not self.drive_selection.get(): print("Drive Not Selected") else: # print(self.controller.SystemParam["DriveLetter"]) Scan_Process = threading.Thread(target=self.Drive_Scanner, daemon=True) Scan_Process.start() Scan_Process.join() directory_list = self.controller.directory_list print(self.controller.directory_list) # directory_list = [] # # file_list_test = [] # # for (dirpath, dirnames, filenames) in os.walk(self.controller.SystemParam["DriveLetter"]): # for k in range(1): # # for dir in dirpath: # # f_test.append(dir) # directory_list.append(dirpath) # print(dirpath) # # file_list_test.append(os.path.join(dirpath+"\\"+dir)) info = win32api.GetVolumeInformation( self.controller.SystemParam["DriveLetter"]) print("disk serial number = %d" % info[1]) directory_list.insert(0, info[1]) directory_list.insert(0, info[0]) print(pd.DataFrame(directory_list)) self.new_data = directory_list messagebox.showinfo("Scan Complete", "Selected drive scanned successfully!")
def _isFAT32(self): if not isWin: return import win32api, win32file name = win32file.GetVolumeNameForVolumeMountPoint(self._dir[:3]) if win32api.GetVolumeInformation(name)[4].lower().startswith("fat"): return True
def detect_usb(self): # TODO - Should this return if nothing is in the whitelist? # Feels like it should be done elsewhere. if not self.config['windows']['usb_id_whitelist']: log.warning("No USB devices whitelisted, skipping detection...") return ids = [] for each in win32api.GetLogicalDriveStrings().split('\\\x00'): if win32file.GetDriveType(each) == win32file.DRIVE_REMOVABLE: decimal_id = win32api.GetVolumeInformation(each[1]) hex_id = '%X' % (0x100000000 + decimal_id) ids.append(hex_id) log.debug('USB:', ', '.join(ids) if ids else 'none detected') for each_device in ids: if each_device not in self.config['windows']['usb_id_whitelist']: self.kill_the_system('USB Allowed Whitelist: {0}'.format(each_device)) else: if self.config['windows']['usb_id_whitelist'][each_device] != ids.count(each_device): self.kill_the_system('USB Duplicate Device: {0}'.format(each_device)) for device in self.config['windows']['usb_connected_whitelist']: if device not in ids: self.kill_the_system('USB Connected Whitelist: {0}'.format(device)) else: if self.config['windows']['usb_connected_whitelist'][each_device] != ids.count(each_device): self.kill_the_system('USB Whitelist Duplicate Device: {0}'.format(each_device))
def volname(path): ''' Get the volume label for a CD/DVD @type path: C{str} @param path: Disc path @rtype: C{str} @return: Volume label ''' volname=None try: #if sys.platform[0:3].lower()=='win': if iswin: import win32api drive=os.path.splitdrive(path)[0] if drive[-1]!='\\':drive+='\\' if drive: volinfo=win32api.GetVolumeInformation(drive) if volinfo[4] in ['CDFS','UDF']:volname=volinfo[0] else: #get the device from mount point exit_code,stdout,stderr=utilities.runcmd('df '+path) if exit_code == 0: device=stdout.split('\n')[1].split()[0] exit_code,stdout,stderr=runcmd('volname '+device) if exit_code == 0:volname=stdout.strip() finally: return volname
def load_drivebay(self): #get the names of the drives in the system self.drives = win32api.GetLogicalDriveStrings() self.drives = self.drives.split('\000')[:-1] for i in self.drives:#iterate over no of drives self.disk_type = win32file.GetDriveType(i)#get the drive type if self.disk_type == 3:#If hard disk self.disk_usage = round(shutil.disk_usage(i)[2]/1024/1024/1024, 2) self.item = ThreeLineAvatarListItem(text=i, secondary_text = win32api.GetVolumeInformation(i)[0], tertiary_text = str(self.disk_usage) + "Gb is left") self.item2 = IconLeftWidget(icon = 'harddisk', pos=self.pos,size=self.size) self.item.add_widget(self.item2) self.item.bind(on_release = self.callback_function) self.ids.drivers.ids.drivebay.add_widget(self.item) elif self.disk_type == 2:# If pendrive or removable medium self.disk_usage = round(shutil.disk_usage(i)[2]/1024/1024/1024, 2) self.item = ThreeLineAvatarListItem(text=i, secondary_text = win32api.GetVolumeInformation(i)[0], tertiary_text = str(self.disk_usage) + "Gb is left") self.item2 = IconLeftWidget(icon = 'usb-flash-drive', pos=self.pos,size=self.size) self.item.add_widget(self.item2) self.item.bind(on_release = self.callback_function) self.ids.drivers.ids.drivebay.add_widget(self.item) elif self.disk_type == 3: #If cd drive self.disk_usage = round(shutil.disk_usage(i)[2]/1024/1024/1024, 2) self.item = ThreeLineAvatarListItem(text=i, secondary_text = win32api.GetVolumeInformation(i)[0], tertiary_text = str(self.disk_usage) + "Gb is left") self.item2 = IconLeftWidget(icon = 'album', pos=self.pos,size=self.size) self.item.add_widget(self.item2) self.item.bind(on_release = self.callback_function) self.ids.drivers.ids.drivebay.add_widget(self.item) elif self.disk_type == 0: #If drive is corrupt self.disk_usage = round(shutil.disk_usage(i)[2]/1024/1024/1024, 2) self.item = ThreeLineAvatarListItem(text=i, secondary_text = win32api.GetVolumeInformation(i)[0], tertiary_text = "Something is wrong with this drive") self.item2 = IconLeftWidget(icon = 'alert-circle', pos=self.pos,size=self.size) self.item.add_widget(self.item2) self.item.bind(on_release = self.callback_function) self.ids.drivers.ids.drivebay.add_widget(self.item)
def get_card_name(): ### Complete ''' Gets the loaded card name and number, to be used in the folder structed of the inputs. ''' cardname = win32api.GetVolumeInformation("K:\\")[0] return cardname.lower()
def get_drive_names(): drives = win.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] drive_map = {} for d in drives: drive_name = win.GetVolumeInformation(d)[0] drive_map[drive_name] = d return drive_map
def _find_drive_by_name_windows(name): drives = win32api.GetLogicalDriveStrings() drives = drives.split("\000")[:-1] for drive in drives: info = win32api.GetVolumeInformation(drive) if info[0] == name: return drive raise RuntimeError(f"No drive {name} found.")
def __is_cd_inserted(self, drive=''): try: x = win32api.GetVolumeInformation(drive) #print "CD is inserted in drive %s" % drive return 1 except: #print "no CD inserted in drive %s" % drive return 0
def find_circuitpython_drive(): drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] for drive in drives: info = win32api.GetVolumeInformation(drive) if info[0] == "CIRCUITPY": return drive raise RuntimeError("No circuitpython drive found.")
def is_partition_supported(folder): if folder[-1] != os.path.sep: folder = folder + os.path.sep if win32file.GetDriveType(folder) != win32file.DRIVE_FIXED: return False volume = win32file.GetVolumePathName(folder) t = win32api.GetVolumeInformation(volume) return t[-1] == 'NTFS'
def getCVolumeSerialNumber(self): CVolumeSerialNumber = win32api.GetVolumeInformation("C:\\")[1] # print chardet.detect(str(CVolumeSerialNumber)) # print CVolumeSerialNumber if CVolumeSerialNumber: return str( CVolumeSerialNumber) # number is long type,has to be changed to str for comparing to content after. else: return 0
def get_ramdrive_by_label(): ramdisk_drives = [] driver_list_str = win32api.GetLogicalDriveStrings() for driver in driver_list_str.split('\x00'): # 2 is removable driver, im ramdisk is 2 if win32file.GetDriveType(driver) == 2 and win32api.GetVolumeInformation(driver+'\\')[0] == 'RamDisk': ramdisk_drives.append(driver[0:2]) return ramdisk_drives
def _scan_drives_names(self): """Get the names of all local drives""" for drive_letter in self._drives: if not drive_letter in self._mapped.values(): try: data = win32api.GetVolumeInformation(drive_letter + ":\\") self._mapped[data[0]] = drive_letter except Exception as e: pass
def is_inode_capable(path): system = platform.system() if system == "Windows": volume_name = "%s:\\\\" % path.split(":", 1)[0] import win32api # type: ignore[import] # pylint: disable=import-error volume_info = win32api.GetVolumeInformation(volume_name) volume_type = volume_info[-1] return "ntfs" in volume_type.lower() return system == "Linux"
def get_volume_label(*args, **kwargs): """ Gets volume information using Windows API. :param args: Arguments for GetVolumeInformation from Windows API :param kwargs: Keyword arguments for GetVolumeInformation from Windows API :return: label from VolumeInformation tuple instance """ volume_information = VolumeInformation( *win32api.GetVolumeInformation(*args, **kwargs)) return volume_information.Label
def _isFAT32(self): if not isWin: return try: name = win32file.GetVolumeNameForVolumeMountPoint(self._dir[:3]) except: # mapped & unmapped network drive; pray that it's not vfat return if win32api.GetVolumeInformation(name)[4].lower().startswith("fat"): return True