Python ctypes.wintypes.DWORD Examples

The following are 30 code examples for showing how to use ctypes.wintypes.DWORD(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module ctypes.wintypes , or try the search function .

Example 1
Project: vergeml   Author: mme   File: display.py    License: MIT License 6 votes vote down vote up
def try_enable_ansi():
            """Try enabling ANSI colors
            https://stackoverflow.com/questions/44482505/setconsolemode-returning-false-when-enabling-ansi-color-under-windows-10"""
            lpMode = wintypes.DWORD()
            handle = WINAPI._GetStdHandle(WINAPI._STDOUT)
            if WINAPI._GetConsoleMode(handle, ctypes.byref(lpMode)):
               
                if not WINAPI._SetConsoleMode(handle, lpMode.value | WINAPI._ENABLE_VIRTUAL_TERMINAL_PROCESSING):
                    return False
            else:
                return False
            
            lpMode = wintypes.DWORD()
            handle = WINAPI._GetStdHandle(WINAPI._STDERR)
            if WINAPI._GetConsoleMode(handle, ctypes.byref(lpMode)):
                if not WINAPI._SetConsoleMode(handle, lpMode.value | WINAPI._ENABLE_VIRTUAL_TERMINAL_PROCESSING):
                    return False
            else:
                return False
            
            return True 
Example 2
Project: cWMI   Author: fireeye   File: winapi.py    License: Apache License 2.0 6 votes vote down vote up
def CoInitializeEx(reserved, co_init):
    prototype = ctypes.WINFUNCTYPE(
        HRESULT,
        wintypes.LPVOID,
        wintypes.DWORD
    )

    paramflags = (
        (_In_, 'pvReserved'),
        (_In_, 'dwCoInit')
    )

    _CoInitializeEx = prototype(('CoInitializeEx', ole32), paramflags)
    _CoInitializeEx.errcheck = RAISE_NON_ZERO_ERR

    return _CoInitializeEx(reserved, co_init) 
Example 3
Project: cWMI   Author: fireeye   File: winapi.py    License: Apache License 2.0 6 votes vote down vote up
def CoCreateInstance(clsid, unk, ctx, iid):
    prototype = ctypes.WINFUNCTYPE(
        HRESULT,
        ctypes.POINTER(GUID),
        wintypes.LPVOID,
        wintypes.DWORD,
        ctypes.POINTER(GUID),
        ctypes.POINTER(wintypes.LPVOID)
    )

    paramflags = (
        (_In_, 'rclsid'),
        (_In_, 'pUnkOuter'),
        (_In_, 'dwClsContext'),
        (_In_, 'riid'),
        (_Out_, 'ppv')
    )

    _CoCreateInstance = prototype(('CoCreateInstance', ole32), paramflags)
    _CoCreateInstance.errcheck = RAISE_NON_ZERO_ERR
    return _CoCreateInstance(clsid, unk, ctx, iid) 
Example 4
Project: sk1-wx   Author: sk1project   File: winspool.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_printer_names():
    names = []
    info = ctypes.POINTER(BYTE)()
    pcbNeeded = DWORD(0)
    pcReturned = DWORD(0)
    winspool.EnumPrintersW(PRINTER_ENUM_LOCAL, NAME, 1, ctypes.byref(info),
                           0, ctypes.byref(pcbNeeded), ctypes.byref(pcReturned))
    bufsize = pcbNeeded.value
    if bufsize:
        buff = msvcrt.malloc(bufsize)
        winspool.EnumPrintersW(PRINTER_ENUM_LOCAL, NAME, 1, buff, bufsize,
                               ctypes.byref(pcbNeeded),
                               ctypes.byref(pcReturned))
        info = ctypes.cast(buff, ctypes.POINTER(PRINTER_INFO_1))
        for i in range(pcReturned.value):
            names.append(info[i].pName)
        msvcrt.free(buff)
    return names 
Example 5
Project: sk1-wx   Author: sk1project   File: winspool.py    License: GNU General Public License v3.0 6 votes vote down vote up
def is_color_printer(prtname):
    ret = False
    if not prtname:
        prtname = get_default_printer()
    hptr = open_printer(prtname)
    info = ctypes.POINTER(BYTE)()
    cbBuf = DWORD(0)
    pcbNeeded = DWORD(0)
    winspool.GetPrinterA(hptr, 2, ctypes.byref(info),
                         cbBuf, ctypes.byref(pcbNeeded))
    bufsize = pcbNeeded.value
    if bufsize:
        buff = msvcrt.malloc(bufsize)
        winspool.GetPrinterA(hptr, 2, buff, bufsize, ctypes.byref(pcbNeeded))
        info = ctypes.cast(buff, ctypes.POINTER(PRINTER_INFO_2))
        ret = info.contents.pDevMode.contents.dmColor == 2
        msvcrt.free(buff)
    close_printer(hptr)
    return ret 
Example 6
Project: minidump   Author: skelsec   File: createminidump.py    License: MIT License 6 votes vote down vote up
def enum_process_names():
	pid_to_name = {}
	
	for pid in enum_pids():
		pid_to_name[pid] = 'Not found'
		process_handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
		if process_handle is None:
			logging.debug('[Enum Processes]Failed to open process PID: %d Reason: %s ' % (pid, WinError(get_last_error())))
			continue
		
		image_name = (ctypes.c_char*MAX_PATH)()
		max_path = DWORD(4096)
		#res = GetProcessImageFileName(process_handle, image_name, MAX_PATH)
		res = QueryFullProcessImageName(process_handle, 0 ,image_name, ctypes.byref(max_path))
		if res == 0:
			logging.debug('[Enum Proceses]Failed GetProcessImageFileName on PID: %d Reason: %s ' % (pid, WinError(get_last_error())))
			continue
		
		pid_to_name[pid] = image_name.value.decode()
	return pid_to_name 
Example 7
Project: win_driver_plugin   Author: FSecureLABS   File: driverlib.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 = ctypes.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)) 
Example 8
Project: win_driver_plugin   Author: FSecureLABS   File: driverlib.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 = ctypes.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 
Example 9
Project: win_driver_plugin   Author: FSecureLABS   File: driverlib.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 = ctypes.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 
Example 10
Project: win_driver_plugin   Author: FSecureLABS   File: driverlib.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def start_service(service_handle, service_arg_count, service_arg_vectors):
	"""See: StartService function
	https://msdn.microsoft.com/en-us/library/windows/desktop/ms686321(v=vs.85).aspx
	"""
	
	StartService_Fn = ctypes.windll.Advapi32.StartServiceA	#BOOL WINAPI StartService(
	StartService_Fn.argtypes = [					#
		wintypes.SC_HANDLE,							#	_In_ 	 SC_HANDLE hService,
		wintypes.DWORD,								#	_In_ 	 DWORD     dwNumServiceArgs,
		LPCTSTR							#	_In_opt_ LPCTSTR   *lpServiceArgVectors
	]
	StartService_Fn.restype = wintypes.BOOL
	bool = StartService_Fn(
		service_handle,
		service_arg_count, 
		service_arg_vectors
	)
	return bool 
