### Example: List all device classes Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/sample.html Run this script with no arguments to list all available device classes on the system. The output shows the name and GUID for each class. ```bash $ python64 device_manager\enum_devices.py --no-print-devices Namespace(clsfilter=None, no_print_devices=True, print_resources=False) .... ``` -------------------------------- ### start Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/event_trace.html Starts the ETW tracing session. ```APIDOC ## start(flags=0, mode=0) ### Description Starts the tracing session. ### Parameters - **flags** (int, optional) - Flags to control tracing behavior. Defaults to 0. - **mode** (int, optional) - Mode for the trace log file. Defaults to 0. ``` -------------------------------- ### VirtualSymbolHandler Usage Example Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/debug/symbols.html Demonstrates loading a DLL, accessing a specific symbol by name, and retrieving related symbols by offset. Shows how to inspect symbol properties like start address, displacement, and name. ```python >>> sh = windows.debug.symbols.VirtualSymbolHandler() >>> mod = sh.load_file(r"c:\windows\system32\kernelbase.dll") >>> sym1 = sh["kernelbase!CreateFileW"] >>> sym2 = sh[int(sym1) + 3] >>> sym2 >>> hex(sym2.start) '0x100f20b0L' >>> hex(sym2.addr) '0x100f20b3L' >>> hex(sym2.displacement) '0x3L' >>> str(sym2) 'kernelbase!CreateFileW+0x3' ``` -------------------------------- ### Install and Register a Windows Service in Python Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/sample.html Use this command to install and register a Python script as a Windows service. Ensure you are in an administrator command prompt. ```bash (cmd-admin) py .\service\python_service.py --install Registering service as : ``` -------------------------------- ### StartServicing Source: https://github.com/hakril/pythonforwindows/blob/master/ctypes_generation/definitions/com/propertysystem/IPackageDebugSettings.txt Starts servicing for a specified package. ```APIDOC ## StartServicing ### Description Starts servicing for a specified package. ### Method Call ### Parameters #### Path Parameters - **packageFullName** (LPCWSTR) - Required - The full name of the package to start servicing. ### Response #### Success Response (HRESULT) Indicates success or failure of the operation. #### Response Example ``` HRESULT ``` ``` -------------------------------- ### ALPC Server Process Initialization Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/sample.html Starts the ALPC server process as a separate multiprocessing.Process. This is the entry point for running the example, ensuring the server is ready before the client attempts to connect. ```python if __name__ == "__main__": proc = multiprocessing.Process(target=full_alpc_server, args=()) proc.start() import time; time.sleep(0.5) alpc_client() import time; time.sleep(0.5) print("BYE") proc.terminate() ``` -------------------------------- ### Start a Windows Service Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/service.html Starts the specified service. Optionally accepts a list of arguments to pass to the service upon startup. ```python nbelt = 0 if args is not None: if isinstance(args, windows.pycompat.anybuff): args = [args] nbelt = len(args) args = (gdef.LPWSTR * (nbelt))(*args) return windows.winproxy.StartServiceW(self, nbelt, args) ``` -------------------------------- ### Service.start Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/service.html Starts the specified service. ```APIDOC ## start ### Description Starts the service. ### Parameters - **args** (list of str, optional): A list of arguments to pass to the service when starting. Defaults to None. ### Example ```python service.start(['arg1', 'arg2']) ``` ``` -------------------------------- ### Start a Windows Service Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/sample.html Command to start a registered Windows service. This is useful for testing service functionality. ```bash (cmd-admin) sc.exe start PFW_DEMO SERVICE_NAME: PFW_DEMO TYPE : 10 WIN32_OWN_PROCESS STATE : 2 START_PENDING (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x7d0 PID : 21132 FLAGS : ``` -------------------------------- ### StartTraceA Source: https://github.com/hakril/pythonforwindows/blob/master/docs/source/winfuncs_generated.rst Starts a trace session. ```APIDOC ## StartTraceA ### Description Starts a trace session. This function creates and starts a trace session, allocating resources and beginning the collection of trace data. This is the ANSI version. ### Parameters - **TraceHandle** (TRACEHANDLE*) - A pointer to a TRACEHANDLE variable that receives a handle to the trace session. This handle is used in subsequent calls to control and stop the trace session. - **InstanceName** (LPSTR) - The name of the trace session instance. This name must be unique on the system. - **Properties** (PEVENT_TRACE_PROPERTIES) - A pointer to an EVENT_TRACE_PROPERTIES structure that specifies the properties of the trace session, such as buffer size, maximum buffers, and logging mode. ``` -------------------------------- ### Example: NtQueryInformationProcess 32-bit to 64-bit Call Source: https://github.com/hakril/pythonforwindows/blob/master/docs/source/internals.rst This is an example of a specific SysWOW64 API proxy for NtQueryInformationProcess, demonstrating how to query process information in a 64-bit process from a 32-bit environment. ```python NtQueryInformationProcess_32_to_64 = Syswow64ApiProxy(windows.winproxy.NtQueryInformationProcess) ``` -------------------------------- ### Example: NtQueryVirtualMemory 32-bit to 64-bit Call Source: https://github.com/hakril/pythonforwindows/blob/master/docs/source/internals.rst This is an example of a specific SysWOW64 API proxy for NtQueryVirtualMemory, demonstrating how to query memory information in a 64-bit process from a 32-bit environment. ```python NtQueryVirtualMemory_32_to_64 = Syswow64ApiProxy(windows.winproxy.NtQueryVirtualMemory) ``` -------------------------------- ### ETW Provider Enumeration Output Example Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/sample.rst.txt This is an example output from enumerating ETW providers, showing the GUID, name, and flags associated with each provider. ```text {'guid': '65534-0-1234', 'name': 'Microsoft-Windows-Security-Auditing', 'flags': 1} {'guid': '65534-0-5678', 'name': 'Microsoft-Windows-Kernel-General', 'flags': 1} ``` -------------------------------- ### Debugger: on_setup Callback Sample Source: https://github.com/hakril/pythonforwindows/blob/master/docs/source/sample.rst This example shows how to define and use the on_setup callback function within the Debugger class. This function is executed when the debugger is set up. ```python from windows.debug import Debugger def my_setup_callback(debugger): print("Debugger setup complete!") debugger = Debugger() debugger.on_setup.add(my_setup_callback) debugger.load_debugger() debugger.attach() ``` -------------------------------- ### Get Thread Start Address Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/process.html Retrieves the starting address of the thread. Handles cross-architecture calls, including WOW64 and potential x86 on ARM64 limitations. ```python if windows.current_process.bitness == 32 and self.owner.bitness == 64: if windows.current_process._is_x86_on_arm64: raise NotImplementedError("Crossing heaven gate x86 -> arm64 not implemented") res = ULONGLONG() windows.syswow64.NtQueryInformationThread_32_to_64(self.handle, ThreadQuerySetWin32StartAddress, byref(res), ctypes.sizeof(res)) return res.value res_size = max(self.owner.bitness, windows.current_process.bitness) if res_size == 32: res = ULONG() else: res = ULONGLONG() winproxy.NtQueryInformationThread(self.handle, ThreadQuerySetWin32StartAddress, byref(res), ctypes.sizeof(res)) return res.value ``` -------------------------------- ### Example: List Display devices with resources Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/sample.html This command lists devices in the 'Display' class and prints their allocated resources, such as memory ranges and private resources. ```bash $ python64 device_manager\enum_devices.py --class Display --print-resources Namespace(clsfilter='Display', no_print_devices=False, print_resources=True) * * * * * ``` -------------------------------- ### Start EtwTrace Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/event_trace.html Starts an ETW trace session. Configures properties like buffer count, enable flags, and log file mode. If a GUID is provided, it's used; otherwise, it's obtained after starting. ```python def start(self, flags=0, mode=0): """Start the tracing""" prop = EventTraceProperties.create() prop.NumberOfBuffers = 42 prop.EnableFlags = flags prop.LogFileMode = mode if self.guid: prop.Wnode.Guid = self.guid if self.logfile: prop.logfile = self.logfile if self.name: # Base REAL_TIME on option ? name presence ? logfile presence ? prop.LogFileMode |= gdef.EVENT_TRACE_REAL_TIME_MODE handle = gdef.TRACEHANDLE() windows.winproxy.StartTraceW(handle, self.name, prop) if not self.guid: self.guid = prop.Wnode.Guid self.handle = handle ``` -------------------------------- ### Example: NtGetContextThread 32-bit to 64-bit Call Source: https://github.com/hakril/pythonforwindows/blob/master/docs/source/internals.rst This is an example of a specific SysWOW64 API proxy for NtGetContextThread, demonstrating how to get the context of a thread in a 64-bit process from a 32-bit environment. ```python NtGetContextThread_32_to_64 = Syswow64ApiProxy(windows.winproxy.NtGetContextThread) ``` -------------------------------- ### Debugger with on_setup Callback Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/sample.html Demonstrates how to use the `on_setup` method in a custom debugger class. This method is called once after the debugger attaches to the process, allowing for initial setup actions. ```python import windows.debug class MySetupDebugger(windows.debug.Debugger): def on_setup(self): super(MySetupDebugger, self).on_setup() print("Setup called: {0}".format(self.current_process)) def on_exception(self, exc): print("Exception: {0}".format(exc.ExceptionRecord.ExceptionCode)) def on_exit_process(self, evt): print("Process exit: {0}".format(self.current_process)) class SimpleDebugger(windows.debug.Debugger): def on_exception(self, exc): print("Exception: {0}".format(exc.ExceptionRecord.ExceptionCode)) def on_exit_process(self, evt): print("Process exit: {0}".format(self.current_process)) print("== With on_setup ==") dbg = MySetupDebugger.debug(r"c:\windows\system32\whoami.exe") dbg.loop() print("\n== Without on_setup ==") dbg = SimpleDebugger.debug(r"c:\windows\system32\whoami.exe") dbg.loop() ``` -------------------------------- ### windows.com.init() Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/com.html Initializes the COM subsystem. ```APIDOC ## windows.com.init() ### Description Initializes the COM subsystem. This function must be called before using other COM functions. ### Method `init()` ### Parameters None ### Response None ``` -------------------------------- ### EtwManager Existing Providers Enumeration Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/event_trace.html Retrieves a list of all currently existing ETW providers on the system. It uses EnumerateTraceGuidsEx with TraceGuidQueryList to get the provider GUIDs. ```python @property def providers(self): """The list of currently existing ETW providers. :type: [:class:`TraceProvider`] -- A list of ETW providers """ buffer = windows.utils.BUFFER(gdef.GUID, 0x1000)() size = gdef.DWORD() windows.winproxy.EnumerateTraceGuidsEx(gdef.TraceGuidQueryList, None, 0, buffer, buffer.real_size, size) return [TraceProvider(g) for g in buffer[:size.value // ctypes.sizeof(gdef.GUID)]] ``` -------------------------------- ### Get Local Information with Call Trace Activity Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/rpc/client.html Retrieves local information with a specified call trace activity GUID and client thread ID. ```python return gdef.LOCALTHIS32(callTraceActivity=gdef.GUID.from_string("42424242-4242-4242-4242-424242424242"), dwClientThread = windows.current_thread.tid) ``` -------------------------------- ### Example: List Processor devices with attributes Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/sample.html This command lists devices belonging to the 'Processor' class and displays specific attributes like name, manufacturer, device object name, and location paths. ```bash $ python64 device_manager\enum_devices.py --class Processor --attributes name manufacturer device_object_name location_paths Namespace(attributes=["name", "manufacturer", "device_object_name", "location_paths"], clsfilter='Processor', no_print_devices=False, print_resources=False) * Attributes: * name=Intel(R) Core(TM) i5-6600 CPU @ 3.30GHz * manufacturer=Intel * device_object_name=\Device\00000017 * location_paths=[u'ACPI(_SB_)#ACPI(CPU0)'] * Attributes: * name=Intel(R) Core(TM) i5-6600 CPU @ 3.30GHz * manufacturer=Intel * device_object_name=\Device\00000018 * location_paths=[u'ACPI(_SB_)\\#ACPI(CPU1)'] * Attributes: * name=Intel(R) Core(TM) i5-6600 CPU @ 3.30GHz * manufacturer=Intel * device_object_name=\Device\00000019 * location_paths=[u'ACPI(_SB_)#ACPI(CPU2)'] * Attributes: * name=Intel(R) Core(TM) i5-6600 CPU @ 3.30GHz * manufacturer=Intel * device_object_name=\Device\0000001a * location_paths=[u'ACPI(_SB_)#ACPI(CPU3)'] ``` -------------------------------- ### windows.com.init() Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/com.html Initializes the COM subsystem with default parameters. ```APIDOC ## windows.com.init() ### Description Initializes COM with some default parameters. ### Method `init()` ### Parameters None ``` -------------------------------- ### init() Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/com.html Initializes the COM library for the current thread and apartment. ```APIDOC ## init() ### Description Initializes the COM library with default parameters. It attempts to call `winproxy.CoInitializeEx` and handles potential `WindowsError`. ### Returns - `int`: The HRESULT of `CoInitializeEx` if it failed, otherwise 0. ``` -------------------------------- ### Get WMI Property Names Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/wmi.html Retrieves a list of property names for the current WMI object. System properties (those starting with '_') are excluded by default. Use system_properties=True to include them. ```python def get_properties(self, system_properties=False): """Return the list of properties names available for the current object. If `system_properties` is `False` property names begining with `_` are ignored. :returns: [:class:`str`] -- A list of string .. note: About system properties: https://docs.microsoft.com/en-us/windows/desktop/wmisdk/wmi-system-properties """ res = POINTER(windows.com.SafeArray)() x = ctypes.pointer(res) self.GetNames(None, 0, None, cast(x, POINTER(POINTER(gdef.SAFEARRAY)))) # need to free the safearray / unlock ? properties = [p for p in res[0].to_list(BSTR) if system_properties or (not p.startswith("_"))] return properties ``` -------------------------------- ### Setting Up and Running the Debugger Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/sample.html This code initializes the debugger, allocates memory, injects x86 assembly code, sets up a memory breakpoint, and starts the debugging loop. Ensure the target process is created with DEBUG_PROCESS flag. ```python calc = windows.test.pop_proc_32(dwCreationFlags=DEBUG_PROCESS) d = MyDebugger(calc) code = calc.virtual_alloc(0x1000) data = calc.virtual_alloc(0x1000) injected = x86.MultipleInstr() injected += x86.Mov("EAX", 0) injected += x86.Mov(x86.deref(data), "EAX") injected += x86.Add("EAX", 4) injected += x86.Mov(x86.deref(data + 4), "EAX") injected += x86.Add("EAX", 8) injected += x86.Mov(x86.deref(data + 8), "EAX") injected += x86.Nop() injected += x86.Nop() injected += x86.Ret() calc.write_memory(code, injected.get_code()) d.add_bp(SingleStepOnWrite(data, size=8, events="W")) calc.create_thread(code, 0) d.loop() ``` -------------------------------- ### on_setup Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/debug.html Callback function executed on the first breakpoint event. Allows for setting up hooks or interacting with the debugee when it's ready. If overridden, on_exception will not be called for the first breakpoint event. ```APIDOC ## on_setup ### Description Called on the first breakpoint event occurring in the debugger. This callback allows setting up hooks or interacting with the debugee when ready. * If `on_setup()` is overridden by a subclass, it will be called and `on_exception()` will NOT be called for this event (first BP). * If `on_setup()` is not defined, the first BP will trigger an `on_exception()`. Note: See sample [on_setup](sample.html#sample-debugger-on-setup) ### Parameters This method does not take any parameters. ``` -------------------------------- ### WMI Queries with SQL-style SELECT Source: https://context7.com/hakril/pythonforwindows/llms.txt Perform WMI queries using SQL-like SELECT statements across any namespace. Examples include retrieving all running processes, filtering for specific processes by PID, and getting operating system information. ```python import windows wmi = windows.system.wmi # Select all running processes processes = wmi.select("Win32_Process") print(processes[0]["Name"]) # 'System Idle Process' print(processes[0]["ProcessId"]) # 0 # Filter to find a specific process my_proc = [p for p in wmi.select("Win32_Process") if int(p["Handle"]) == windows.current_process.pid][0] print(my_proc["CommandLine"]) # '"C:\\Python311\\python.exe"' print(my_proc["HandleCount"]) # 123 # Operating system info os_info = wmi.select("Win32_OperatingSystem")[0] print(os_info["Caption"]) # 'Microsoft Windows 10 Pro' print(os_info["BuildNumber"]) # '19045' ``` -------------------------------- ### SetupDiEnumDeviceInterfaces Source: https://github.com/hakril/pythonforwindows/blob/master/ctypes_generation/definitions/functions/setupapi.txt Enumerates the device interfaces present in a device information set. ```APIDOC ## SetupDiEnumDeviceInterfaces ### Description Enumerates the device interfaces present in a device information set. Call this function repeatedly to retrieve all device interface elements. ### Parameters - **DeviceInfoSet** (_In_ HDEVINFO) - Handle to the device information set that contains the device interfaces. - **DeviceInfoData** (_In_opt_ PSP_DEVINFO_DATA) - Optional pointer to a structure that specifies the device information element for which to retrieve interface information. If NULL, the function retrieves interfaces for all devices in the set. - **InterfaceClassGuid** (_In_ CONST GUID *) - Pointer to the GUID of the device interface class to enumerate. - **MemberIndex** (_In_ DWORD) - Index of the device interface to retrieve. This should be zero on the first call. - **DeviceInterfaceData** (_Out_ PSP_DEVICE_INTERFACE_DATA) - Pointer to a structure that receives information about the enumerated device interface. ### Return Value Returns TRUE if the function succeeds and retrieves a device interface element, FALSE otherwise. If there are no more device interface elements, the function returns FALSE and GetLastError returns ERROR_NO_MORE_ITEMS. ``` -------------------------------- ### WMI Create Process Sample Source: https://github.com/hakril/pythonforwindows/blob/master/docs/source/sample.rst This example shows how to use WMI to create a new process on a local or remote machine. It requires specifying the command line for the process to be created. ```python from windows.wmi import WMIConnection conn = WMIConnection() # Example: Create a notepad process command_line = 'notepad.exe' result = conn.create_process(command_line) if result.return_value == 0: print(f"Process '{command_line}' created successfully.") else: print(f"Failed to create process. Return value: {result.return_value}") ``` -------------------------------- ### Service.start Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/service.html Starts the service. Accepts an optional list of string arguments. ```APIDOC ## start ### Description Start the service. ### Method (Implicitly a method call, not HTTP) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **args** (list[str]) - Optional - A list of string arguments to pass to the service start command. ``` -------------------------------- ### GUID Structure Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/winstructs_generated.rst.txt Represents a Globally Unique Identifier (GUID). ```APIDOC ## _GUID ### Description Represents a Globally Unique Identifier (GUID). ### Attributes - **Data1** (`ULONG`): The first part of the GUID. - **Data2** (`USHORT`): The second part of the GUID. - **Data3** (`USHORT`): The third part of the GUID. ``` -------------------------------- ### Get Process Information with PythonForWindows Source: https://github.com/hakril/pythonforwindows/blob/master/README.md Demonstrates how to retrieve basic process information, including bitness, security token integrity, and details about loaded modules and their exports. Also shows how to access thread contexts. ```python >>> import windows >>> windows.current_process.bitness 32 >>> windows.current_process.token.integrity SECURITY_MANDATORY_MEDIUM_RID(0x2000) >>> proc = [p for p in windows.system.processes if p.name == "notepad.exe"][0] >>> proc >>> proc.bitness 64 >>> proc.peb.modules[:3] [, , ] >>> k32 = proc.peb.modules[2] >>> hex(k32.pe.exports["CreateFileW"]) '0x7ffee6761550L' >>> proc.threads[0] >>> hex(proc.threads[0].context.Rip) '0x7ffee68b54b0L' ``` -------------------------------- ### Unpack NDR Guid Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/rpc/ndr.html Unpacks 16 bytes from the stream into an NDR GUID object. ```python @classmethod def unpack(self, stream): rawguid = stream.partial_unpack("16s")[0] return gdef.IID.from_buffer_copy(rawguid) ``` -------------------------------- ### WinThread.start_address Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/process.html Retrieves the starting address of the thread. Handles cross-bitness scenarios for retrieving the start address. ```APIDOC ## WinThread.start_address ### Description Gets the start address of the thread. ### Type :class:`int` ### Raises NotImplementedError: If crossing from x86 to ARM64 is attempted. ``` -------------------------------- ### VirtualAlloc Example Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/winproxy.rst.txt Demonstrates how to use the VirtualAlloc function from the windows.winproxy module, including calling with ordinal and keyword arguments, and handling errors. ```APIDOC ## VirtualAlloc ### Description Allocates memory in the virtual address space of the calling process. ### Method `windows.winproxy.VirtualAlloc` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import windows # Ordinal arguments address1 = windows.winproxy.VirtualAlloc(0, 0x1000) print(address1) # Keyword arguments address2 = windows.winproxy.VirtualAlloc(dwSize=0x1000) print(address2) # Example of calling without a needed parameter (will raise TypeError) # windows.winproxy.VirtualAlloc() # Example of an invalid size causing an error (will raise WinproxyError) # windows.winproxy.VirtualAlloc(dwSize=0xffffffff) ``` ### Response #### Success Response (200) - **address** (int) - The base address of the allocated region of pages. #### Response Example ```json { "address": 34537472 } ``` ### Error Handling - **TypeError**: Raised when a mandatory parameter like `dwSize` is not provided. - **WinproxyError**: Raised when the Windows API call fails (e.g., due to insufficient storage). ``` -------------------------------- ### Pack NDR Guid Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/rpc/ndr.html Packs a GUID object or string into NDR format (16 bytes). ```python @classmethod def pack(cls, data): if not isinstance(data, gdef.IID): data = gdef.IID.from_string(data) return bytes(bytearray(data)) ``` -------------------------------- ### Install and Uninstall Windows Service Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/sample.html Functions to install and uninstall the demo service. The install function registers the service with the Windows service control manager, specifying the executable path and description. The uninstall function removes the service. ```python def install_demo_service(): path = "{executable} {pyfile} --run".format(executable=sys.executable, pyfile=__file__) print("Registering service <{0}> as : <{1}>".format(SERVICE_NAME, path)) newservice = windows.system.services.create( name=SERVICE_NAME, description=SERVICE_DESCRIPTION, access=gdef.SERVICE_ALL_ACCESS, type=gdef.SERVICE_WIN32_OWN_PROCESS, start=gdef.SERVICE_DEMAND_START, path=path, user=None ) print(newservice) return def uninstall_demo_service(): print("Deleting service") print(windows.system.services[SERVICE_NAME].delete()) ``` -------------------------------- ### SetupDiEnumDeviceInfo Source: https://github.com/hakril/pythonforwindows/blob/master/ctypes_generation/definitions/functions/setupapi.txt Enumerates the devices present in a device information set. ```APIDOC ## SetupDiEnumDeviceInfo ### Description Enumerates the devices present in a device information set. Call this function repeatedly to retrieve all device information elements. ### Parameters - **DeviceInfoSet** (_In_ HDEVINFO) - Handle to the device information set to enumerate. - **MemberIndex** (_In_ DWORD) - Index of the device information element to retrieve. This should be zero on the first call. - **DeviceInfoData** (_Out_ PSP_DEVINFO_DATA) - Pointer to a structure that receives information about the enumerated device. ### Return Value Returns TRUE if the function succeeds and retrieves a device information element, FALSE otherwise. If there are no more device information elements, the function returns FALSE and GetLastError returns ERROR_NO_MORE_ITEMS. ``` -------------------------------- ### WMI: Create Process Example Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/sample.rst.txt Shows how to use WMI to create a new process on a local or remote machine. This is a powerful tool for process automation. ```python from windows.wmi import WMIConnection # Example: Create a process using WMI # wmi = WMIConnection() # command = "notepad.exe" # wmi.create_process(command) ``` -------------------------------- ### EventTraceProperties GUID and ID Access Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/event_trace.html Provides properties to access the GUID and ID of an Event Trace session. ```python @property def guid(self): """The GUID of the Event Trace session (see ```Wnode.Guid```)`""" return self.Wnode.Guid @property def id(self): ``` -------------------------------- ### _STARTUPINFOEXW Structure Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/winstructs_generated.rst.txt Contains information used by the CreateProcess function to start a process. This is the Unicode version and includes extended attributes. ```APIDOC ## _STARTUPINFOEXW ### Description Contains information used by the CreateProcess function to start a process. This is the Unicode version and includes extended attributes. ### Attributes - **StartupInfo** (STARTUPINFOW) - A STARTUPINFOW structure that specifies the window station, standard handles, and appearance of the main window for the process. - **lpAttributeList** (LPPROC_THREAD_ATTRIBUTE_LIST) - A pointer to a list of attributes that can be specified for a new process or thread. ``` -------------------------------- ### Debugger.on_setup Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/debug/debugger.html Callback method invoked on the first breakpoint event. Allows for setup of hooks or interaction with the debugee when it's ready. ```APIDOC ## on_setup() ### Description Called on the first breakpoint event occurring in the debugger. This callback allows to setup hook / interact with the debugee when ready: - If `on_setup` is overridden by a subclass it will be called and `on_exception` will NOT be called for this event (first BP). - If `on_setup` is not defined the first BP will trigger an `on_exception`. .. note:: see sample :ref:`sample_debugger_on_setup` ### Method `def` ### Returns `None` ``` -------------------------------- ### Device Manager - List Devices Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/sample.rst.txt Demonstrates how to enumerate and retrieve information about hardware devices. ```python from windows import device_manager print("Listing all devices:") for device in device_manager.list_devices(): print(f" - Name: {device.name}, Description: {device.description}, Status: {device.status}") ``` -------------------------------- ### StartWhenAvailable Property Source: https://github.com/hakril/pythonforwindows/blob/master/ctypes_generation/definitions/com/Tasks/ITaskSettings.txt Controls whether the task should start as soon as possible after a scheduled start time is missed. This is a read/write property. ```APIDOC ## StartWhenAvailable Property ### Description Gets or sets a value that indicates whether the task will start as soon as possible after a scheduled start time is missed. ### Method GET/PUT ### Endpoint ITaskSettings ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **startWhenAvailable** (VARIANT_BOOL) - Required - Specifies whether to start the task when available. ### Request Example ```json { "startWhenAvailable": true } ``` ### Response #### Success Response (200) - **pStartWhenAvailable** (VARIANT_BOOL) - Indicates if the task should start when available. ``` -------------------------------- ### Initialize COM and Interact with INetFwPolicy2 Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/sample.html Initializes COM, generates a CLSID for INetFwPolicy2, creates a COM instance, and checks firewall status for different network profiles. Requires the 'windows' library. ```python import sys import os.path import pprint sys.path.append(os.path.abspath(__file__ + "\..\..")) import windows import windows.generated_def as gdef from windows.generated_def import interfaces # This code is a simple version of the firewall code in windows.winoject.network print("Initialisation of COM") windows.com.init() print("Creating INetFwPolicy2 variable") firewall = interfaces.INetFwPolicy2() print("{0} (value = {1})".format(firewall, firewall.value)) print("") print("Generating CLSID") NetFwPolicy2CLSID = windows.com.IID.from_string("E2B3C97F-6AE1-41AC-817A-F6F92166D7DD") print(repr(NetFwPolicy2CLSID)) print("") print("Creating COM instance") windows.com.create_instance(NetFwPolicy2CLSID, firewall) print("{0} (value = 0x{1:0})".format(firewall, firewall.value)) print("") print("Checking for enabled profiles") for profile in [gdef.NET_FW_PROFILE2_DOMAIN, gdef.NET_FW_PROFILE2_PRIVATE, gdef.NET_FW_PROFILE2_PUBLIC]: enabled = gdef.VARIANT_BOOL() firewall.get_FirewallEnabled(profile, enabled) print(" * {0} -> {1}".format(profile, enabled.value)) ``` -------------------------------- ### TaskFolderCollection Get Index Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/task_scheduler.html Helper method to get an index for TaskFolderCollection, setting the variant type to I4 (32-bit integer). ```python def get_index(self, index): vindex = windows.com.Variant() vindex.vt = gdef.VT_I4 vindex._VARIANT_NAME_3.lVal = index return vindex ``` -------------------------------- ### TRACE_GUID_REGISTRATION Structure Definition Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/generated_def/winstructs.html Defines the TRACE_GUID_REGISTRATION structure, used for registering GUIDs with the tracing system. It includes the GUID and a registration handle. ```python class _TRACE_GUID_REGISTRATION(Structure): _fields_ = [ ("Guid", LPCGUID), ("RegHandle", HANDLE), ] PTRACE_GUID_REGISTRATION = POINTER(_TRACE_GUID_REGISTRATION) TRACE_GUID_REGISTRATION = _TRACE_GUID_REGISTRATION ``` -------------------------------- ### SetupDiClassNameFromGuidExW Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/winfuncs_generated.html Retrieves the class name for a device interface GUID on a remote computer using Unicode characters. ```APIDOC ## SetupDiClassNameFromGuidExW() ### Description Retrieves the class name for a device interface GUID on a remote computer using Unicode characters. ### Method Not specified (likely a function call in a Python SDK) ### Parameters Not specified in the source text. ### Request Example ```python # Example usage would depend on the specific SDK implementation ``` ### Response Not specified in the source text. ``` -------------------------------- ### Symbols: Symbol Search Example Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/sample.rst.txt Provides an example of how to search for symbols using the symbol handling utilities. This is useful for locating specific functions or variables. ```python from windows.debug.symbols import SymbolHandler symbol_handler = SymbolHandler() # Example: Search for a symbol by name # symbol_info = symbol_handler.get_symbol_by_name("CreateFileW") # print(symbol_info) ``` -------------------------------- ### Service Management Demo Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/sample.rst.txt Demonstrates registering, deleting, and managing a Windows service written in Python. ```python from windows.winobject.service import Service service_name = "MyPythonService" # Register the service # Service.register(service_name, "C:\\path\\to\\your\\script.py", start_type='demand') # Delete the service # Service.delete(service_name) # Example of interacting with a service (assuming it's registered) # try: # service = Service(service_name) # print(f"Service '{service_name}' status: {service.status}") # # service.stop() # # service.start() # except Exception as e: # print(f"Error managing service '{service_name}': {e}") ``` -------------------------------- ### VirtualAlloc Example Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/winproxy.html Demonstrates the usage of the VirtualAlloc function from the windows.winproxy module, including calling with ordinal and keyword arguments, and handling missing mandatory parameters. ```APIDOC ## VirtualAlloc ### Description Allocates memory in the virtual address space of the calling process. ### Method `windows.winproxy.VirtualAlloc` ### Parameters - **lpAddress** (int) - Optional - The base address of the region of pages to be mapped. If this parameter is NULL, the system determines where to allocate the region. - **dwSize** (int) - Required - The size, in bytes, of the region of pages to be mapped. - **flAllocationType** (int) - Optional - The type of memory allocation. Defaults to MEM_COMMIT (0x1000L). - **flProtect** (int) - Optional - The memory protection for the region of pages. Defaults to PAGE_EXECUTE_READWRITE (0x40L). ### Request Example ```python import windows # Using ordinal arguments windows.winproxy.VirtualAlloc(0, 0x1000) # Using keyword arguments windows.winproxy.VirtualAlloc(dwSize=0x1000) ``` ### Response #### Success Response (int) Returns the base address of the allocated region of pages, or 0 if the function fails. #### Error Handling Raises `WinproxyError` (or subclasses like `Kernel32Error`) if the function fails, for example, due to insufficient memory or missing mandatory parameters. ### Error Example ```python import windows try: windows.winproxy.VirtualAlloc() except TypeError as e: print(f"Error: {e}") try: windows.winproxy.VirtualAlloc(dwSize=0xffffffff) except windows.winproxy.error.WinproxyError as e: print(f"Error: {e}") ``` ``` -------------------------------- ### Example: LdrLoadDll 32-bit to 64-bit Call Source: https://github.com/hakril/pythonforwindows/blob/master/docs/source/internals.rst This is an example of a specific SysWOW64 API proxy for LdrLoadDll, demonstrating how to load a DLL in a 64-bit process from a 32-bit environment. ```python LdrLoadDll_32_to_64 = Syswow64ApiProxy(windows.winproxy.LdrLoadDll) ``` -------------------------------- ### Example: NtCreateThreadEx 32-bit to 64-bit Call Source: https://github.com/hakril/pythonforwindows/blob/master/docs/source/internals.rst This is an example of a specific SysWOW64 API proxy for NtCreateThreadEx, demonstrating how to create a thread in a 64-bit process from a 32-bit environment. ```python NtCreateThreadEx_32_to_64 = Syswow64ApiProxy(windows.winproxy.NtCreateThreadEx) ``` -------------------------------- ### Debugger: On Setup Event Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/sample.rst.txt Shows how to hook into the 'on_setup' event of the Debugger class. This event is triggered when the debugger is initialized. ```python from windows.debug import Debugger class MyDebugger(Debugger): def on_setup(self): print("Debugger setup complete!") debugger = MyDebugger() debugger.load_debugger() ``` -------------------------------- ### Initialize and Connect to Task Scheduler Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_modules/windows/winobject/system.html Initializes COM, creates a Task Scheduler service instance, and connects to it. Requires COM initialization. ```python windows.com.init() clsid_task_scheduler = gdef.IID.from_string("0f87369f-a4e5-4cfc-bd3e-73e6154572dd") task_service = task_scheduler.TaskService() # What is non-implemented (WinXP) # Raise (NotImplementedError?) ? Return NotImplemented ? windows.com.create_instance(clsid_task_scheduler, task_service) task_service.connect() return task_service ``` -------------------------------- ### Full Setup for Optimal Encoding Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/encoding.rst.txt This snippet shows the recommended setup for correct Unicode handling by setting PYTHONIOENCODING to utf-8 and changing the console codepage to 65001. ```shell $ set PYTHONIOENCODING=utf-8 $ chcp 65001 Active code page: 65001 $ python samples\encoding\check_encoding_config.py Python version is <2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)]> Py2 python/console configuration analysis: [*] env[PYTHONIOENCODING] = utf-8 [+] Optimal PYTHONIOENCODING [*] sys.stdout.encoding = utf-8 [*] Console Codepage = 65001 Unicode string print: <お前はもう死んでい-какие_фжющдфя> Unicode object repr: ``` -------------------------------- ### Encryption Demo: Generate Key, Encrypt, and Decrypt File Source: https://github.com/hakril/pythonforwindows/blob/master/docs/build/html/_sources/sample.rst.txt This sample demonstrates generating a key pair, encrypting a file, and then decrypting it. It requires a password for PFX file operations. Ensure the correct password is used to avoid errors. ```python import windows.crypto.certificate as crypto import windows.winproxy as winproxy import windows.error import sys import argparse parser = argparse.ArgumentParser(description='Encryption demo') subparsers = parser.add_subparsers(dest='command') # genkey command genkey_parser = subparsers.add_parser('genkey', help='Generate a new key pair') genkey_parser.add_argument('certname', help='Name of the certificate') genkey_parser.add_argument('keyname', help='Name of the key file (without extension)') genkey_parser.add_argument('--pfxpassword', default='password', help='Password for the PFX file') # crypt command crypt_parser = subparsers.add_parser('crypt', help='Encrypt a file') crypt_parser.add_argument('inputfile', help='File to encrypt') crypt_parser.add_argument('outputfile', help='Output encrypted file') crypt_parser.add_argument('cerfile', help='Certificate file (.cer) for encryption') # decrypt command decrypt_parser = subparsers.add_parser('decrypt', help='Decrypt a file') decrypt_parser.add_argument('inputfile', help='File to decrypt') decrypt_parser.add_argument('outputfile', help='Output decrypted file') decrypt_parser.add_argument('--password', default='password', help='Password for the PFX file') decrypt_parser.add_argument('pfxfile', help='Certificate file (.pfx) for decryption') res = parser.parse_args() if res.command == 'genkey': cert = crypto.CertificateContext.create_selfsigned(res.certname) cert.export_pfx(res.keyname + '.pfx', res.pfxpassword) cert.export_public(res.keyname + '.cer') print(cert) elif res.command == 'crypt': with open(res.inputfile, 'rb') as f: data = f.read() with open(res.cerfile, 'rb') as f: cert = crypto.CertificateContext.load_cert(f.read()) encrypted_data = cert.encrypt(data) with open(res.outputfile, 'wb') as f: f.write(encrypted_data) print('Encryption done. Result:\n%r' % bytearray(encrypted_data)) elif res.command == 'decrypt': with open(res.inputfile, 'rb') as f: data = f.read() with open(res.pfxfile, 'rb') as f: pfx = crypto.import_pfx(f.read(), res.password) decrypted_data = pfx.decrypt(data) with open(res.outputfile, 'wb') as f: f.write(decrypted_data) print('Result = %r' % decrypted_data) ``` -------------------------------- ### Example: NtQueryInformationThread 32-bit to 64-bit Call Source: https://github.com/hakril/pythonforwindows/blob/master/docs/source/internals.rst This is an example of a specific SysWOW64 API proxy for NtQueryInformationThread, demonstrating how to query thread information in a 64-bit process from a 32-bit environment. ```python NtQueryInformationThread_32_to_64 = Syswow64ApiProxy(windows.winproxy.NtQueryInformationThread) ```