def create_instance(clsiid, targetinterface, custom_iid=None, context=CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER): """A simple wrapper around ``CoCreateInstance <https://msdn.microsoft.com/en-us/library/windows/desktop/ms686615(v=vs.85).aspx>``""" if custom_iid is None: custom_iid = targetinterface.IID return winproxy.CoCreateInstance(byref(clsiid), None, context, byref(custom_iid), byref(targetinterface))
def read_pointer_from_process_vm(handle, address): pointer = PTR() num_bytes = ctypes.c_uint32() status = NtReadVirtualMemory(handle, address, byref(pointer), ctypes.sizeof(pointer), byref(num_bytes)) if status != STATUS_SUCCESS: raise WindowsOperationException('Could not read process virtual' ' memory to find pointer.') return pointer.value
def PeekNamedPipe(handle): """Calls kernel32.PeekNamedPipe(). Simplified version.""" c_avail = wintypes.DWORD() c_message = wintypes.DWORD() success = windll.kernel32.PeekNamedPipe(handle, None, 0, None, wintypes.byref(c_avail), wintypes.byref(c_message)) if not success: raise OSError(wintypes.GetLastError()) return c_avail.value
def PeekNamedPipe(handle): """Calls kernel32.PeekNamedPipe(). Simplified version.""" c_avail = wintypes.DWORD() c_message = wintypes.DWORD() success = windll.kernel32.PeekNamedPipe( handle, None, 0, None, wintypes.byref(c_avail), wintypes.byref(c_message)) if not success: raise OSError(wintypes.GetLastError()) return c_avail.value
def load(self): if not self._windll: if USE_NTDLL_LDR: mod = wintypes.byref( UNICODE_STRING(len(self.dllname) * 2, 256, self.dllname)) handle = wintypes.HANDLE() ctypes.windll.ntdll.LdrLoadDll(None, 0, mod, wintypes.byref(handle)) windll = ctypes.WinDLL(self.dllname, handle=handle.value) else: windll = ctypes.WinDLL(self.dllname) self._windll = windll
def readlink(path): reparse_point_handle = CreateFileW( path, 0, 0, None, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, None) if reparse_point_handle == INVALID_HANDLE_VALUE: _raise_winerror(get_last_error(), 'Error opening symblic link \"%s\"'.format(path)) target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE) n_bytes_returned = DWORD() io_result = DeviceIoControl(reparse_point_handle, FSCTL_GET_REPARSE_POINT, None, 0, target_buffer, len(target_buffer), byref(n_bytes_returned), None) CloseHandle(reparse_point_handle) if not io_result: _raise_winerror(get_last_error(), 'Error reading symblic link \"%s\"'.format(path)) rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer) if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK: return _preserve_encoding(path, rdb.SymbolicLinkReparseBuffer.PrintName) elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT: return _preserve_encoding(path, rdb.MountPointReparseBuffer.PrintName) # Unsupported reparse point type _raise_winerror(ERROR_NOT_SUPPORTED, 'Error reading symblic link \"%s\"'.format(path))
def windows_memory_usage(): """Return physical memory usage (float) Works on Windows platforms only""" from ctypes import windll, wintypes class MemoryStatus(wintypes.Structure): _fields_ = [ ('dwLength', wintypes.DWORD), ('dwMemoryLoad', wintypes.DWORD), ('ullTotalPhys', wintypes.c_uint64), ('ullAvailPhys', wintypes.c_uint64), ('ullTotalPageFile', wintypes.c_uint64), ('ullAvailPageFile', wintypes.c_uint64), ('ullTotalVirtual', wintypes.c_uint64), ('ullAvailVirtual', wintypes.c_uint64), ('ullAvailExtendedVirtual', wintypes.c_uint64), ] memorystatus = MemoryStatus() # MSDN documetation states that dwLength must be set to MemoryStatus # size before calling GlobalMemoryStatusEx # http://msdn.microsoft.com/en-us/library/aa366770(v=vs.85) memorystatus.dwLength = wintypes.sizeof(memorystatus) windll.kernel32.GlobalMemoryStatusEx(wintypes.byref(memorystatus)) return float(memorystatus.dwMemoryLoad)
def readlink(path): reparse_point_handle = CreateFileW(path, 0, 0, None, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, None) if reparse_point_handle == INVALID_HANDLE_VALUE: raise WinError() target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE) n_bytes_returned = DWORD() io_result = DeviceIoControl(reparse_point_handle, FSCTL_GET_REPARSE_POINT, None, 0, target_buffer, len(target_buffer), byref(n_bytes_returned), None) CloseHandle(reparse_point_handle) if not io_result: raise WinError() rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer) if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK: return rdb.SymbolicLinkReparseBuffer.PrintName elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT: return rdb.MountPointReparseBuffer.PrintName raise ValueError("not a link")
def windows_memory_usage(): """Return physical memory usage (float) Works on Windows platforms only""" from ctypes import windll, wintypes class MemoryStatus(wintypes.Structure): _fields_ = [ ("dwLength", wintypes.DWORD), ("dwMemoryLoad", wintypes.DWORD), ("ullTotalPhys", wintypes.c_uint64), ("ullAvailPhys", wintypes.c_uint64), ("ullTotalPageFile", wintypes.c_uint64), ("ullAvailPageFile", wintypes.c_uint64), ("ullTotalVirtual", wintypes.c_uint64), ("ullAvailVirtual", wintypes.c_uint64), ("ullAvailExtendedVirtual", wintypes.c_uint64), ] memorystatus = MemoryStatus() # MSDN documetation states that dwLength must be set to MemoryStatus # size before calling GlobalMemoryStatusEx # http://msdn.microsoft.com/en-us/library/aa366770(v=vs.85) memorystatus.dwLength = wintypes.sizeof(memorystatus) windll.kernel32.GlobalMemoryStatusEx(wintypes.byref(memorystatus)) return float(memorystatus.dwMemoryLoad)
def get_pid_info(pid): """Get a processes command line and environment. :raises: ProcessOperationException on error :rtype: str command line, dict of environ (str name, str value) """ # open the process so we can read its memory K32DLL.OpenProcess.restype = HANDLE handle = K32DLL.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, BOOL(False), DWORD(pid)) if not handle: raise WindowsOperationException("Could not open process [%d] " "with memory read access." % (pid,)) try: process_basic_info = PROCESS_BASIC_INFORMATION() status = NtQueryInformationProcess(handle, 0, byref(process_basic_info), ctypes.sizeof(process_basic_info), None) if status != STATUS_SUCCESS: raise WindowsOperationException('Could not get process ' 'basic info') user_process_parameter_address = read_pointer_from_process_vm(handle, process_basic_info.PebBaseAddress + (4 * ctypes.sizeof(PTR))) environ_address = read_pointer_from_process_vm( handle, user_process_parameter_address + 16 + (14 * ctypes.sizeof(PTR))) cmd_line = read_unicode_string_from_process_vm(handle, user_process_parameter_address + 16 + (12 * ctypes.sizeof(PTR))) env = read_environ_from_process_vm(handle, environ_address) return (cmd_line, env) except TypeError as exc: raise OperationException(exc.message) finally: K32DLL.CloseHandle(handle)
def move_files(paths, destination, fs = None, highlight = True, highlight_limit = 10): src_drive = paths[0][0] should_move = paths[0][1] == ':' and all([ len(src) > 1 and src_drive == src[0] and src[1] == ':' for src in paths ]) and src_drive == destination[0] and destination[1] == ':' total_file_size = 0 num_files = 0 move_paths = [] for path in paths: if is_shortcut_file(path): continue try: total_file_size += os.path.getsize(path) num_files += 1 move_paths.append(path) except Exception as e: if e.errno != errno.ENOENT: unhandled_exc_handler() continue if num_files > 0: TRACE('Decided to %s files listed on command line', 'move' if should_move else 'copy') args = SHFILEOPSTRUCTW(wFunc=UINT(shellcon.FO_MOVE if should_move else shellcon.FO_COPY), pFrom=LPCWSTR(u'\x00'.join(move_paths) + '\x00'), pTo=LPCWSTR(destination), fFlags=shellcon.FOF_ALLOWUNDO, fAnyOperationsAborted=BOOL()) result = shell32.SHFileOperationW(byref(args)) if result == 0: if highlight: items_to_show = [ os.path.join(destination, os.path.basename(src)) for src in move_paths ] if len(items_to_show) <= highlight_limit: highlight_files(destination, items_to_show) else: launch_folder(destination) return (num_files, total_file_size) TRACE('SHFileOperationW failed with result %d', result)
def _get_physical_mem_win32(): """Try getting a value for the physical memory using GlobalMemoryStatus. This is a windows specific method. Returns None if no value can be obtained (eg, not running on windows) - otherwise, returns a value in bytes. """ try: import ctypes import ctypes.wintypes as wintypes except ValueError: return None class MEMORYSTATUS(wintypes.Structure): _fields_ = [ ('dwLength', wintypes.DWORD), ('dwMemoryLoad', wintypes.DWORD), ('dwTotalPhys', wintypes.DWORD), ('dwAvailPhys', wintypes.DWORD), ('dwTotalPageFile', wintypes.DWORD), ('dwAvailPageFile', wintypes.DWORD), ('dwTotalVirtual', wintypes.DWORD), ('dwAvailVirtual', wintypes.DWORD), ] m = MEMORYSTATUS() wintypes.windll.kernel32.GlobalMemoryStatus(wintypes.byref(m)) return m.dwTotalPhys
def getFileVersion(self,filename): from ctypes.wintypes import ( windll, sizeof, WinError, byref, POINTER, cast, c_char, Structure, c_uint, pointer, BOOL, DWORD, LPVOID, LPCVOID, LPCWSTR, ) class VS_FIXEDFILEINFO(Structure): _fields_ = [ ("dwSignature", DWORD), # will be 0xFEEF04BD ("dwStrucVersion", DWORD), ("dwFileVersionMS", DWORD), ("dwFileVersionLS", DWORD), ("dwProductVersionMS", DWORD), ("dwProductVersionLS", DWORD), ("dwFileFlagsMask", DWORD), ("dwFileFlags", DWORD), ("dwFileOS", DWORD), ("dwFileType", DWORD), ("dwFileSubtype", DWORD), ("dwFileDateMS", DWORD), ("dwFileDateLS", DWORD) ] PUINT = POINTER(c_uint) LPDWORD = POINTER(DWORD) GetFileVersionInfoSizeW = windll.version.GetFileVersionInfoSizeW GetFileVersionInfoSizeW.restype = DWORD GetFileVersionInfoSizeW.argtypes = [LPCWSTR, LPDWORD] GetFileVersionInfoSize = GetFileVersionInfoSizeW # alias GetFileVersionInfoW = windll.version.GetFileVersionInfoW GetFileVersionInfoW.restype = BOOL GetFileVersionInfoW.argtypes = [LPCWSTR, DWORD, DWORD, LPVOID] GetFileVersionInfo = GetFileVersionInfoW # alias VerQueryValueW = windll.version.VerQueryValueW VerQueryValueW.restype = BOOL VerQueryValueW.argtypes = [LPCVOID, LPCWSTR, POINTER(LPVOID), PUINT] VerQueryValue = VerQueryValueW # alias filename = unicode(filename) dwLen = GetFileVersionInfoSize(filename, None) if not dwLen : raise WinError() lpData = (c_char * dwLen)() if not GetFileVersionInfo(filename, 0, sizeof(lpData), lpData): raise WinError() uLen = c_uint() lpffi = POINTER(VS_FIXEDFILEINFO)() lplpBuffer = cast(pointer(lpffi), POINTER(LPVOID)) if not VerQueryValue(lpData, u"\\", lplpBuffer, byref(uLen)): raise WinError() ffi = lpffi.contents return [int(ffi.dwFileVersionMS >> 16), int(ffi.dwFileVersionMS & 0xFFFF), int(ffi.dwFileVersionLS >> 16), int(ffi.dwFileVersionLS & 0xFFFF)]
def read_unicode_string_from_process_vm(handle, address): unicode_str_struct = UNICODE_STRING() status = NtReadVirtualMemory(handle, address, byref(unicode_str_struct), ctypes.sizeof(unicode_str_struct), None) if status != STATUS_SUCCESS: raise WindowsOperationException('Could not read process virtual' ' memory to get unicode string structure.') num_char = unicode_str_struct.Length / ctypes.sizeof(WCHAR) string = (WCHAR * num_char)() address = unicode_str_struct.Buffer status = NtReadVirtualMemory(handle, address, byref(string), ctypes.sizeof(string), None) if status != STATUS_SUCCESS: raise WindowsOperationException('Could not read process virtual' ' memory to get unicode string data.') return string.value
def ReadFile(handle, desired_bytes): """Calls kernel32.ReadFile().""" c_read = wintypes.DWORD() buff = wintypes.create_string_buffer(desired_bytes + 1) windll.kernel32.ReadFile(handle, buff, desired_bytes, wintypes.byref(c_read), None) # NULL terminate it. buff[c_read.value] = "\x00" return wintypes.GetLastError(), buff.value
def read_unicode_string_from_process_vm(handle, address): unicode_str_struct = UNICODE_STRING() status = NtReadVirtualMemory(handle, address, byref(unicode_str_struct), ctypes.sizeof(unicode_str_struct), None) if status != STATUS_SUCCESS: raise WindowsOperationException( 'Could not read process virtual' ' memory to get unicode string structure.') num_char = unicode_str_struct.Length / ctypes.sizeof(WCHAR) string = (WCHAR * num_char)() address = unicode_str_struct.Buffer status = NtReadVirtualMemory(handle, address, byref(string), ctypes.sizeof(string), None) if status != STATUS_SUCCESS: raise WindowsOperationException('Could not read process virtual' ' memory to get unicode string data.') return string.value
def kill_pid(pid): K32DLL.OpenProcess.restype = HANDLE handle = K32DLL.OpenProcess(PROCESS_TERMINATE, BOOL(False), DWORD(pid)) try: exit_status = ctypes.c_int32() K32DLL.TerminateProcess(handle, byref(exit_status)) finally: K32DLL.CloseHandle(handle)
def ReadFile(handle, desired_bytes): """Calls kernel32.ReadFile().""" c_read = wintypes.DWORD() buff = wintypes.create_string_buffer(desired_bytes + 1) windll.kernel32.ReadFile(handle, buff, desired_bytes, wintypes.byref(c_read), None) # NULL terminate it. buff[c_read.value] = '\x00' return wintypes.GetLastError(), buff.value
def hook(self): log.debug("Hook thread start") keyhook = keyboard_hook.KeyboardHook() keyhook.register_callback(self.hook_callback) msg = ctypes.MSG() while ctypes.windll.user32.GetMessageW(ctypes.byref(msg), None, 0, 0): pass log.debug("Hook thread end") keyhook.free()
def drawStringRight(font, x, y, w, h, color, text): """ (x, y) defines the bottom-right corner of the text """ r = RECT(int(x-w), int(y-h), int(x), int(y)) font.DrawTextA(None, text, -1, byref(r), DT_RIGHT | DT_NOCLIP | DT_SINGLELINE, color) # ------------- xx -------------
def getTotalMem(): if sys.platform == "win32": x = MEMORYSTATUSEX() # create the structure x.dwLength = 8 * 8 windll.kernel32.GlobalMemoryStatusEx(byref(x)) # from cytypes.wintypes return x.ullTotalPhys elif sys.platform == "darwin": return int(os.popen("/usr/sbin/sysctl -n hw.memsize").read()) else: total, free = parseMemInfo() return total * 1024
def getTotalMem (): if sys.platform=="win32": x = MEMORYSTATUSEX() # create the structure x.dwLength = 8*8; windll.kernel32.GlobalMemoryStatusEx(byref(x)) # from cytypes.wintypes return x.ullTotalPhys elif sys.platform=="darwin": return int(os.popen('/usr/sbin/sysctl -n hw.memsize').read()) else: total, free = parseMemInfo () return total * 1024
def send_key(vk=None, scan=None, extended=False, pressed=True): i = INPUT() i.union.ki.wVk = vk if scan: i.union.ki.wScan = scan else: #No scancode provided, try to get one i.union.ki.wScan = ctypes.windll.user32.MapVirtualKeyW(vk, MAPVK_VK_TO_VSC) if not pressed: i.union.ki.dwFlags |= KEYEVENTF_KEYUP if extended: i.union.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY i.type = INPUT_KEYBOARD ctypes.windll.user32.SendInput(1, ctypes.byref(i), ctypes.sizeof(INPUT))
def read_wchar_string_from_process_vm(handle, address): env_wchar = WCHAR() chars = [] while True: status = NtReadVirtualMemory(handle,address, byref(env_wchar), ctypes.sizeof(env_wchar), None) if status != STATUS_SUCCESS: raise WindowsOperationException('Failed while reading wchar' ' string from process virtual memory') address += ctypes.sizeof(env_wchar) if env_wchar.value == u'\x00': return address, u''.join(chars) chars.append(env_wchar.value)
def read_wchar_string_from_process_vm(handle, address): env_wchar = WCHAR() chars = [] while True: status = NtReadVirtualMemory(handle, address, byref(env_wchar), ctypes.sizeof(env_wchar), None) if status != STATUS_SUCCESS: raise WindowsOperationException( 'Failed while reading wchar' ' string from process virtual memory') address += ctypes.sizeof(env_wchar) if env_wchar.value == u'\x00': return address, u''.join(chars) chars.append(env_wchar.value)
def send_key(vk=None, scan=None, extended=False, pressed=True): i = INPUT() i.union.ki.wVk = vk if scan: i.union.ki.wScan = scan else: #No scancode provided, try to get one i.union.ki.wScan = ctypes.windll.user32.MapVirtualKeyW( vk, MAPVK_VK_TO_VSC) if not pressed: i.union.ki.dwFlags |= KEYEVENTF_KEYUP if extended: i.union.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY i.type = INPUT_KEYBOARD ctypes.windll.user32.SendInput(1, ctypes.byref(i), ctypes.sizeof(INPUT))
def getAvailableMem(): if sys.platform == "win32": x = MEMORYSTATUSEX() # create the structure x.dwLength = 8 * 8 windll.kernel32.GlobalMemoryStatusEx(byref(x)) # from cytypes.wintypes return x.ullAvailPhys elif sys.platform == "darwin": for line in os.popen("/usr/bin/vm_stat").readlines(): if line.startswith("Pages free"): data = line.split() return int(data[2].rstrip(".")) * 4 * 1024 return 0 else: total, free = parseMemInfo() return free * 1024
def getAvailableMem (): if sys.platform=="win32": x = MEMORYSTATUSEX() # create the structure x.dwLength = 8*8; windll.kernel32.GlobalMemoryStatusEx(byref(x)) # from cytypes.wintypes return x.ullAvailPhys elif sys.platform=="darwin": for line in os.popen('/usr/bin/vm_stat').readlines(): if line.startswith('Pages free'): data = line.split() return int(data[2].rstrip('.')) * 4 * 1024 return 0 else: total, free = parseMemInfo () return free * 1024
def SetColorKey(window, rgb_color_tuple): assert len(rgb_color_tuple) == 3 color = ctypes.c_uint((0xff000000 & 0) | (0x00ff0000 & rgb_color_tuple[0]) | (0x0000ff00 & rgb_color_tuple[1]) | (0x000000ff & rgb_color_tuple[2])) hwnd = window.Handle # make WS_EX_LAYERED if necessary. style = GetWindowLongA(hwnd, 0xffffffecL) layered_style = style | WS_EX_LAYERED if layered_style != style: SetWindowLongA(hwnd, 0xffffffecL, layered_style) SetLayeredWindowAttributes(hwnd, byref(color), 0, LWA_COLORKEY)
def decode_command_line_args(argv): command_line = kernel32.GetCommandLineW() if not command_line: return argv argc = c_int(0) argv_w = shell32.CommandLineToArgvW(command_line, byref(argc)) try: if not argv_w: return argv if argc.value <= 0: return argv start = argc.value - len(argv) ret_args = argv_w[start:argc.value] return ret_args finally: kernel32.LocalFree(argv_w)
def GetFileVersion(filename): dwLen = GetFileVersionInfoSize(filename, None) if not dwLen: raise WinError() lpData = (c_char * dwLen)() if not GetFileVersionInfo(filename, 0, sizeof(lpData), lpData): raise WinError() uLen = c_uint() lpffi = POINTER(VS_FIXEDFILEINFO)() lplpBuffer = cast(pointer(lpffi), POINTER(LPVOID)) if not VerQueryValue(lpData, u"\\", lplpBuffer, byref(uLen)): raise WinError() ffi = lpffi.contents return ( ffi.dwFileVersionMS >> 16, ffi.dwFileVersionMS & 0xFFFF, ffi.dwFileVersionLS >> 16, ffi.dwFileVersionLS & 0xFFFF, )
def list_pids(): try: EnumProcesses = ctypes.windll.psapi.EnumProcesses except AttributeError: EnumProcesses = K32DLL.EnumProcesses used = DWORD() block_size = 8192 ten_megs = 10 * 1024 * 1024 cur_size = block_size while True: processes = (DWORD * cur_size)() status = EnumProcesses(processes, ctypes.sizeof(processes), byref(used)) if not status: raise WindowsOperationException('Could not enumerate proces' 'ses') if used.value != cur_size: return processes[:used.value / ctypes.sizeof(DWORD)] cur_size += block_size if cur_size > ten_megs: raise WindowsOperationException('Unreasonable number of pro' 'cesses?')
def mouse_move(delta_x, delta_y, center_x, center_y, sensitivity): mouse_move_x = delta_x * 4.0/ sensitivity mouse_move_y = delta_y * 4.0/ sensitivity if mouse_move_x == 0 and mouse_move_y == 0: return (0, 0) fScreenWidth = windll.user32.GetSystemMetrics(0) - 1.0 # SM_CXSCREEN fScreenHeight = windll.user32.GetSystemMetrics(1) - 1.0 # SM_CYSCREEN dx = 65535.0 / fScreenWidth dy = 65535.0 / fScreenHeight fx = (center_x + mouse_move_x) * dx if not MOUSE_INVERSION: fy = (center_y + mouse_move_y) * dy else: fy = (center_y - mouse_move_y) * dy input = INPUT() input.type = INPUT_MOUSE input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE # using ceil() as recommended here: http://msdn.microsoft.com/en-us/library/ms646273%28v=VS.85%29.aspx input.mi.dx = int(ceil(fx)) input.mi.dy = int(ceil(fy)) windll.User32.SendInput(1, byref(input), sizeof(input)) return (mouse_move_x, mouse_move_y)
def list_pids(): try: EnumProcesses = ctypes.windll.psapi.EnumProcesses except AttributeError: EnumProcesses = K32DLL.EnumProcesses used = DWORD() block_size = 8192 ten_megs = 10*1024*1024 cur_size = block_size while True: processes = (DWORD*cur_size)() status = EnumProcesses(processes, ctypes.sizeof(processes), byref(used)) if not status: raise WindowsOperationException('Could not enumerate proces' 'ses') if used.value != cur_size: return processes[:used.value/ctypes.sizeof(DWORD)] cur_size += block_size if cur_size > ten_megs: raise WindowsOperationException('Unreasonable number of pro' 'cesses?')
def readlink(path): reparse_point_handle = CreateFileW(path, 0, 0, None, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, None) if reparse_point_handle == INVALID_HANDLE_VALUE: _raise_winerror( get_last_error(), 'Error opening symblic link \"%s\"'.format(path)) target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE) n_bytes_returned = DWORD() io_result = DeviceIoControl(reparse_point_handle, FSCTL_GET_REPARSE_POINT, None, 0, target_buffer, len(target_buffer), byref(n_bytes_returned), None) CloseHandle(reparse_point_handle) if not io_result: _raise_winerror( get_last_error(), 'Error reading symblic link \"%s\"'.format(path)) rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer) if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK: return _preserve_encoding(path, rdb.SymbolicLinkReparseBuffer.PrintName) elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT: return _preserve_encoding(path, rdb.MountPointReparseBuffer.PrintName) # Unsupported reparse point type _raise_winerror( ERROR_NOT_SUPPORTED, 'Error reading symblic link \"%s\"'.format(path))
def get_pid_info(pid): """Get a processes command line and environment. :raises: ProcessOperationException on error :rtype: str command line, dict of environ (str name, str value) """ # open the process so we can read its memory K32DLL.OpenProcess.restype = HANDLE handle = K32DLL.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, BOOL(False), DWORD(pid)) if not handle: raise WindowsOperationException("Could not open process [%d] " "with memory read access." % (pid, )) try: process_basic_info = PROCESS_BASIC_INFORMATION() status = NtQueryInformationProcess(handle, 0, byref(process_basic_info), ctypes.sizeof(process_basic_info), None) if status != STATUS_SUCCESS: raise WindowsOperationException('Could not get process ' 'basic info') user_process_parameter_address = read_pointer_from_process_vm( handle, process_basic_info.PebBaseAddress + (4 * ctypes.sizeof(PTR))) environ_address = read_pointer_from_process_vm( handle, user_process_parameter_address + 16 + (14 * ctypes.sizeof(PTR))) cmd_line = read_unicode_string_from_process_vm( handle, user_process_parameter_address + 16 + (12 * ctypes.sizeof(PTR))) env = read_environ_from_process_vm(handle, environ_address) return (cmd_line, env) except TypeError as exc: raise OperationException(exc.message) finally: K32DLL.CloseHandle(handle)
def draw_string_left(font, x, y, w, h, color, text): r = RECT(int(x), int(y), int(x+w), int(y-h)) font.DrawTextA(None, text, -1, byref(r), DT_LEFT | DT_NOCLIP | DT_SINGLELINE, color)
def drawStringLeft(font, x, y, w, h, color, text): """ (x, y) defines the top-left corner of the text """ r = RECT(int(x), int(y), int(x+w), int(y-h)) font.DrawTextA(None, text, -1, byref(r), DT_LEFT | DT_NOCLIP | DT_SINGLELINE, color)
def is_wow64(): wow64 = BOOL() K32DLL.IsWow64Process(K32DLL.GetCurrentProcess(), byref(wow64)) return True if wow64.value else False
def GlobalMemoryStatusEx(): x = MEMORYSTATUSEX() x.dwLength = sizeof(x) windll.kernel32.GlobalMemoryStatusEx(byref(x)) return x
def draw_string_center(font, x, y, color, text): r = RECT(int(x-150), int(y-10), int(x+150), int(y+18)) font.DrawTextA(None, text, -1, byref(r), DT_CENTER | DT_NOCLIP | DT_SINGLELINE, color)
def create_instance(clsiid, targetinterface, custom_iid=None, context=CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER): if custom_iid is None: custom_iid = targetinterface.IID return winproxy.CoCreateInstance(byref(clsiid), None, context, byref(custom_iid), byref(targetinterface))
def draw_string_right(font, x, y, w, h, color, text): r = RECT(int(x-w), int(y-h), int(x), int(y)) font.DrawTextA(None, text, -1, byref(r), DT_RIGHT | DT_NOCLIP | DT_SINGLELINE, color)
def DrawSubMenuArrow(dc, rect): from gui.native.win.winextensions import wxRectToRECT rect = wxRectToRECT(rect) _drawnativecontrol_wxMSW(dc.GetHDC(), byref(rect), controls.menuarrow, 0)
def dump_obj(o): s = string_at(byref(o), sizeof(o)) return dump(s)
def create_instance(clsiid, targetinterface, custom_iid=None): if custom_iid is None: custom_iid = targetinterface.IID return winproxy.CoCreateInstance(byref(clsiid), None, CLSCTX_INPROC_SERVER, byref(custom_iid), byref(targetinterface))