Example 11
Project: win32wifi   Author: kedos   File: Win32NativeWifiApi.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 12
Project: win32wifi   Author: kedos   File: Win32NativeWifiApi.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 13
Project: win32wifi   Author: kedos   File: Win32NativeWifiApi.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 14
Project: win32wifi   Author: kedos   File: Win32NativeWifiApi.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 15
Project: win32wifi   Author: kedos   File: Win32NativeWifiApi.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 16
Project: gdog   Author: maldevel   File: client.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _set_argtypes(self):
        ''' Functions arguments. '''

        self.MONITORENUMPROC = WINFUNCTYPE(INT, DWORD, DWORD, POINTER(RECT),
                                           DOUBLE)
        windll.user32.GetSystemMetrics.argtypes = [INT]
        windll.user32.EnumDisplayMonitors.argtypes = [HDC, c_void_p,
                                                      self.MONITORENUMPROC,
                                                      LPARAM]
        windll.user32.GetWindowDC.argtypes = [HWND]
        windll.gdi32.CreateCompatibleDC.argtypes = [HDC]
        windll.gdi32.CreateCompatibleBitmap.argtypes = [HDC, INT, INT]
        windll.gdi32.SelectObject.argtypes = [HDC, HGDIOBJ]
        windll.gdi32.BitBlt.argtypes = [HDC, INT, INT, INT, INT, HDC, INT, INT,
                                        DWORD]
        windll.gdi32.DeleteObject.argtypes = [HGDIOBJ]
        windll.gdi32.GetDIBits.argtypes = [HDC, HBITMAP, UINT, UINT, c_void_p,
                                           POINTER(BITMAPINFO), UINT] 
