def dd_disk_image(self, progress, image): if os.path.exists(image): progress.status(" writing %s to %s" % (os.path.basename(image), self.drive)) if sys.platform == "win32": import win32file # need to convert Letter driver to device path that dd.exe wants device_path = win32file.QueryDosDevice(self.drive) path = string.split(device_path, "\\") dd_device_path = '\\\\?\\' + path[1] + '\\' + path[ 2] + '\\Partition0' self.popen('dd-removable if="%s" of="%s" bs=1M --size' % (image, dd_device_path)) elif sys.platform == "darwin": # dd usb disk image onto physical usb flash device # use the raw disk (rdisk) for speed #TODO - fix "/dev/disk#" to "/dev/rdisk#" convertion path = string.split(self.drive, "/") rdrive = "/" + path[1] + "/r" + path[2] [status, rtn] = commands.getstatusoutput( "dd if=%s of=%s bs=1m" % (image, rdrive)) if status: self.log.warning('Unable write usb disk image') print rtn else: [status, rtn] = commands.getstatusoutput( "dd if=%s of=%s bs=1M" % (image, self.drive)) if status: self.log.warning('Unable write usb disk image') print rtn
def revise_filepath(fullpath=''): #fullpath="\\\\??\\\\c:\\tools\\safe\\xu.sys" #fullpath='\\SystemRoot\\tools\\safe\\xu.sys' #fullpath='\\WINDOWS\\pro \\1e2e.exe' #fullpath='\\WINNT\\pro \\1e2e.exe' #fullpath='\\device\\harddiskvolume1\\aaaa\\1.exe' fullpath=fullpath.lower() if fullpath.startswith('\\??\\'): fullpath=fullpath[len('\\??\\'):] return fullpath elif fullpath.startswith('\\systemroot\\'): fullpath=os.path.join(os.getenv('systemroot'), fullpath[len('\\systemroot\\'):]) return fullpath elif fullpath.startswith('%systemroot%\\'): fullpath=os.path.join(os.getenv('systemroot'), fullpath[len('%systemroot%\\'):]) return fullpath elif fullpath.startswith('\\device\\harddiskvolume'): s=win32api.GetLogicalDriveStrings() l=s.split('\x00') for i in l: if i!='': name=win32file.QueryDosDevice(i.rstrip('\\')).strip('\x00').lower() if fullpath.startswith(name): fullpath=fullpath.replace(name, '') fullpath=os.path.join(i, fullpath) break return fullpath elif fullpath.startswith('\\windows\\'): windowsdir=win32api.GetWindowsDirectory() fullpath=os.path.join(windowsdir, fullpath[len('\\windows\\'):]) return fullpath elif fullpath.startswith('\\winnt\\'): windowsdir=win32api.GetWindowsDirectory() fullpath=os.path.join(windowsdir, fullpath[len('\\winnt\\'):]) return fullpath elif fullpath.startswith('\\'): s=win32api.GetLogicalDriveStrings() l=s.split('\x00') for i in l: if i!='': drivername=i.rstrip('\\') newfullpath=os.path.join(drivername, fullpath) if os.path.exists(newfullpath): return newfullpath return fullpath else: return fullpath
def __init__(self): self.DEVICE_DRIVES = dict() self._running = False self._threads = [] self._pid_blacklist = dict() self._pid_blacklist[os.getpid()] = True # Get Windows Drive for d in "abcdefghijklmnopqrstuvwxyz": try: device = win32file.QueryDosDevice(d + ":").strip("\x00").lower() self.DEVICE_DRIVES[device] = d.upper() + ":" except win32file.error, (errno, errctx, errmsg): if errno != 2: raise
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 CheckDeviceNode(curdev): ''' Checks whether it makes sense to perform searching on this device and possibly warns user about misconfigurations. Returns tuple of 4 members: - error code (0 = ok, -1 = device does not exits, -2 = no permissions) - log text - error dialog title - error dialog text ''' if sys.platform == 'win32': try: import win32file if curdev[:3] == 'COM': try: win32file.QueryDosDevice(curdev) return (0, '', '', '') except: return (-1, _('Device %s does not exist!') % curdev, _('Error opening device'), _('Device %s does not exist!') % curdev ) except ImportError: return (0, '', '', '') if not os.path.exists(curdev): return (-1, _('Device %s does not exist!') % curdev, _('Error opening device'), _('Device %s does not exist!') % curdev ) if not os.access(curdev, os.R_OK) or not os.access(curdev, os.W_OK): gid = os.stat(curdev).st_gid try: group = grp.getgrgid(gid)[0] except: group = str(gid) return (-2, _('You don\'t have permissions for %s device!') % curdev, _('Error opening device'), (_('You don\'t have permissions for %s device!') % curdev) + ' ' + (_('Maybe you need to be member of %s group.') % group) ) return (0, '', '', '')
def __init__(self): self.DEVICE_DRIVES = dict() self._running = False self._threads = [] self._requests = Queue.Queue() self._results = Queue.Queue() # Get WIndows Drive for d in "abcdefghijklmnopqrstuvwxyz": try: device = win32file.QueryDosDevice(d + ":").strip("\x00").lower() self.DEVICE_DRIVES[device] = d.upper() + ":" except win32file.error, (errno, errctx, errmsg): if errno == 2: pass else: raise
def ejectDrive(driveLetter): try: deviceName = win32file.QueryDosDevice(driveLetter[0].upper() + ":") except pywintypes.error as e: if e.winerror == 2: return errorCodes.FILE_NOT_FOUND else: dialog(_("エラー"), e.strerror) # log.error(unknown error in"+e.funcname+". code="+e.winerror+" # message="+e.strerror) return errorCodes.UNKNOWN deviceName = re.sub(r"\\Device\\([^\x00]+).*", r"\1", deviceName) try: handle = win32file.CreateFile( "\\\\.\\" + deviceName, win32file.GENERIC_WRITE | win32file.GENERIC_READ, 0, # クローズするまで他からはOPENできない None, # セキュリティ関連の構造体 win32file.OPEN_EXISTING, # デバイスのOPENはこれじゃないとダメ 0, None) except pywintypes.error as e: if e.winerror == 32: return errorCodes.ACCESS_DENIED else: dialog(_("エラー"), e.strerror) # log.error(unknown error in"+e.funcname+". code="+e.winerror+" # message="+e.strerror) return errorCodes.UNKNOWN ret = win32file.DeviceIoControl(handle, winioctlcon.IOCTL_DISK_EJECT_MEDIA, None, None) handle.Close() return errorCodes.OK
def _get_recycle_bins(): #logging.debug(repr(win32api.GetLogicalDrives())) drives = win32api.GetLogicalDriveStrings() #logging.debug(repr(drives.split("\0"))) bin_info = [] for drive in drives.split("\0"): drive_type = win32file.GetDriveType(drive) if drive_type in (win32file.DRIVE_FIXED, win32file.DRIVE_RAMDISK #win32file.DRIVE_REMOVABLE ): # Detect SUBSTed volume and ignore it try: volume_mapping = win32file.QueryDosDevice(drive[:2]) if volume_mapping.startswith("\\??\\"): break except: pass try: size, files = shell.SHQueryRecycleBin(drive) bin_info.append((drive, size, files)) logging.debug(drive + str(drive_type)) except Exception, e: log.error(e)
def findVolumeGuids(): DiskExtent = collections.namedtuple( 'DiskExtent', ['DiskNumber', 'StartingOffset', 'ExtentLength']) Volume = collections.namedtuple( 'Volume', ['Guid', 'MediaType', 'DosDevice', 'Extents']) found = [] h, guid = FindFirstVolume() while h and guid: #print (guid) #print (guid, win32file.GetDriveType(guid), # win32file.QueryDosDevice(guid[4:-1])) hVolume = win32file.CreateFile( guid[:-1], win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) extents = [] driveType = win32file.GetDriveType(guid) if driveType in [win32con.DRIVE_REMOVABLE, win32con.DRIVE_FIXED]: x = win32file.DeviceIoControl( hVolume, winioctlcon.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, None, 512, None) instream = io.BytesIO(x) numRecords = struct.unpack('<q', instream.read(8))[0] fmt = '<qqq' sz = struct.calcsize(fmt) while 1: b = instream.read(sz) if len(b) < sz: break rec = struct.unpack(fmt, b) extents.append(DiskExtent(*rec)) vinfo = Volume(guid, driveType, win32file.QueryDosDevice(guid[4:-1]), extents) found.append(vinfo) guid = FindNextVolume(h) return found
def QueryDosDevice(dev): dev = dev[:dev.index(":") + 1] target = File.QueryDosDevice(dev) return target.split("\0")[0]
def find_process_with_file_handle(path): # Check for drive absolute path if path[1:2] != ':': return None try: device_prefix = win32file.QueryDosDevice(path[:2]) except WinError: return None device_path = device_prefix[:-2] + path[2:] pid = os.getpid() pid_handle = {} denied_pid = set() cphandle = kernel32.GetCurrentProcess() found_process = None for handle in list_handles(): # Do no query handles with 0x0012019f GrantedAccess, it may hang # Only name pipes should have that GrantedAccess value if handle.GrantedAccess == 0x0012019f: continue # Skip handles in processes previously denied if handle.UniqueProcessId in denied_pid: continue # Get process handle phandle = pid_handle.get(handle.UniqueProcessId, None) if phandle is None: if VISTA_OR_LATER: desired_access = DWORD( PROCESS_DUP_HANDLE.value | PROCESS_QUERY_LIMITED_INFORMATION.value) else: desired_access = DWORD(PROCESS_DUP_HANDLE.value | PROCESS_QUERY_INFORMATION.value) phandle = kernel32.OpenProcess(desired_access, BOOL(False), handle.UniqueProcessId) if phandle is None: denied_pid.add(handle.UniqueProcessId) continue # Get a handle duplicate dup_handle = HANDLE() status = ntdll.NtDuplicateObject(phandle, handle.HandleValue, cphandle, byref(dup_handle), 0, 0, 0) if status != STATUS_SUCCESS: continue # Query the object type buflen = 0x1000 pobject_type_info = cast(create_string_buffer(buflen), POINTER(OBJECT_TYPE_INFORMATION)) length = ULONG() status = ntdll.NtQueryObject(dup_handle, ObjectTypeInformation, pobject_type_info, buflen, byref(length)) if status != STATUS_SUCCESS: kernel32.CloseHandle(dup_handle) continue # We are only looking for file handles if pobject_type_info.contents.Name.Buffer != 'File': kernel32.CloseHandle(dup_handle) continue # Query the object name buflen = 0x1000 pobject_name = cast(create_string_buffer(buflen), POINTER(UNICODE_STRING)) length = ULONG() while True: status = ntdll.NtQueryObject(dup_handle, ObjectNameInformation, pobject_name, buflen, byref(length)) if status != STATUS_INFO_LENGTH_MISMATCH: break buflen = length.value pobject_name = cast(create_string_buffer(buflen), POINTER(UNICODE_STRING)) if status != STATUS_SUCCESS: kernel32.CloseHandle(dup_handle) continue # Is this handle the file we are looking for? if device_path == pobject_name.contents.Buffer: # Get process path buflen = 0x1000 pimage_file_name = cast(create_string_buffer(buflen), POINTER(UNICODE_STRING)) length = ULONG() while True: status = ntdll.NtQueryInformationProcess( phandle, ProcessImageFileName, pimage_file_name, buflen, byref(length)) if status != STATUS_INFO_LENGTH_MISMATCH: break buflen = length.value pimage_file_name = cast(create_string_buffer(buflen), POINTER(UNICODE_STRING)) if status != STATUS_SUCCESS: kernel32.CloseHandle(dup_handle) continue image_file_name = pimage_file_name.contents.Buffer if image_file_name.startswith(device_prefix[:-2]): image_file_name = path[:2] + image_file_name[len(device_prefix ) - 2:] else: devices = win32file.QueryDosDevice(None).split('\x00') letters = [] for device in devices: if (len(device) == 2 and device[-1] == ':' and device != path[:2]): letters.append(device) for letter in letters: device_prefix = win32file.QueryDosDevice(letter) if image_file_name.startswith(device_prefix[:-2]): image_file_name = letter + image_file_name[ len(device_prefix) - 2:] break found_process = { 'pid': handle.UniqueProcessId, 'image_file_name': image_file_name } kernel32.CloseHandle(dup_handle) break kernel32.CloseHandle(dup_handle) for phandle in pid_handle.values(): kernel32.CloseHandle(phandle) return found_process
PVOID = c_void_p ntdll = windll.ntdll SystemHandleInformation = 16 STATUS_INFO_LENGTH_MISMATCH = 0xC0000004 STATUS_BUFFER_OVERFLOW = 0x80000005L STATUS_INVALID_HANDLE = 0xC0000008L STATUS_BUFFER_TOO_SMALL = 0xC0000023L STATUS_SUCCESS = 0 CURRENT_PROCESS = win32api.GetCurrentProcess () DEVICE_DRIVES = {} for d in "abcdefghijklmnopqrstuvwxyz": try: DEVICE_DRIVES[win32file.QueryDosDevice (d + ":").strip ("\x00").lower ()] = d + ":" except win32file.error, (errno, errctx, errmsg): if errno == 2: pass else: raise class x_file_handles (Exception): pass def signed_to_unsigned (signed): unsigned, = struct.unpack ("L", struct.pack ("l", signed)) return unsigned class SYSTEM_HANDLE_TABLE_ENTRY_INFO (Structure): _fields_ = [
def subst(device, target): try: Wfile.QueryDosDevice(device) except: Wfile.DefineDosDevice(0, device, target)
import win32file import re deviceName = win32file.QueryDosDevice("I:") deviceName = re.sub(r"\\Device\\([^\x00]+).*", r"\1", deviceName) handle = win32file.CreateFile( "\\\\.\\" + deviceName, win32file.GENERIC_WRITE | win32file.GENERIC_READ, 0, # クローズするまで他からはOPENできない None, # セキュリティ関連の構造体 win32file.OPEN_EXISTING, # デバイスのOPENはこれじゃないとダメ 0, None) print(handle) print(win32file.DeviceIoControl(handle, 0x2D4808, None, None)) # IOCTL_STORAGE_EJECT_MEDIA print(handle.Close())