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 assign_letter_by_label(label, letter): label_ = label.lower() letter_ = letter.lower() drives = get_drives_labels() if label_ in drives.values(): search_drive = list(drives.keys())[list(drives.values()).index(label_)] else: print(f'Disk "{label}" not found.') return False if letter_ in drives and drives[letter_] == label_: print(f'Disk "{label}" already assigned to {letter.upper()}:\\') return True elif letter_ in drives: print( f'Letter {letter.upper()}:\\ already assigned to disk "{drives[letter_]}"' ) mounted_volume = win32file.GetVolumeNameForVolumeMountPoint( f'{letter_}:\\') win32file.DeleteVolumeMountPoint(f'{letter_}:\\') new_volume_letter = sorted(char_range('c', 'z') - set(drives.keys()))[0] print( f'Remapping partition {mounted_volume} to {new_volume_letter.upper()}:\\' ) win32file.SetVolumeMountPoint(f'{new_volume_letter}:\\', mounted_volume) elif search_drive: print(f'Disk "{label}" found as drive {search_drive.upper()}:\\') remap_from_ = f'{search_drive}:\\' remap_to_ = f'{letter_}:\\' print(f'Remapping from {remap_from_.upper()} to {remap_to_.upper()}') volume_name = win32file.GetVolumeNameForVolumeMountPoint(remap_from_) win32file.DeleteVolumeMountPoint(remap_from_) win32file.SetVolumeMountPoint(remap_to_, volume_name) return True
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
def usb(): # DRIVE_TYPES = """ # 0 Unknown # 1 No Root Directory # 2 Removable Disk # 3 Local Disk # 4 Network Drive # 5 Compact Disc # 6 RAM Disk #""" # drive_types = dict((int (i), j) for (i, j) in (l.split ("\t") for l in DRIVE_TYPES.splitlines () if l)) # drives = (drive for drive in win32api.GetLogicalDriveStrings ().split ("\000") if drive) # for drive in drives: #print drive, "=>", drive_types[win32file.GetDriveType (drive)] # if drive_types[win32file.GetDriveType (drive)] == 'Local Disk': # print drive #disks = wmi.WMI().Win32_DiskDrive(MediaType="External hard disk media") #for disk in disks: # for disk1 in wmi.WMI().Win32_LogicalDisk(): # print disk # print disk1 # e2.delete(0, END) # e2.insert(0, drive+r'USMT_Store') c = wmi.WMI() for disk in c.query( 'SELECT * FROM Win32_DiskDrive WHERE MediaType LIKE "External hard disk media"' ): deviceID = disk.DeviceID for partition in c.query( 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' + deviceID + '"} WHERE AssocClass = Win32_DiskDriveToDiskPartition'): for logical_disk in c.query( 'ASSOCIATORS OF {Win32_DiskPartition.DeviceID="' + partition.DeviceID + '"} WHERE AssocClass = Win32_LogicalDiskToPartition'): #print('USB Drive letter: {}'.format(logical_disk.DeviceID)) if logical_disk.VolumeName == 'Win7MIG': remap_from, remap_to = logical_disk.DeviceID + '\\', "g:\\" volume_name = win32file.GetVolumeNameForVolumeMountPoint( remap_from) win32file.DeleteVolumeMountPoint(remap_from) win32file.SetVolumeMountPoint(remap_to, volume_name) e2.delete(0, END) #e2.insert(0, logical_disk.DeviceID+r'\USMT_Store') e2.insert(0, remap_to + r'USMT_Store') else: print "Volume Name is Incorrect: Manually Enter the Local Drive Path" return
def _isFAT32(self) -> bool: if not isWin: return False # pylint: disable=import-error import win32api, win32file # pytype: disable=import-error try: name = win32file.GetVolumeNameForVolumeMountPoint(self._dir[:3]) except: # mapped & unmapped network drive; pray that it's not vfat return False if win32api.GetVolumeInformation(name)[4].lower().startswith("fat"): return True return False
def _isFAT32(self): if not isWin: return False import win32api import win32file try: name = win32file.GetVolumeNameForVolumeMountPoint(self._dir[:3]) except: # Probably a network drive. When that is FAT we may have a # problem. return False if win32api.GetVolumeInformation(name)[4].lower().startswith("fat"): return True
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 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 GetRawDevice(path): """Resolves the raw device that contains the path. Args: path: A path to examine. Returns: A pathspec to read the raw device as well as the modified path to read within the raw device. This is usually the path without the mount point. Raises: IOError: if the path does not exist or some unexpected behaviour occurs. """ path = CanonicalPathToLocalPath(path) # Try to expand the shortened paths try: path = win32file.GetLongPathName(path) except pywintypes.error: pass try: mount_point = win32file.GetVolumePathName(path) except pywintypes.error as details: logging.info("path not found. %s", details) raise IOError("No mountpoint for path: %s", path) if not path.startswith(mount_point): stripped_mp = mount_point.rstrip("\\") if not path.startswith(stripped_mp): raise IOError("path %s is not mounted under %s" % (path, mount_point)) corrected_path = LocalPathToCanonicalPath(path[len(mount_point):]) corrected_path = utils.NormalizePath(corrected_path) volume = win32file.GetVolumeNameForVolumeMountPoint(mount_point).rstrip( "\\") volume = LocalPathToCanonicalPath(volume) # The pathspec for the raw volume result = rdf_paths.PathSpec(path=volume, pathtype=rdf_paths.PathSpec.PathType.OS, mount_point=mount_point.rstrip("\\")) return result, corrected_path
def windowsDevices(): '''This one is to get all the info about windows removable devices in a big array, the format is as follows: [ ['\\\\.\\PHYSICALDRIVE1', 'Mass Storage Device USB Device', '8052549120', [('F:\\', 'MSDOS', '\\\\?\\Volume{23e2ba26-8a62-11e9-afa4-080027673c27}\\')] ], ['\\\\.\\PHYSICALDRIVE2', 'Verbatim STORE N GO USB Device', '7739988480', [('G:\\', 'PAVEL', '\\\\?\\Volume{23e2ba2b-8a62-11e9-afa4-080027673c27}\\')], [('H:\\', 'RAPUT', '\\\\?\\Volume{23e2bcfb-8112-11e9-afa4-080276524590}\\')] ] ] ''' c = wmi.WMI() data = [] for physical_disk in c.Win32_DiskDrive(): capas = physical_disk.Capabilities if capas != None and 7 in capas: # is a removable media phy = physical_disk.DeviceID size = int(physical_disk.Size) desc = physical_disk.Caption drives = [] for partition in physical_disk.associators( "Win32_DiskDriveToDiskPartition"): for logical_disk in partition.associators( "Win32_LogicalDiskToPartition"): name = logical_disk.Name + "\\" label = logical_disk.VolumeName guid = win32file.GetVolumeNameForVolumeMountPoint(name) drives.append((name, label, guid)) data.append([phy, desc, size, drives]) return data
def Devices(): c = wmi.WMI() data = [] for physical_disk in c.Win32_DiskDrive(): if 7 in physical_disk.Capabilities: # is a removable media phy = physical_disk.DeviceID size = int(physical_disk.Size) desc = physical_disk.Caption drives = [] for partition in physical_disk.associators( "Win32_DiskDriveToDiskPartition"): for logical_disk in partition.associators( "Win32_LogicalDiskToPartition"): name = logical_disk.Name + "\\" label = logical_disk.VolumeName guid = win32file.GetVolumeNameForVolumeMountPoint(name) drives.append((name, label, guid)) data.append([phy, desc, size, drives]) return data
def test_volume(self): self.assertEquals( fs.drive("C:").volume.name, win32file.GetVolumeNameForVolumeMountPoint("C:\\"))
def get_volume (): return win32file.GetVolumeNameForVolumeMountPoint (sys.executable[:3])
def get_volume_for_c_drive(): return win32file.GetVolumeNameForVolumeMountPoint("C:\\")
def __refresh(self): """ Refresh all data (fill self.devices) """ # check if refresh is needed if (self.timestamp is not None and time.time() - self.timestamp <= self.CACHE_DURATION): self.logger.debug("Don't refresh") return # get system drive system_drive = self.__get_system_drive() self.logger.debug("System drive: %s" % system_drive) # get infos from DiskDrive command and init devices devices = {} disks = self.winService.ExecQuery("SELECT * FROM Win32_DiskDrive") for disk in disks: current_device = { "device": None, "displayName": None, "description": None, "size": 0, "mountpoints": [], "raw": None, "protected": False, "system": None, "deviceType": None, "temp_partitions": [], "temp_displayname": [], "temp_device": None, } for property in disk.Properties_: if property.Name == "DeviceID": current_device["temp_device"] = property.Value # workaround for etcher-cli >=1.3.1 and balena-cli # balena.exe util available-drives # DEVICE SIZE DESCRIPTION # \\.\PhysicalDrive3 30.9 GB Kingston DataTraveler 3.0 USB Device current_device["device"] = property.Value.replace( "PHYSICALDRIVE", "PhysicalDrive") # current_device['device'] = property.Value current_device["raw"] = property.Value elif property.Name == "Caption": current_device["description"] = property.Value elif property.Name == "MediaType": # try to set drive type. If drive has partitions, it will be overwritten below if property.Value is None: current_device["deviceType"] = self.DEVICE_TYPE_UNKNOWN elif property.Value.lower() in ( self.MEDIA_TYPE_EXTERNAL_HD, self.MEDIA_TYPE_FIXED_HD, ): current_device["deviceType"] = self.DEVICE_TYPE_FIXED elif property.Value.lower() == self.MEDIA_TYPE_REMOVABLE: current_device[ "deviceType"] = self.DEVICE_TYPE_REMOVABLE else: current_device["deviceType"] = self.DEVICE_TYPE_UNKNOWN current_device["displayName"] = "No partition" elif property.Name == "Size": try: current_device["size"] = int(property.Value) except: current_device["size"] = 0 devices[current_device["temp_device"]] = current_device # get infos from DiskDriveToDiskPartitions command partitions = self.winService.ExecQuery( "SELECT * FROM Win32_DiskDriveToDiskPartition") for partition in partitions: for device in devices.keys(): if device.replace("\\", "") in str( partition.Antecedent.replace("\\", "")): devices[device]["temp_partitions"].append( partition.Dependent.split("=")[1].replace('"', "")) # get infos from LogicalDiskToPartition logicals = self.winService.ExecQuery( "SELECT * FROM Win32_LogicalDiskToPartition") for logical in logicals: for device in devices.keys(): for partition in devices[device]["temp_partitions"]: self.logger.debug("%s == %s" % (partition, str(logical.Antecedent))) if partition in str(logical.Antecedent): mountpoint = logical.Dependent.split("=")[1].replace( '"', "") # save system if mountpoint == system_drive: devices[device]["system"] = True elif not devices[device]["system"]: devices[device]["system"] = False # save mountpoint (and its guid to allow mouting it) guid = None try: guid = win32file.GetVolumeNameForVolumeMountPoint( "%s\\\\" % mountpoint).replace("\\\\", "\\") except: self.logger.exception( "Exception during GetVolumeNameForVolumeMountPoint:" ) devices[device]["mountpoints"].append({ "path": mountpoint, "guid": guid }) # save displayName devices[device]["temp_displayname"].append(mountpoint) # save device type if devices[device]["deviceType"] in ( None, self.DEVICE_TYPE_UNKNOWN, ): devices[device][ "deviceType"] = win32file.GetDriveType( mountpoint) # save protected try: # https://msdn.microsoft.com/en-us/library/windows/desktop/aa364993(v=vs.85).aspx (_, _, _, readonly, _) = win32api.GetVolumeInformation("%s\\" % mountpoint) if (int(readonly) & 0x00080000) == 0: devices[device]["protected"] = False else: devices[device]["protected"] = True except Exception as e: pass # clean dicts for device in devices.keys(): devices[device]["temp_displayname"].sort() if len(devices[device]["temp_displayname"]) == 0: devices[device]["displayName"] = "no partition" else: devices[device]["displayName"] = ", ".join( devices[device]["temp_displayname"]) del devices[device]["temp_displayname"] del devices[device]["temp_partitions"] del devices[device]["temp_device"] # save devices self.devices = list(devices.values()) # update timestamp self.timestamp = time.time()
c = wmi.WMI() for disk in c.query( 'SELECT * FROM Win32_DiskDrive WHERE MediaType LIKE "External hard disk media"' ): deviceID = disk.DeviceID for partition in c.query( 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' + deviceID + '"} WHERE AssocClass = Win32_DiskDriveToDiskPartition'): for logical_disk in c.query( 'ASSOCIATORS OF {Win32_DiskPartition.DeviceID="' + partition.DeviceID + '"} WHERE AssocClass = Win32_LogicalDiskToPartition'): remap_from, remap_to = logical_disk.DeviceID + '\\', "G:\\" volume_name = win32file.GetVolumeNameForVolumeMountPoint( remap_from) win32file.DeleteVolumeMountPoint(remap_from) win32file.SetVolumeMountPoint(remap_to, volume_name) print('Local USB Drive letter: {}'.format(remap_to) ) + " To Not Interfere With Local Drive Data Transfer D:,E:,F:" except: print "No Local USB Drive Found" ################################################################# def usb(): # DRIVE_TYPES = """ # 0 Unknown # 1 No Root Directory
def acquire_files(self): self.updateLabel("Starting Processing") self.cursor.execute( "insert into evidence_sources (filename) values (?)", [self.compdesc]) evi_id = self.cursor.execute( "SELECT last_insert_rowid()").fetchone()[0] self.cursor.execute( "insert into partitions (number, offset, evidence_file_id) values (?, ?, ?)", [0, 0, evi_id]) self.part_id = self.cursor.execute( "SELECT last_insert_rowid()").fetchone()[0] # find the OS install drive and its raw/partition path letter = os.getenv("SystemDrive") if letter[-1] != "\\": letter = letter + "\\" # raw path to the system drive path = win32file.GetVolumeNameForVolumeMountPoint(letter) path = path.replace("?", ".") path = path.rstrip("\\") img_info = pytsk3.Img_Info(path) fs = pytsk3.FS_Info(img_info) winver = platform.release() # vss if winver in ['Vista', '7']: self.updateLabel("Processing Vista/7") cls = vista7(self) # sys restore elif winver == 'XP': self.updateLabel("Processing Windows XP") cls = XP(self) else: self.message( "Your operating system is unsupported. Please file a bug if you are running on Windows 7, Vista, or XP." ) return False if self.acquire_backups: cls.backup_ops.acquire_files(fs) self.conn.commit() if self.acquire_current: cls.current_ops.acquire_files(fs) self.conn.commit() self.updateLabel("Final Processing") self.conn.commit() self.updateLabel("Finished Processing. Files successfully acquired.") return True