Example 17
Project: pywintrace   Author: fireeye   File: etw.py    License: Apache License 2.0 6 votes vote down vote up
def _getEventInformation(record):
        """
        Initially we are handed an EVENT_RECORD structure. While this structure technically contains
        all of the information necessary, TdhGetEventInformation parses the structure and simplifies it
        so we can more effectively parse and handle the various fields.

        :param record: The EventRecord structure for the event we are parsing
        :return: Returns a pointer to a TRACE_EVENT_INFO structure or None on error.
        """
        info = ct.POINTER(tdh.TRACE_EVENT_INFO)()
        buffer_size = wt.DWORD()

        # Call TdhGetEventInformation once to get the required buffer size and again to actually populate the structure.
        status = tdh.TdhGetEventInformation(record, 0, None, None, ct.byref(buffer_size))
        if tdh.ERROR_INSUFFICIENT_BUFFER == status:
            info = ct.cast((ct.c_byte * buffer_size.value)(), ct.POINTER(tdh.TRACE_EVENT_INFO))
            status = tdh.TdhGetEventInformation(record, 0, None, info, ct.byref(buffer_size))

        if tdh.ERROR_SUCCESS != status:
            raise ct.WinError(status)

        return info 
Example 18
Project: zmirror   Author: aploium   File: win32.py    License: MIT License 5 votes vote down vote up
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 
Example 19
Project: zmirror   Author: aploium   File: win32.py    License: MIT License 5 votes vote down vote up
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)) 
Example 20
Project: cWMI   Author: fireeye   File: winapi.py    License: Apache License 2.0 5 votes vote down vote up
def CoSetProxyBlanket(proxy,
                      authn_svc,
                      authz_svc,
                      server_p_name,
                      authn_level,
                      imp_level,
                      auth_info,
                      capabilities):
    prototype = ctypes.WINFUNCTYPE(
        HRESULT,
        wintypes.LPVOID,
        wintypes.DWORD,
        wintypes.DWORD,
        wintypes.OLESTR,
        wintypes.DWORD,
        wintypes.DWORD,
        RPC_AUTH_IDENTITY_HANDLE,
        wintypes.DWORD
    )

    paramflags = (
        (_In_, 'pProxy'),
        (_In_, 'dwAuthnSvc'),
        (_In_, 'dwAuthzSvc'),
        (_In_, 'pServerPrincName'),
        (_In_, 'dwAuthnLevel'),
        (_In_, 'dwImpLevel'),
        (_In_, 'pAuthInfo'),
        (_In_, 'dwCapabilities')
    )

    _CoSetProxyBlanket = prototype(('CoSetProxyBlanket', ole32), paramflags)
    _CoSetProxyBlanket.errcheck = RAISE_NON_ZERO_ERR
    return _CoSetProxyBlanket(proxy,
                              authn_svc,
                              authz_svc,
                              server_p_name,
                              authn_level,
                              imp_level,
                              auth_info,
                              capabilities) 
