def _get_removable_drives() -> list: removable_drives = [] all_drives_enum: str = GetLogicalDriveStrings() for drive in all_drives_enum.split('\x00'): if GetDriveType(drive) == win32con.DRIVE_REMOVABLE: removable_drives.append(drive) return removable_drives
def get_drives_list(drive_types=(win32con.DRIVE_REMOVABLE, )): drives_str = GetLogicalDriveStrings() drives = [item for item in drives_str.split("\x00") if item] return [ item[:2] for item in drives if drive_types is None or GetDriveType(item) in drive_types ]
def get_drives_list(drive_types=(win32con.DRIVE_REMOVABLE, )): ret = list() print(ret) drives = [item for item in GetLogicalDriveStrings().split("\x00") if item] for drive in drives: if GetDriveType(drive) in drive_types: ret.append(drive[:2]) return ret
def _write_default_setup_file(setup_file): """ stanza if setup_file needs to be created """ # Windows only for now # ===================== os_system = os.name if os_system != 'nt': print('Operating system is ' + os_system + 'should be nt - cannot proceed with writing default setup file') sleep(sleepTime) sys.exit(0) # auto find ORATOR location from list of drive # ============================================ err_mess = '*** Error creating setup file *** ' drives = GetLogicalDriveStrings() drives = drives.split('\000')[:-1] orator_flag = False for drive in drives: orator_dir = os.path.join(drive, 'ORATOR') if os.path.isdir(orator_dir): print('Found ' + orator_dir) orator_flag = True break if not orator_flag: print(err_mess + 'Could not find ' + orator_dir + ' on any of the drives ' + str(drives).strip('[]')) sleep(sleepTime) sys.exit(0) data_path = os.path.join(drive, 'GlobalEcosseData') if not os.path.isdir(data_path): print(err_mess + 'Could not find ' + data_path) sleep(sleepTime) sys.exit(0) orator_dir += '\\' data_path += '\\' _default_setup = { 'setup': { 'config_dir': orator_dir + 'config', 'fname_png': os.path.join(orator_dir + 'Images', 'Tree_of_life.PNG'), 'hwsd_dir': data_path + 'HWSD_NEW', 'log_dir': orator_dir + 'logs', 'shp_dir': data_path + 'CountryShapefiles', 'weather_dir': data_path } } # create setup file # ================= with open(setup_file, 'w') as fsetup: json.dump(_default_setup, fsetup, indent=2, sort_keys=True) fsetup.close() return _default_setup
def getRemovableDrives(drive_types=(win32con.DRIVE_REMOVABLE, )): driveList = list() driveStr = GetLogicalDriveStrings() drives = [str(item) + '\\' for item in driveStr.split("\x00")] for drv in drives: if GetDriveType(drv) in drive_types: driveList.append(drv[:3]) return driveList
def scan_for_disk_root_win(): from win32api import GetLogicalDriveStrings from win32file import GetDriveType, DRIVE_FIXED, DRIVE_REMOVABLE drives = GetLogicalDriveStrings() drives = drives.split('\000')[:-1] drives = list( filter( lambda d: GetDriveType(d) == DRIVE_FIXED or GetDriveType(d) == DRIVE_REMOVABLE, drives)) disk_root = next(iter(filter(has_info_head, drives)), None) return disk_root
def get_removable_drives(drive_types=(win32con.DRIVE_REMOVABLE, )): ret = list([" "]) drives_str = GetLogicalDriveStrings() drives = [item for item in drives_str.split("\x00") if item] for drive in drives: if GetDriveType(drive) in drive_types: try: GetVolumeInformation(drive[:2] + "\\") ret.append(drive[:2]) except: pass #print("Removable Drives: " + str(ret)) return ret
def getDrives(): driveFiltersExamples = [(None, "All"), ((win32con.DRIVE_REMOVABLE, ), "Removable")] for (driveTypesTuple, displayText) in driveFiltersExamples: drivesStr = GetLogicalDriveStrings() drives = [item for item in drivesStr.split("\x00") if item] drives = [ item[:3] for item in drives if driveTypesTuple is None or GetDriveType(item) in driveTypesTuple ] break return drives
def EvtRefreshAmovible(self): SplitDisk, j = None, 0 self.Disk = GetLogicalDriveStrings() self.comboBox_drives.clear() if isinstance(self.Disk, str): SplitDisk = self.Disk.split('\\\x00') self.Disks = SplitDisk #['C:', 'D:', 'E:', 'F:', 'G:', ''] for i in self.Disks: self.setComboContent(j, i) j += 1 self.currentSelected = SplitDisk[0] del SplitDisk else: return self.RefreshAmovible()
def __init__(self, parent=None): self.app = QtWidgets.QApplication(argv) FRemover.Ui_MainWindow.__init__(self) self.ComSpec = GetEnvironmentVariable('ComSpec') self.Disk = GetLogicalDriveStrings() self.IndexDrives = [] self.TextLogs = '' self.currentSelected = None self.Disks = self.EvtRefreshAmovible() self.EventsUI() FRemover.Ui_MainWindow.show(self) exit(self.app.exec_())
def searchAutorun(): """Scans every local drive looking for autoruns""" devices = GetLogicalDriveStrings().split("\\\x00")[:-1] autoruns = [] if "A:" in devices: devices.remove("A:") # List comprehention. Isn't it beautiful? fixed_devices = [device for device in devices if GetDriveType(device) == DRIVE_FIXED] for device in fixed_devices: device_content = commandHandler.getOutput(["dir", "/a/b", device + "\\"]) if "autorun.inf" in device_content or "autorun.exe" in device_content: autoruns.append(device) return autoruns
def _drives(drive_letter: Text) -> Text: """Returns drive letter. drive_letter: Drive letter to be searched for. Returns the drive letter from all the valid and present partitions. This assures that the user does not use any drive letter which is not present on the system. """ partitions = GetLogicalDriveStrings().split('\000')[:-1] drive = {} try: for index in range(len(partitions)): keys = (Path(partitions[index]).parts[0].split(':\\')[0]).lower() values = partitions[index] drive[keys] = values return drive[drive_letter[0].lower()] except KeyError as error: missing_drive = str(error).strip('\'') print(f'Could not find {missing_drive.title()}:\\ drive.')
def getRemovableDevices(): removableDevices = [] if sys.platform == "win32": from win32api import GetLogicalDriveStrings, GetVolumeInformation from win32file import GetDriveType drives = GetLogicalDriveStrings() drives = drives.split('\000')[:-1] for drive in drives: if GetDriveType(drive) == 2: try: removableDevices.append( list(GetVolumeInformation(drive)) + [drive]) except: QgsMessageLog.logMessage("GetVolumeInformation error ", u'qgis2mobile', QgsMessageLog.CRITICAL) else: pass return removableDevices
# Iterate over all the entries for entry in listOfFile: if entry == "System Volume Information" or entry == "Programs" or entry == "$RECYCLE.BIN": #Optional for C: drive continue fullPath = path.join(dirName, entry) # Create full path if path.isdir(fullPath): #If directory the get subfiles allFiles = allFiles + getListOfFiles(fullPath) else: allFiles.append(fullPath) return allFiles except OSError: pass return [] drivess1 = GetLogicalDriveStrings() #Disk drives drivess1 = drivess1.split('\000')[:-1] #On characters enough shuffle(drivess1) #huffling the drive list drivess1.remove( "C:\\" ) #Removing C drive since permission issues takes place and C contains alot of subfolders for drives in drivess1: dirName1 = drives listOfFiles = getListOfFiles(dirName1) out_file = "C:\\Users\\" + username + "\\Desktop\\Tempfile.txt" A = "" B = "" temp_elem = ""
# python 3.8.1 from os import walk from re import match, search from timeit import timeit from win32api import GetLogicalDriveStrings default_root_paths = GetLogicalDriveStrings().split('\000')[:-1] default_path_filter = r'' default_query = r'' default_filter_flag = 0 default_parallel = 1 notNone = lambda val, method: val if val != None else method() class Search: def __init__( self, root_paths=None, path_filter=None, query=None, filter_flag=None, ): self.root_paths = notNone(root_paths, self.get_root_paths) self.path_filter = notNone(path_filter, self.get_path_filter) self.query = notNone(query, self.get_query) self.filter_flag = notNone(filter_flag, self.get_filter_flag) self.report = '' def get_root_paths(self): message = """
self.error = QLabel(self) self.error.setText('error') self.error.move(150, 150) self.show() if __name__ == '__main__': inf1 = os.environ['COMPUTERNAME'] inf2 = os.environ['USERNAME'] inf3 = os.environ['WINDIR'] inf4 = GetSystemDirectory() inf5 = GetSystemMetrics(0) inf6 = os.getcwd() inf7 = GetLogicalDriveStrings() signature = inf1 + inf2 + inf3 + inf4 + inf6 + inf7 + str(inf5) sha = hashlib.sha256(signature.encode()).hexdigest() key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Romanuik\\Signature", 0, winreg.KEY_READ) key_dict = {} i = 0 while True: try: subvalue = winreg.EnumValue(key, i) except WindowsError as e: break key_dict[subvalue[0]] = subvalue[1:] i += 1
def __init__(self, root: str = '192.168.0', first: int = 1, last: int = 254, timeout: float = 2): # Generate list of all possible addresses nodes = list('{}.{}'.format(root, str(i)) for i in range(first, last + 1)) # Dict of all responding addresses self.active_nodes = {} netbios = set() with concurrent.futures.ThreadPoolExecutor( max_workers=len(nodes)) as executor: sock_timeout = getdefaulttimeout() setdefaulttimeout(1) _names = { executor.submit(self._get_names, address): address for address in nodes } setdefaulttimeout(sock_timeout) try: for future in concurrent.futures.as_completed(_names, timeout=timeout): _name = _names[future] try: data = future.result() except Exception as exc: print('%r generated an exception: %s' % (_name, exc)) else: if data[1]: if data[1][0].split('.')[0].upper() not in netbios: netbios.add(data[1][0].split('.')[0].upper()) self.active_nodes[data[0]] = data[1] except concurrent.futures.TimeoutError: pass # Dict of info for addresses with data shares self.machines_info = {} # List of shares formatted as \\server\share self.shares_list = [] # list of drives self.drives_list = [ letter[0:2] for letter in GetLogicalDriveStrings().split('\x00') if letter != '' ] with concurrent.futures.ThreadPoolExecutor( max_workers=len(self.active_nodes)) as executor: _shares = { executor.submit(self._get_shares, node): node for node in self.active_nodes.keys() } try: for future in concurrent.futures.as_completed(_shares, timeout=timeout): _share = _shares[future] try: data = future.result() except Exception as exc: print('%r generated an exception: %s' % (_share, exc)) else: if data[3]: self.machines_info[data[0]] = [data[1], data[2]] for share in data[3]: self.shares_list.append( f'\\\\{data[1]}\{share}') except concurrent.futures.TimeoutError: pass
def get_drive_list(self): return list(letter[0:2] for letter in GetLogicalDriveStrings().split('\x00') if letter != '').sort()
#x.replace(" ","") p2 = "{}.jpg".format(x) print p2 camera = cv2.VideoCapture(0) time.sleep(1) return_value, image = camera.read() cv2.imwrite(p2, image) camera.release() cv2.destroyAllWindows() time.sleep(1) while True: try: drive_types = (win32con.DRIVE_REMOVABLE, ) ret = list() drives_str = GetLogicalDriveStrings() drives = [item for item in drives_str.split("\x00") if item] for drive in drives: if GetDriveType(drive) in drive_types: ret.append(drive) item1 = ret[0] except: time.sleep(3) continue if os.path.exists(item1): takephoto() break sound()