我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.wintypes.DWORD。
def window__get_thread_window_handles(thread_process_id): """ :param thread_process_id: thread process ID, as from window__get_thread_process_id :return: hwnd for all top-level windows with this thread process id. """ ret = [] def callback(hwnd, lparam): ret.append(hwnd) return True enum_win_proc = WINFUNCTYPE(c_bool, POINTER(c_int), POINTER(c_int)) windll.user32.EnumThreadWindows(wintypes.DWORD(thread_process_id), enum_win_proc(callback), None) return ret
def _wait_for_handles(handles, timeout=-1): """ Waits for multiple handles. (Similar to 'select') Returns the handle which is ready. Returns `None` on timeout. http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx """ arrtype = HANDLE * len(handles) handle_array = arrtype(*handles) ret = windll.kernel32.WaitForMultipleObjects( len(handle_array), handle_array, BOOL(False), DWORD(timeout)) if ret == WAIT_TIMEOUT: return None else: h = handle_array[ret] return h
def getvolumeinfo(path): """ Return information for the volume containing the given path. This is going to be a pair containing (file system, file system flags). """ # Add 1 for a trailing backslash if necessary, and 1 for the terminating # null character. volpath = ctypes.create_unicode_buffer(len(path) + 2) rv = GetVolumePathName(path, volpath, len(volpath)) if rv == 0: raise WinError() fsnamebuf = ctypes.create_unicode_buffer(MAX_PATH + 1) fsflags = DWORD(0) rv = GetVolumeInformation(volpath, None, 0, None, None, byref(fsflags), fsnamebuf, len(fsnamebuf)) if rv == 0: raise WinError() return (fsnamebuf.value, fsflags.value)
def WlanOpenHandle(): """ The WlanOpenHandle function opens a connection to the server. DWORD WINAPI WlanOpenHandle( _In_ DWORD dwClientVersion, _Reserved_ PVOID pReserved, _Out_ PDWORD pdwNegotiatedVersion, _Out_ PHANDLE phClientHandle ); """ func_ref = wlanapi.WlanOpenHandle func_ref.argtypes = [DWORD, c_void_p, POINTER(DWORD), POINTER(HANDLE)] func_ref.restype = DWORD negotiated_version = DWORD() client_handle = HANDLE() result = func_ref(2, None, byref(negotiated_version), byref(client_handle)) if result != ERROR_SUCCESS: raise Exception("WlanOpenHandle failed.") return client_handle
def WlanCloseHandle(hClientHandle): """ The WlanCloseHandle function closes a connection to the server. DWORD WINAPI WlanCloseHandle( _In_ HANDLE hClientHandle, _Reserved_ PVOID pReserved ); """ func_ref = wlanapi.WlanCloseHandle func_ref.argtypes = [HANDLE, c_void_p] func_ref.restype = DWORD result = func_ref(hClientHandle, None) if result != ERROR_SUCCESS: raise Exception("WlanCloseHandle failed.") return result
def WlanEnumInterfaces(hClientHandle): """ The WlanEnumInterfaces function enumerates all of the wireless LAN interfaces currently enabled on the local computer. DWORD WINAPI WlanEnumInterfaces( _In_ HANDLE hClientHandle, _Reserved_ PVOID pReserved, _Out_ PWLAN_INTERFACE_INFO_LIST *ppInterfaceList ); """ func_ref = wlanapi.WlanEnumInterfaces func_ref.argtypes = [HANDLE, c_void_p, POINTER(POINTER(WLAN_INTERFACE_INFO_LIST))] func_ref.restype = DWORD wlan_ifaces = pointer(WLAN_INTERFACE_INFO_LIST()) result = func_ref(hClientHandle, None, byref(wlan_ifaces)) if result != ERROR_SUCCESS: raise Exception("WlanEnumInterfaces failed.") return wlan_ifaces
def WlanDeleteProfile(hClientHandle, pInterfaceGuid, profileName): """ DWORD WINAPI WlanDeleteProfile( _In_ HANDLE hClientHandle, _In_ const GUID *pInterfaceGuid, _In_ LPCWSTR strProfileName, _Reserved_ PVOID pReserved ); """ func_ref = wlanapi.WlanDeleteProfile func_ref.argtypes = [HANDLE, POINTER(GUID), LPCWSTR, c_void_p] func_ref.restype = DWORD result = func_ref(hClientHandle, byref(pInterfaceGuid), profileName, None) if result != ERROR_SUCCESS: raise Exception("WlanDeleteProfile failed. error %d" % result, result) return result
def WlanConnect(hClientHandle, pInterfaceGuid, pConnectionParameters): """ The WlanConnect function attempts to connect to a specific network. DWORD WINAPI WlanConnect( _In_ HANDLE hClientHandle, _In_ const GUID *pInterfaceGuid, _In_ const PWLAN_CONNECTION_PARAMETERS pConnectionParameters, _Reserved_ PVOID pReserved ); """ func_ref = wlanapi.WlanConnect func_ref.argtypes = [HANDLE, POINTER(GUID), POINTER(WLAN_CONNECTION_PARAMETERS), c_void_p] func_ref.restype = DWORD result = func_ref(hClientHandle, pointer(pInterfaceGuid), pointer(pConnectionParameters), None) if result != ERROR_SUCCESS: raise Exception("".join(["WlanConnect failed with error ", str(result)])) return result
def process__get_exit_code(thread_pid): """ :param thread_pid: :return: None if the process hasn't exited, or the int exit code. """ hproc = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, thread_pid) try: exit_code = wintypes.DWORD() if GetExitCodeProcess(hproc, byref(exit_code)) != 0: if exit_code == STILL_ACTIVE: return None return int(exit_code) raise WinError() finally: windll.kernel32.CloseHandle(hproc)
def areAdminRightsElevated(): ''' Tells you whether current script already has Administrative rights. ''' pid = GetCurrentProcess() processToken = HANDLE() if not OpenProcessToken(pid, TOKEN_READ, ctypes.byref(processToken)): raise ctypes.WinError() try: elevated, elevatedSize = DWORD(), DWORD() if not GetTokenInformation(processToken, TokenElevation, ctypes.byref(elevated), ctypes.sizeof(elevated), ctypes.byref(elevatedSize)): raise ctypes.WinError() return bool(elevated) finally: CloseHandle(processToken)
def CreateFile(path, access=GENERIC_READ | GENERIC_WRITE, mode=0, security_attributes=NULL, creation=OPEN_EXISTING, flags=FILE_ATTRIBUTE_NORMAL, template_file = NULL): """See: CreateFile function http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx """ CreateFile_Fn = windll.kernel32.CreateFileA CreateFile_Fn.argtypes = [ wintypes.LPCSTR, # _In_ LPCTSTR lpFileName wintypes.DWORD, # _In_ DWORD dwDesiredAccess wintypes.DWORD, # _In_ DWORD dwShareMode LPSECURITY_ATTRIBUTES, # _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes wintypes.DWORD, # _In_ DWORD dwCreationDisposition wintypes.DWORD, # _In_ DWORD dwFlagsAndAttributes wintypes.HANDLE] # _In_opt_ HANDLE hTemplateFile CreateFile_Fn.restype = wintypes.HANDLE handle = wintypes.HANDLE(CreateFile_Fn(path, access, mode, security_attributes, creation, flags, template_file)) return handle
def WriteFile(file, buffer, number_of_bytes_to_write, number_of_bytes_written, overlapped): """See: WriteFile function https://msdn.microsoft.com/en-us/library/windows/desktop/aa365747(v=vs.85).aspx """ WriteFile_Fn = windll.kernel32.WriteFile WriteFile_Fn.argtypes = [ wintypes.HANDLE, # _In_ HANDLE hFile, wintypes.LPCVOID, # _In_ LPCVOID lpBuffer, wintypes.DWORD, # _In_ DWORD nNumberOfBytesToWrite, LPDWORD, # _Out_opt_ LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED # _Inout_opt_ LPOVERLAPPED lpOverlapped ] WriteFile_Fn.restype = wintypes.BOOL ret = wintypes.BOOL(WriteFile_Fn( file, buffer, number_of_bytes_to_write, number_of_bytes_written, overlapped )) return ret
def open_device(self, access=GENERIC_READ | GENERIC_WRITE, mode=0, creation=OPEN_EXISTING, flags=FILE_ATTRIBUTE_NORMAL): """See: CreateFile function http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx """ CreateFile_Fn = windll.kernel32.CreateFileA CreateFile_Fn.argtypes = [ wintypes.LPCSTR, # _In_ LPCTSTR lpFileName wintypes.DWORD, # _In_ DWORD dwDesiredAccess wintypes.DWORD, # _In_ DWORD dwShareMode LPSECURITY_ATTRIBUTES, # _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes wintypes.DWORD, # _In_ DWORD dwCreationDisposition wintypes.DWORD, # _In_ DWORD dwFlagsAndAttributes wintypes.HANDLE] # _In_opt_ HANDLE hTemplateFile CreateFile_Fn.restype = wintypes.HANDLE self.handle = wintypes.HANDLE(CreateFile_Fn('\\\\.\\' + self.name, access, mode, NULL, creation, flags, NULL))
def open_service(service_manager_handle, service_name, desired_access): """ See: OpenService function https://msdn.microsoft.com/en-us/library/windows/desktop/ms684330(v=vs.85).aspx """ OpenService_Fn = windll.Advapi32.OpenServiceA #SC_HANDLE WINAPI OpenService( OpenService_Fn.argtypes = [ # wintypes.HANDLE, # _In_ SC_HANDLE hSCManager, LPCTSTR, # _In_ LPCTSTR lpServiceName, wintypes.DWORD # _In_ DWORD dwDesiredAccess ] OpenService_Fn.restype = wintypes.SC_HANDLE handle = OpenService_Fn( service_manager_handle, service_name, desired_access ) return handle
def control_service(service_handle, control, service_status): """See: ControlService function https://msdn.microsoft.com/en-us/library/windows/desktop/ms682108(v=vs.85).aspx """ ControlService_Fn = windll.Advapi32.ControlService #BOOL WINAPI ControlService( ControlService_Fn.argtypes = [ # wintypes.SC_HANDLE, # _In_ SC_HANDLE hService, wintypes.DWORD, # _In_ DWORD dwControl, wintypes.LPCVOID # _Out_ LPSERVICE_STATUS lpServiceStatus ] ControlService_Fn.restype = wintypes.BOOL bool = ControlService_Fn( service_handle, control, service_status ) return bool
def open_sc_manager(machine_name, database_name, desired_access): """See: OpenSCManager function https://msdn.microsoft.com/en-us/library/windows/desktop/ms684323(v=vs.85).aspx """ OpenSCManager_Fn = windll.Advapi32.OpenSCManagerA #SC_HANDLE WINAPI OpenSCManager( OpenSCManager_Fn.argtypes = [ # LPCTSTR, # _In_opt_ LPCTSTR lpMachineName, LPCTSTR, # _In_opt_ LPCTSTR lpDatabaseName, wintypes.DWORD # _In_ DWORD dwDesiredAccess ] OpenSCManager_Fn.restype = wintypes.SC_HANDLE handle = OpenSCManager_Fn( machine_name, database_name, desired_access ) return handle
def FillConsoleOutputCharacter(stream_id, char, length, start): handle = handles[stream_id] char = c_char(char.encode()) length = wintypes.DWORD(length) num_written = wintypes.DWORD(0) # Note that this is hard-coded for ANSI (vs wide) bytes. success = _FillConsoleOutputCharacterA( handle, char, length, start, byref(num_written)) return num_written.value
def FillConsoleOutputAttribute(stream_id, attr, length, start): ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )''' handle = handles[stream_id] attribute = wintypes.WORD(attr) length = wintypes.DWORD(length) num_written = wintypes.DWORD(0) # Note that this is hard-coded for ANSI (vs wide) bytes. return _FillConsoleOutputAttribute( handle, attribute, length, start, byref(num_written))
def readlink(path): # Make sure the path exists and is actually a junction if not isjunction(path): raise Exception("%s does not exist or is not a junction" % path) hlink = CreateFile(path, fs.GENERIC_READ, fs.FILE_SHARE_READ, None, fs.OPEN_EXISTING, fs.FILE_FLAG_OPEN_REPARSE_POINT | fs.FILE_FLAG_BACKUP_SEMANTICS, None) if hlink == fs.INVALID_HANDLE_VALUE: raise WinError() try: (junctioninfo, infolen) = new_junction_reparse_buffer() dummy = DWORD(0) res = DeviceIoControl( hlink, FSCTL_GET_REPARSE_POINT, None, 0, byref(junctioninfo), infolen, byref(dummy), None) if res == 0: raise WinError() return unparsed_unconvert(junctioninfo.SubstituteNameBuffer) finally: CloseHandle(hlink)
def FillConsoleOutputCharacter(stream_id, char, length, start): handle = handles[stream_id] char = c_char(char) length = wintypes.DWORD(length) num_written = wintypes.DWORD(0) # Note that this is hard-coded for ANSI (vs wide) bytes. success = _FillConsoleOutputCharacterA( handle, char, length, start, byref(num_written)) return num_written.value
def WriteFile(handle, data, ol = None): c_written = DWORD() success = ctypes.windll.kernel32.WriteFile(handle, ctypes.create_string_buffer(encode(data)), len(data), ctypes.byref(c_written), ol) return ctypes.windll.kernel32.GetLastError(), c_written.value
def ReadFile(handle, desired_bytes, ol = None): c_read = DWORD() buffer = ctypes.create_string_buffer(desired_bytes+1) success = ctypes.windll.kernel32.ReadFile(handle, buffer, desired_bytes, ctypes.byref(c_read), ol) buffer[c_read.value] = null_byte return ctypes.windll.kernel32.GetLastError(), decode(buffer.value)
def PeekNamedPipe(handle, desired_bytes): c_avail = DWORD() c_message = DWORD() if desired_bytes > 0: c_read = DWORD() buffer = ctypes.create_string_buffer(desired_bytes+1) success = ctypes.windll.kernel32.PeekNamedPipe(handle, buffer, desired_bytes, ctypes.byref(c_read), ctypes.byref(c_avail), ctypes.byref(c_message)) buffer[c_read.value] = null_byte return decode(buffer.value), c_avail.value, c_message.value else: success = ctypes.windll.kernel32.PeekNamedPipe(handle, None, desired_bytes, None, ctypes.byref(c_avail), ctypes.byref(c_message)) return "", c_avail.value, c_message.value
def hotpatch(source, destination): source = cast(source, c_void_p).value destination = cast(destination, c_void_p).value old = DWORD() if windll.kernel32.VirtualProtect(source - 5, 8, PAGE_EXECUTE_READWRITE, byref(old)): try: written = c_size_t() jmp_code = struct.pack('<BI', 0xE9, (destination - source) & 0xFFFFFFFF) windll.kernel32.WriteProcessMemory(-1, source - 5, cast(jmp_code, c_char_p), len(jmp_code), byref(written)) windll.kernel32.WriteProcessMemory(-1, source, cast(struct.pack('<H', 0xF9EB), c_char_p), 2, byref(written)) finally: windll.kernel32.VirtualProtect(source - 5, 8, old, byref(old)) return source + 2
def unhotpatch(source): source = cast(source, c_void_p).value old = DWORD() if windll.kernel32.VirtualProtect(source, 2, PAGE_EXECUTE_READWRITE, byref(old)): try: written = c_size_t() windll.kernel32.WriteProcessMemory(-1, source, cast(b'\x8B\xFF', c_char_p), 2, byref(written)) finally: windll.kernel32.VirtualProtect(source, 2, old, byref(old))
def KerberosInit(): hLsaConnection = HANDLE() status = DWORD(0) LPTR = (0x0000 | 0x0040) MICROSOFT_KERBEROS_NAME_A = PWSTR() MICROSOFT_KERBEROS_NAME_A = windll.kernel32.LocalAlloc(LPTR, len("Kerberos") + 1) memmove(MICROSOFT_KERBEROS_NAME_A, "Kerberos", len("Kerberos")) status = LsaConnectUntrusted(byref(hLsaConnection)) if status != STATUS_SUCCESS: print "LsaConnectUntrusted, cannot get LSA handle, error %d " % status windll.kernel32.LocalFree(MICROSOFT_KERBEROS_NAME_A) return None, None kerberosPackageName = UNICODE_STRING() kerberosPackageName.Length = USHORT(8) kerberosPackageName.MaximumLength = USHORT(9) kerberosPackageName.Buffer = MICROSOFT_KERBEROS_NAME_A dwKerberosAuthenticationPackageId = DWORD(0) status = LsaLookupAuthenticationPackage(hLsaConnection, byref(kerberosPackageName), byref(dwKerberosAuthenticationPackageId)) windll.kernel32.LocalFree(MICROSOFT_KERBEROS_NAME_A) if status == STATUS_SUCCESS: return hLsaConnection, dwKerberosAuthenticationPackageId else: return None, None
def WlanScan(hClientHandle, pInterfaceGuid, ssid=""): """ The WlanScan function requests a scan for available networks on the indicated interface. DWORD WINAPI WlanScan( _In_ HANDLE hClientHandle, _In_ const GUID *pInterfaceGuid, _In_opt_ const PDOT11_SSID pDot11Ssid, _In_opt_ const PWLAN_RAW_DATA pIeData, _Reserved_ PVOID pReserved ); """ func_ref = wlanapi.WlanScan func_ref.argtypes = [HANDLE, POINTER(GUID), POINTER(DOT11_SSID), POINTER(WLAN_RAW_DATA), c_void_p] func_ref.restype = DWORD if ssid: length = len(ssid) if length > DOT11_SSID_MAX_LENGTH: raise Exception("SSIDs have a maximum length of 32 characters.") # data = tuple(ord(char) for char in ssid) data = ssid dot11_ssid = byref(DOT11_SSID(length, data)) else: dot11_ssid = None # TODO: Support WLAN_RAW_DATA argument. result = func_ref(hClientHandle, byref(pInterfaceGuid), dot11_ssid, None, None) if result != ERROR_SUCCESS: raise Exception("WlanScan failed.") return result
def WlanGetAvailableNetworkList(hClientHandle, pInterfaceGuid): """ The WlanGetAvailableNetworkList function retrieves the list of available networks on a wireless LAN interface. DWORD WINAPI WlanGetAvailableNetworkList( _In_ HANDLE hClientHandle, _In_ const GUID *pInterfaceGuid, _In_ DWORD dwFlags, _Reserved_ PVOID pReserved, _Out_ PWLAN_AVAILABLE_NETWORK_LIST *ppAvailableNetworkList ); """ func_ref = wlanapi.WlanGetAvailableNetworkList func_ref.argtypes = [HANDLE, POINTER(GUID), DWORD, c_void_p, POINTER(POINTER(WLAN_AVAILABLE_NETWORK_LIST))] func_ref.restype = DWORD wlan_available_network_list = pointer(WLAN_AVAILABLE_NETWORK_LIST()) result = func_ref(hClientHandle, byref(pInterfaceGuid), 0, None, byref(wlan_available_network_list)) if result != ERROR_SUCCESS: raise Exception("WlanGetAvailableNetworkList failed.") return wlan_available_network_list
def WlanGetProfileList(hClientHandle, pInterfaceGuid): """ The WlanGetProfileList function retrieves the list of profiles in preference order. DWORD WINAPI WlanGetProfileList( _In_ HANDLE hClientHandle, _In_ const GUID *pInterfaceGuid, _Reserved_ PVOID pReserved, _Out_ PWLAN_PROFILE_INFO_LIST *ppProfileList ); """ func_ref = wlanapi.WlanGetProfileList func_ref.argtypes = [HANDLE, POINTER(GUID), c_void_p, POINTER(POINTER(WLAN_PROFILE_INFO_LIST))] func_ref.restype = DWORD wlan_profile_info_list = pointer(WLAN_PROFILE_INFO_LIST()) result = func_ref(hClientHandle, byref(pInterfaceGuid), None, byref(wlan_profile_info_list)) if result != ERROR_SUCCESS: raise Exception("WlanGetProfileList failed.") return wlan_profile_info_list
def WlanGetProfile(hClientHandle, pInterfaceGuid, profileName): """ The WlanGetProfile function retrieves all information about a specified wireless profile. DWORD WINAPI WlanGetProfile( _In_ HANDLE hClientHandle, _In_ const GUID *pInterfaceGuid, _In_ LPCWSTR strProfileName, _Reserved_ PVOID pReserved, _Out_ LPWSTR *pstrProfileXml, _Inout_opt_ DWORD *pdwFlags, _Out_opt_ PDWORD pdwGrantedAccess ); """ func_ref = wlanapi.WlanGetProfile func_ref.argtypes = [HANDLE, POINTER(GUID), LPCWSTR, c_void_p, POINTER(LPWSTR), POINTER(DWORD), POINTER(DWORD)] func_ref.restype = DWORD pdw_granted_access = DWORD() xml = LPWSTR() flags = DWORD(WLAN_PROFILE_GET_PLAINTEXT_KEY) result = func_ref(hClientHandle, byref(pInterfaceGuid), profileName, None, byref(xml), byref(flags), byref(pdw_granted_access)) if result != ERROR_SUCCESS: raise Exception("WlanGetProfile failed.") return xml
def WlanQueryInterface(hClientHandle, pInterfaceGuid, OpCode): """ DWORD WINAPI WlanQueryInterface( _In_ HANDLE hClientHandle, _In_ const GUID *pInterfaceGuid, _In_ WLAN_INTF_OPCODE OpCode, _Reserved_ PVOID pReserved, _Out_ PDWORD pdwDataSize, _Out_ PVOID *ppData, _Out_opt_ PWLAN_OPCODE_VALUE_TYPE pWlanOpcodeValueType ); """ func_ref = wlanapi.WlanQueryInterface #TODO: Next two lines sketchy due to incomplete implementation. opcode_name = WLAN_INTF_OPCODE_DICT[OpCode.value] return_type = WLAN_INTF_OPCODE_TYPE_DICT[opcode_name] func_ref.argtypes = [HANDLE, POINTER(GUID), WLAN_INTF_OPCODE, c_void_p, POINTER(DWORD), POINTER(POINTER(return_type)), POINTER(WLAN_OPCODE_VALUE_TYPE)] func_ref.restype = DWORD pdwDataSize = DWORD() ppData = pointer(return_type()) pWlanOpcodeValueType = WLAN_OPCODE_VALUE_TYPE() result = func_ref(hClientHandle, byref(pInterfaceGuid), OpCode, None, pdwDataSize, ppData, pWlanOpcodeValueType) if result != ERROR_SUCCESS: raise Exception("WlanQueryInterface failed.") return ppData