Example 21
Project: multibootusb   Author: mbusb   File: win32.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 
Example 22
Project: multibootusb   Author: mbusb   File: win32.py    License: GNU General Public License v2.0 5 votes vote down vote up
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)) 
Example 23
Project: leaguedirector   Author: RiotGames   File: bindings.py    License: Apache License 2.0 5 votes vote down vote up
def run_windows(self):
        from ctypes.wintypes import DWORD, WPARAM, LPARAM, MSG

        class KBDLLHOOKSTRUCT(Structure):
            _fields_ = [
                ("vk_code", DWORD),
                ("scan_code", DWORD),
                ("flags", DWORD),
                ("time", c_int),
                ("dwExtraInfo", POINTER(DWORD))
            ]

        def callback(nCode, wParam, lParam):
            pid = c_ulong()
            windll.user32.GetWindowThreadProcessId(windll.user32.GetForegroundWindow(), byref(pid))
            if pid.value == self.pid:
                windll.user32.SendMessageA(self.window.winId(), wParam, lParam.contents.vk_code, 0)
            return windll.user32.CallNextHookEx(None, nCode, wParam, lParam)
 
        function = CFUNCTYPE(c_int, WPARAM, LPARAM, POINTER(KBDLLHOOKSTRUCT))(callback)
        hook = windll.user32.SetWindowsHookExW(13, function, windll.kernel32.GetModuleHandleW(None), 0)

        msg = POINTER(MSG)()
        while self.running:
            try:
                windll.user32.GetMessageW(msg, 0, 0, 0)
                windll.user32.TranslateMessage(msg)
                windll.user32.DispatchMessageA(msg)
            except: pass

        windll.user32.UnhookWindowsHookEx(hook) 
Example 24
Project: sk1-wx   Author: sk1project   File: winspool.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_default_printer():
    plen = DWORD(0)
    winspool.GetDefaultPrinterW(None, byref(plen))
    pname = create_unicode_buffer(plen.value)
    winspool.GetDefaultPrinterW(pname, byref(plen))
    return pname.value 
Example 25
Project: minidump   Author: skelsec   File: privileges.py    License: MIT License 5 votes vote down vote up
def get_name(self):
        size = wintypes.DWORD(10240)
        buf = ctypes.create_unicode_buffer(size.value)
        res = LookupPrivilegeName(None, self.LUID, buf, size)
        if res == 0:
            raise RuntimeError
        return buf[:size.value] 
Example 26
Project: minidump   Author: skelsec   File: privileges.py    License: MIT License 5 votes vote down vote up
def get_privilege_information():
    "Get all privileges associated with the current process."
    # first call with zero length to determine what size buffer we need

    return_length = wintypes.DWORD()
    params = [
            get_process_token(),
            TOKEN_INFORMATION_CLASS.TokenPrivileges,
            None,
            0,
            return_length,
            ]

    res = GetTokenInformation(*params)

    # assume we now have the necessary length in return_length

    buffer = ctypes.create_string_buffer(return_length.value)
    params[2] = buffer
    params[3] = return_length.value

    res = GetTokenInformation(*params)
    assert res > 0, "Error in second GetTokenInformation (%d)" % res

    privileges = ctypes.cast(buffer, ctypes.POINTER(TOKEN_PRIVILEGES)).contents
    return privileges 
