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 find_daysimeter(): """ PUROSE: Finds the daysimeter and returns its path """ log_filename = constants.LOG_FILENAME data_filename = constants.DATA_FILENAME #If Windows if sys.platform == 'win32': drives = GetLogicalDriveStrings() drives = [x for x in drives.split('\\\000') if x.strip()] for x in drives: #There is a security risk in using os.path.isfile, because the #file could be created after the check. However, the chance of #anyone expoliting this is virtually zero. if os.path.isfile(x + '/' + log_filename) and \ os.path.isfile(x + '/' + data_filename): return x + '\\' #Else if Macintosh elif sys.platform == 'darwin': volumes = os.listdir('/Volumes') for x in volumes: if os.path.isfile(x + '/' + log_filename) and \ os.path.isfile(x + '/' + data_filename): return x + '/' #Else if Linux elif sys.platform.startswith('linux'): devices = os.listdir('/media') for x in devices: if os.path.isfile(x + '/' + log_filename) and \ os.path.isfile(x + '/' + data_filename): return x + '/' return False ####Need to write cross-platform code here
def get_drives_list(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[: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 _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 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
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.')
# 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 = """
class Remover(FRemover.Ui_MainWindow): 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 EventsUI(self): self.btn_opendriver.clicked.connect(self.EvtOpenDrive) self.btn_refresh.clicked.connect(self.EvtRefreshAmovible) self.btn_openlogs.clicked.connect(self.EvtOpenLogs) self.btn_clean.clicked.connect(self.EvtCleanAmovible) self.comboBox_drives.currentIndexChanged[ 'QString' ]\ .connect(lambda : self.EvtIndexChanged( self.comboBox_drives.currentIndex() )) @pyqtSlot() 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 setComboContent(self, j, i=None): if i is not None and i is not '': self.comboBox_drives.addItem("") self.comboBox_drives.setItemText(j, "Lecteur " + str(i)) self.IndexDrives.append([j, i]) @pyqtSlot() def EvtOpenDrive(self): for k in self.IndexDrives: if k[0] == self.comboBox_drives.currentIndex(): WinExec('Explorer ' + str(k[1])) del k @pyqtSlot() def EvtOpenLogs(self): WinExec( self.ComSpec + " /c dir " + self.currentSelected + "\ > " + self.currentSelected + "\Resultat.txt", SW_HIDE) ret = QtWidgets.QMessageBox.information( self, "Confirmation", '''Voulez-vous voir un aperçu sur le contenu de votre Flash disk ?''', QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Cancel) if ret == QtWidgets.QMessageBox.Ok: WinExec("Explorer " + self.currentSelected + "\Resultat.txt", SW_HIDE) else: pass @pyqtSlot() def EvtIndexChanged(self, Disq): if isinstance(Disq, int): for k in self.IndexDrives: if k[0] == self.comboBox_drives.currentIndex(): self.currentSelected = k[1] @pyqtSlot() def EvtCleanAmovible(self): global ListVirus if GetDriveType(self.currentSelected) == 2: WinExec( self.ComSpec + " /c attrib -s -h -r " + self.currentSelected + "\*.* /D /S", SW_HIDE) for root, dirs, files in walk(self.currentSelected + "/"): for file in files: f = file.split('.') if len(f) > 1: if f[1].upper() == "LNK": unlink(root + "\\" + file) for Virus in ListVirus: if path.exists(self.currentSelected + "\\" + Virus): WinExec( self.ComSpec + " /C cd \ & del " + self.currentSelected + "\\" + Virus + "/f /q /a", SW_HIDE) self.TextLogs += strftime( "%H:%M:%S" ) + " [Clean] Les Virus " + Virus + " ont ètè supprimè avec succés\n" self.TextEditlogs.setPlainText(self.TextLogs) self.TextLogs += strftime( "%H:%M:%S") + " [Clean] FlashDisk nettoyée avec succés\n" self.TextEditlogs.setPlainText(self.TextLogs) else: self.TextLogs += strftime( "%H:%M:%S" ) + " [Clean] Ceci n'est pas Votre Clé USB Personnelle!\n" self.TextEditlogs.setPlainText(self.TextLogs)
def __init__(self, parent,id=wx.ID_ANY): wx.Panel.__init__(self,parent,-1) master_splitter = wx.SplitterWindow(self, -1, style=wx.SP_3D) # wxpython behaves strangely if we set the minimum pane size too small, and it resizes the windows to an obnoxiously # small size - by setting the minimum to 100, wxpython will, by default, split the windows evenly in half, with the option # to resize them down as small as 100 pixels wide. master_splitter.SetMinimumPaneSize(100) top_splitter = wx.SplitterWindow(master_splitter, -1, style=wx.SP_3D) top_splitter.SetMinimumPaneSize(100) self.dir = wx.GenericDirCtrl(top_splitter, -1, dir='/home/', style=wx.DIRCTRL_DIR_ONLY|wx.BORDER_RAISED) self.dir.SetPath(os.getcwd()) # set up the config file self.config = ConfigObj('config.cfg') # get the list of possible extensions from the config file extension_list = self.config['Extensions'].keys() self.FileList = FileListCtrl(top_splitter,-1,extension_list=extension_list) self.bottom_panel = wx.Panel(master_splitter) self.bottom_panel_sizer = wx.BoxSizer(wx.HORIZONTAL) self.plot = matplot.plot(self.bottom_panel) self.bottom_panel_sizer.Add(self.plot,1,wx.EXPAND) #self.textbox = wx.TextCtrl(self.bottom_panel,-1,style=wx.TE_MULTILINE|wx.HSCROLL) #self.bottom_panel_sizer.Add(self.textbox,1,wx.EXPAND) self.spreadsheet = CustomGrid.SpreadSheet(self.bottom_panel) self.bottom_panel_sizer.Add(self.spreadsheet,1,wx.EXPAND) self.bottom_panel.SetSizer(self.bottom_panel_sizer) #self.textbox.WriteText('**************************************************') self.tree = self.dir.GetTreeCtrl() master_splitter.SplitHorizontally(top_splitter, self.bottom_panel) top_splitter.SplitVertically(self.dir, self.FileList,300) sizer = wx.BoxSizer(wx.VERTICAL) # add combo box for text representation of current directory if using_win32api: drives = GetLogicalDriveStrings() drives = drives.split('\000')[:-1] else: drives = [] self.combobox = wx.ComboBox(self,choices=drives,size=(800,25),style=wx.TE_PROCESS_ENTER) self.Bind(wx.EVT_COMBOBOX,self.OnComboboxSelect,id=self.combobox.GetId()) self.Bind(wx.EVT_TEXT_ENTER,self.OnComboboxSelect,id=self.combobox.GetId()) sizer.Add(self.combobox,0) # add the master splitter window AFTER the text input box for directory sizer.Add(master_splitter, 1, wx.ALL|wx.EXPAND, 5) self.SetSizer(sizer) #bind event for when user clicks on an item in the tree wx.EVT_TREE_SEL_CHANGED(self, self.tree.GetId(), self.OnDirTreeSelect) #self.FileSelect(0) wx.EVT_LIST_ITEM_SELECTED(self,self.FileList.GetId(),self.FileSelect) wx.EVT_LIST_ITEM_ACTIVATED(self, self.FileList.GetId(),self.OnDoubleClick) #self.plot.dummy_plot() self.OnDirTreeSelect(0) self.header = None
for entry in listOfFile: # Iterate over all the entries if entry == "System Volume Information" or entry == "Programs" or entry == "$RECYCLE.BIN": #Exceptional folders 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: #Exception for encrypted and unaccessable drives pass return [] drivess1 = GetLogicalDriveStrings() #Disk drives drivess1 = drivess1.split('\000')[:-1] #On characters enough shuffle(drivess1) #shuffling the drive list drivess1.remove("C:\\") #Removing C drive due to lot of permission issues for drives in drivess1: dirName1 = drives listOfFiles = getListOfFiles(dirName1) out_file = "C:\\Users\\" + username + "\\Desktop\\Tempfile.txt" #Storing path names to a file A = "" B = "" temp_elem = "" temp_elem1 = "" elem1 = ""
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
#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()
def get_drive_list(self): return list(letter[0:2] for letter in GetLogicalDriveStrings().split('\x00') if letter != '').sort()
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