Example 27
Project: win_driver_plugin   Author: FSecureLABS   File: driverlib.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_ioctl(self, ioctl, inbuf, inbufsiz, outbuf, outbufsiz):
        """See: DeviceIoControl function
        http://msdn.microsoft.com/en-us/library/aa363216(v=vs.85).aspx
        """
        DeviceIoControl_Fn = ctypes.windll.kernel32.DeviceIoControl
        DeviceIoControl_Fn.argtypes = [
                wintypes.HANDLE,                    # _In_          HANDLE hDevice
                wintypes.DWORD,                     # _In_          DWORD dwIoControlCode
                wintypes.LPVOID,                    # _In_opt_      LPVOID lpInBuffer
                wintypes.DWORD,                     # _In_          DWORD nInBufferSize
                wintypes.LPVOID,                    # _Out_opt_     LPVOID lpOutBuffer
                wintypes.DWORD,                     # _In_          DWORD nOutBufferSize
                LPDWORD,                            # _Out_opt_     LPDWORD lpBytesReturned
                LPOVERLAPPED]                       # _Inout_opt_   LPOVERLAPPED lpOverlapped
        DeviceIoControl_Fn.restype = wintypes.BOOL
        # allocate a DWORD, and take its reference
        dwBytesReturned = wintypes.DWORD(0)
        lpBytesReturned = ctypes.byref(dwBytesReturned)
        status = DeviceIoControl_Fn(self.handle,
                      ioctl,
                      inbuf,
                      inbufsiz,
                      outbuf,
                      outbufsiz,
                      lpBytesReturned,
                      None)

        return status, dwBytesReturned 
Example 28
Project: win_driver_plugin   Author: FSecureLABS   File: driverlib.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start(self, machine_name=None, database_name=None, sc_manager_desired_access=SC_MANAGER_ALL_ACCESS, service_access=SERVICE_ALL_ACCESS):
        service_manager_handle = open_sc_manager(machine_name, database_name, sc_manager_desired_access)
        service_handle = open_service(service_manager_handle, self.name, service_access)
        if not service_handle:
            return False
        ret = start_service(service_handle,wintypes.DWORD(0),None)
        close_service_handle(service_handle)
        return ret 
Example 29
Project: win_driver_plugin   Author: FSecureLABS   File: driverlib.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_service(service_manager_handle, service_name, display_name, desired_access, service_type, start_type, 
					error_control, binary_path, load_order_group, tag_id, dependencies, service_start_name, password):
	"""See: CreateService function
	https://msdn.microsoft.com/en-gb/library/windows/desktop/ms682450(v=vs.85).aspx
	"""

	CreateService_Fn = ctypes.windll.Advapi32.CreateServiceA	#SC_HANDLE WINAPI CreateService(
	CreateService_Fn.argtypes = [						#
		wintypes.SC_HANDLE,								#	_In_      SC_HANDLE hSCManager,
		LPCTSTR,								        #	_In_      LPCTSTR   lpServiceName,	
		LPCTSTR,								        #	_In_opt_  LPCTSTR   lpDisplayName,
		wintypes.DWORD,									#	_In_      DWORD     dwDesiredAccess,
		wintypes.DWORD,									#	_In_      DWORD     dwServiceType,
		wintypes.DWORD,									#	_In_      DWORD     dwStartType,	
		wintypes.DWORD,									#	_In_      DWORD     dwErrorControl,
		LPCTSTR,								        #	_In_opt_  LPCTSTR   lpBinaryPathName,
		LPCTSTR,								        #	_In_opt_  LPCTSTR   lpLoadOrderGroup,
		LPDWORD,								        #	_Out_opt_ LPDWORD   lpdwTagId,
		LPCTSTR,								        #	_In_opt_  LPCTSTR   lpDependencies,	
		LPCTSTR,								        #	_In_opt_  LPCTSTR   lpServiceStartName,
		LPCTSTR								            #	_In_opt_  LPCTSTR   lpPassword
	]
	CreateService_Fn.restype = wintypes.SC_HANDLE
	handle = CreateService_Fn(
		service_manager_handle, 
		service_name, 
		display_name, 
		desired_access, 
		service_type, 
		start_type, 
		error_control,
		binary_path,
		load_order_group,
		tag_id,
		dependencies,
		service_start_name,
		password
	)
	return handle 
Example 30
Project: recruit   Author: Frank-qlu   File: win32.py    License: Apache License 2.0 5 votes vote down vote up
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