Python ctypes.wintypes.HANDLE Examples

The following are 30 code examples for showing how to use ctypes.wintypes.HANDLE(). 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
Project: pygdbmi   Author: cs01   File: gdbcontroller.py    License: MIT License 6 votes vote down vote up
def _make_non_blocking(file_obj):
    """make file object non-blocking
    Windows doesn't have the fcntl module, but someone on
    stack overflow supplied this code as an answer, and it works
    http://stackoverflow.com/a/34504971/2893090"""

    if USING_WINDOWS:
        LPDWORD = POINTER(DWORD)
        PIPE_NOWAIT = wintypes.DWORD(0x00000001)

        SetNamedPipeHandleState = windll.kernel32.SetNamedPipeHandleState
        SetNamedPipeHandleState.argtypes = [HANDLE, LPDWORD, LPDWORD, LPDWORD]
        SetNamedPipeHandleState.restype = BOOL

        h = msvcrt.get_osfhandle(file_obj.fileno())

        res = windll.kernel32.SetNamedPipeHandleState(h, byref(PIPE_NOWAIT), None, None)
        if res == 0:
            raise ValueError(WinError())

    else:
        # Set the file status flag (F_SETFL) on the pipes to be non-blocking
        # so we can attempt to read from a pipe with no new data without locking
        # the program up
        fcntl.fcntl(file_obj, fcntl.F_SETFL, os.O_NONBLOCK) 
Example 9
Project: hupper   Author: Pylons   File: winapi.py    License: MIT License 6 votes vote down vote up
def DuplicateHandle(
    hSourceProcess,
    hSourceHandle,
    hTargetProcess,
    desiredAccess,
    inheritHandle,
    options,
):
    targetHandle = wintypes.HANDLE()
    ret = kernel32.DuplicateHandle(
        hSourceProcess,
        hSourceHandle,
        hTargetProcess,
        ctypes.byref(targetHandle),
        desiredAccess,
        inheritHandle,
        options,
    )
    CheckError(ret, 'failed to duplicate handle')
    return Handle(targetHandle.value) 
Example 10
Project: monitor_ctrl   Author: dot-osk   File: vcp.py    License: MIT License 6 votes vote down vote up
def close(self):
        """
        Close WinAPI Handle.
        
        https://msdn.microsoft.com/en-us/library/windows/desktop/dd692936(v=vs.85).aspx
        BOOL DestroyPhysicalMonitor(
            _In_  HANDLE hMonitor
        );
        :return:
        """
        import ctypes
        api_call = ctypes.windll.Dxva2.DestroyPhysicalMonitor
        
        if not api_call(self._phy_monitor_handle):
            _LOGGER.error(ctypes.WinError())
    
    # ########################## 发送/读取 VCP 设置的函数 
Example 11
Project: luci-py   Author: luci   File: fix_encoding.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, console_handle, fileno, stream_name, encoding):
    super(WinUnicodeConsoleOutput, self).__init__(
        fileno, '<Unicode console %s>' % stream_name, encoding)
    # Handle to use for WriteConsoleW
    self._console_handle = console_handle

    # Loads the necessary function.
    # These types are available on linux but not Mac.
    # pylint: disable=no-name-in-module,F0401
    from ctypes import byref, GetLastError, POINTER, windll, WINFUNCTYPE
    from ctypes.wintypes import BOOL, DWORD, HANDLE, LPWSTR
    from ctypes.wintypes import LPVOID  # pylint: disable=no-name-in-module

    self._DWORD = DWORD
    self._byref = byref

    # <http://msdn.microsoft.com/en-us/library/ms687401.aspx>
    self._WriteConsoleW = WINFUNCTYPE(
        BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID)(
            ('WriteConsoleW', windll.kernel32))
    self._GetLastError = GetLastError 
Example 12
Project: luci-py   Author: luci   File: fix_encoding.py    License: Apache License 2.0 6 votes vote down vote up
def win_handle_is_a_console(handle):
  """Returns True if a Windows file handle is a handle to a console."""
  # These types are available on linux but not Mac.
  # pylint: disable=no-name-in-module,F0401
  from ctypes import byref, POINTER, windll, WINFUNCTYPE
  from ctypes.wintypes import BOOL, DWORD, HANDLE

  FILE_TYPE_CHAR   = 0x0002
  FILE_TYPE_REMOTE = 0x8000
  INVALID_HANDLE_VALUE = DWORD(-1).value

  # <http://msdn.microsoft.com/en-us/library/ms683167.aspx>
  GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
      ('GetConsoleMode', windll.kernel32))
  # <http://msdn.microsoft.com/en-us/library/aa364960.aspx>
  GetFileType = WINFUNCTYPE(DWORD, DWORD)(('GetFileType', windll.kernel32))

  # GetStdHandle returns INVALID_HANDLE_VALUE, NULL, or a valid handle.
  if handle == INVALID_HANDLE_VALUE or handle is None:
    return False
  return (
      (GetFileType(handle) & ~FILE_TYPE_REMOTE) == FILE_TYPE_CHAR and
       GetConsoleMode(handle, byref(DWORD()))) 
Example 13
Project: python-prompt-toolkit   Author: prompt-toolkit   File: windows10.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_win_vt100_enabled() -> bool:
    """
    Returns True when we're running Windows and VT100 escape sequences are
    supported.
    """
    if not is_windows():
        return False

    hconsole = HANDLE(windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE))

    # Get original console mode.
    original_mode = DWORD(0)
    windll.kernel32.GetConsoleMode(hconsole, byref(original_mode))

    try:
        # Try to enable VT100 sequences.
        result = windll.kernel32.SetConsoleMode(
            hconsole, DWORD(ENABLE_PROCESSED_INPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
        )

        return result == 1
    finally:
        windll.kernel32.SetConsoleMode(hconsole, original_mode) 
Example 14
Project: python-prompt-toolkit   Author: prompt-toolkit   File: win32.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, stdout: TextIO, use_complete_width: bool = False) -> None:
        self.use_complete_width = use_complete_width

        self._buffer: List[str] = []
        self.stdout = stdout
        self.hconsole = HANDLE(windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE))

        self._in_alternate_screen = False
        self._hidden = False

        self.color_lookup_table = ColorLookupTable()

        # Remember the default console colors.
        info = self.get_win32_screen_buffer_info()
        self.default_attrs = info.wAttributes if info else 15

        if _DEBUG_RENDER_OUTPUT:
            self.LOG = open(_DEBUG_RENDER_OUTPUT_FILENAME, "ab") 
Example 15
Project: minidump   Author: skelsec   File: privileges.py    License: MIT License 5 votes vote down vote up
def get_process_token():
    "Get the current process token"
    token = wintypes.HANDLE()
    TOKEN_ALL_ACCESS = 0xf01ff
    res = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, token)
    if not res > 0:
        raise RuntimeError("Couldn't get process token")
    return token 
Example 16
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 17
Project: win32wifi   Author: kedos   File: Win32NativeWifiApi.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 18
Project: win32wifi   Author: kedos   File: Win32NativeWifiApi.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 19
Project: win32wifi   Author: kedos   File: Win32NativeWifiApi.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 20
Project: win32wifi   Author: kedos   File: Win32NativeWifiApi.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 21
Project: win32wifi   Author: kedos   File: Win32NativeWifiApi.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 22
Project: pymake   Author: mozilla   File: win32process.py    License: MIT License 5 votes vote down vote up
def WaitForAnyProcess(processes):
    arrtype = HANDLE * len(processes)
    harray = arrtype(*(int(p._handle) for p in processes))

    r = _WaitForMultipleObjects(len(processes), harray, False, INFINITE)
    if r == WAIT_FAILED:
        raise WinError()

    return processes[r], GetExitCodeProcess(int(processes[r]._handle)) <<8 
Example 23
Project: WebPocket   Author: TuuuNya   File: rl_utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def enable_win_vt100(handle: HANDLE) -> bool:
            """
            Enables VT100 character sequences in a Windows console
            This only works on Windows 10 and up
            :param handle: the handle on which to enable vt100
            :return: True if vt100 characters are enabled for the handle
            """
            ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004

            # Get the current mode for this handle in the console
            cur_mode = DWORD(0)
            readline.rl.console.GetConsoleMode(handle, byref(cur_mode))

            retVal = False

            # Check if  ENABLE_VIRTUAL_TERMINAL_PROCESSING is already enabled
            if (cur_mode.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0:
                retVal = True

            elif readline.rl.console.SetConsoleMode(handle, cur_mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING):
                # Restore the original mode when we exit
                atexit.register(readline.rl.console.SetConsoleMode, handle, cur_mode)
                retVal = True

            return retVal

        # Enable VT100 sequences for stdout and stderr 
Example 24
Project: cloudbase-init   Author: cloudbase   File: x509.py    License: Apache License 2.0 5 votes vote down vote up
def _generate_key(self, container_name, machine_keyset):
        crypt_prov_handle = wintypes.HANDLE()
        key_handle = wintypes.HANDLE()

        try:
            flags = 0
            if machine_keyset:
                flags |= cryptoapi.CRYPT_MACHINE_KEYSET

            if not cryptoapi.CryptAcquireContext(
                    ctypes.byref(crypt_prov_handle),
                    container_name,
                    None,
                    cryptoapi.PROV_RSA_FULL,
                    flags):
                flags |= cryptoapi.CRYPT_NEWKEYSET
                if not cryptoapi.CryptAcquireContext(
                        ctypes.byref(crypt_prov_handle),
                        container_name,
                        None,
                        cryptoapi.PROV_RSA_FULL,
                        flags):
                    raise cryptoapi.CryptoAPIException()

            # RSA 2048 bits
            if not cryptoapi.CryptGenKey(crypt_prov_handle,
                                         cryptoapi.AT_KEYEXCHANGE,
                                         0x08000000,
                                         ctypes.byref(key_handle)):
                raise cryptoapi.CryptoAPIException()

            return key_handle
        finally:
            if key_handle:
                cryptoapi.CryptDestroyKey(key_handle)
            if crypt_prov_handle:
                cryptoapi.CryptReleaseContext(crypt_prov_handle, 0) 
Example 25
Project: cloudbase-init   Author: cloudbase   File: windows.py    License: Apache License 2.0 5 votes vote down vote up
def create_user_logon_session(self, username, password, domain='.',
                                  load_profile=True,
                                  logon_type=LOGON32_LOGON_INTERACTIVE):
        LOG.debug("Creating logon session for user: %(domain)s\\%(username)s",
                  {"username": username, "domain": domain})

        token = wintypes.HANDLE()
        ret_val = advapi32.LogonUserW(six.text_type(username),
                                      six.text_type(domain),
                                      six.text_type(password),
                                      logon_type,
                                      self.LOGON32_PROVIDER_DEFAULT,
                                      ctypes.byref(token))
        if not ret_val:
            raise exception.WindowsCloudbaseInitException(
                "User logon failed: %r")

        if load_profile:
            pi = Win32_PROFILEINFO()
            pi.dwSize = ctypes.sizeof(Win32_PROFILEINFO)
            pi.lpUserName = six.text_type(username)
            ret_val = userenv.LoadUserProfileW(token, ctypes.byref(pi))
            if not ret_val:
                kernel32.CloseHandle(token)
                raise exception.WindowsCloudbaseInitException(
                    "Cannot load user profile: %r")

        return token 
Example 26
Project: slither   Author: crytic   File: colors.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def enable_windows_virtual_terminal_sequences():
    """
    Sets the appropriate flags to enable virtual terminal sequences in a Windows command prompt.
    Reference: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
    """

    try:
        from ctypes import windll, byref
        from ctypes.wintypes import DWORD, HANDLE

        kernel32 = windll.kernel32
        virtual_terminal_flag = 0x04  # ENABLE_VIRTUAL_TERMINAL_PROCESSING

        # Obtain our stdout/stderr handles.
        # Reference: https://docs.microsoft.com/en-us/windows/console/getstdhandle
        handle_stdout = kernel32.GetStdHandle(-11)
        handle_stderr = kernel32.GetStdHandle(-12)

        # Loop for each stdout/stderr handle.
        for current_handle in [handle_stdout, handle_stderr]:

            # If we get a null handle, or fail any subsequent calls in this scope, we do not colorize any output.
            if current_handle is None or current_handle == HANDLE(-1):
                return False

            # Try to obtain the current flags for the console.
            current_mode = DWORD()
            if not kernel32.GetConsoleMode(current_handle, byref(current_mode)):
                return False

            # If the virtual terminal sequence processing is not yet enabled, we enable it.
            if (current_mode.value & virtual_terminal_flag) == 0:
                if not kernel32.SetConsoleMode(current_handle, current_mode.value | virtual_terminal_flag):
                    return False
    except:
        # Any generic failure (possibly from calling these methods on older Windows builds where they do not exist)
        # will fall back onto disabling colorization.
        return False

    return True 
Example 27
Project: monitor_ctrl   Author: dot-osk   File: vcp.py    License: MIT License 5 votes vote down vote up
def _get_monitor_caps(self):
        """
        https://msdn.microsoft.com/en-us/library/windows/desktop/dd692938(v=vs.85).aspx
        BOOL GetCapabilitiesStringLength(
            _In_   HANDLE hMonitor,
            _Out_  LPDWORD pdwCapabilitiesStringLengthInCharacters
        );
        
        https://msdn.microsoft.com/en-us/library/windows/desktop/dd692934(v=vs.85).aspx
        BOOL CapabilitiesRequestAndCapabilitiesReply(
            _In_   HANDLE hMonitor,
            _Out_  LPSTR pszASCIICapabilitiesString,
            _In_   DWORD dwCapabilitiesStringLengthInCharacters
        );
        :return:
        """
        
        caps_string_length = wintypes.DWORD()
        if not ctypes.windll.Dxva2.GetCapabilitiesStringLength(self._phy_monitor_handle,
                                                               ctypes.byref(caps_string_length)):
            _LOGGER.error(ctypes.WinError())
            raise ctypes.WinError()
        
        caps_string = (ctypes.c_char * caps_string_length.value)()
        if not ctypes.windll.Dxva2.CapabilitiesRequestAndCapabilitiesReply(
                self._phy_monitor_handle, caps_string, caps_string_length):
                _LOGGER.error(ctypes.WinError())
                return
        
        self._caps_string = caps_string.value.decode('ASCII') 
Example 28
Project: monitor_ctrl   Author: dot-osk   File: vcp.py    License: MIT License 5 votes vote down vote up
def send_vcp_code(self, code: int, value: int) -> bool:
        """
        send vcp code to monitor.
        
        https://msdn.microsoft.com/en-us/library/dd692979(v=vs.85).aspx
        BOOL SetVCPFeature(
            _In_  HANDLE hMonitor,
            _In_  BYTE bVCPCode,
            _In_  DWORD dwNewValue
        );
        
        :param code: VCP Code
        :param value: Data
        :return: Win32 API return
        """
        if code is None:
            _LOGGER.error('vcp code to send is None. ignored.')
            return False
        
        api_call = ctypes.windll.Dxva2.SetVCPFeature
        code = wintypes.BYTE(code)
        new_value = wintypes.DWORD(value)
        api_call.restype = ctypes.c_bool
        ret_ = api_call(self._phy_monitor_handle, code, new_value)
        if not ret_:
            _LOGGER.error('send vcp command failed: ' + hex(code))
            _LOGGER.error(ctypes.WinError())
        return ret_ 
Example 29
Project: monitor_ctrl   Author: dot-osk   File: vcp.py    License: MIT License 5 votes vote down vote up
def read_vcp_code(self, code: int) -> Tuple[int, int]:
        """
        send vcp code to monitor, get current value and max value.
        
        https://msdn.microsoft.com/en-us/library/dd692953(v=vs.85).aspx
        BOOL GetVCPFeatureAndVCPFeatureReply(
            _In_   HANDLE hMonitor,
            _In_   BYTE bVCPCode,
            _Out_  LPMC_VCP_CODE_TYPE pvct,
            _Out_  LPDWORD pdwCurrentValue,
            _Out_  LPDWORD pdwMaximumValue
        );
        
        :param code: VCP Code
        :return: current_value, max_value
        """
        if code is None:
            _LOGGER.error('vcp code to send is None. ignored.')
            return 0, 0
        
        api_call = ctypes.windll.Dxva2.GetVCPFeatureAndVCPFeatureReply
        api_in_vcp_code = wintypes.BYTE(code)
        api_out_current_value = wintypes.DWORD()
        api_out_max_value = wintypes.DWORD()
        
        if not api_call(self._phy_monitor_handle, api_in_vcp_code, None,
                        ctypes.byref(api_out_current_value), ctypes.byref(api_out_max_value)):
            _LOGGER.error('get vcp command failed: ' + hex(code))
            _LOGGER.error(ctypes.WinError())
        return api_out_current_value.value, api_out_max_value.value 
Example 30
Project: pre-commit   Author: pre-commit   File: color.py    License: MIT License 5 votes vote down vote up
def _enable() -> None:
        from ctypes import POINTER
        from ctypes import windll
        from ctypes import WinError
        from ctypes import WINFUNCTYPE
        from ctypes.wintypes import BOOL
        from ctypes.wintypes import DWORD
        from ctypes.wintypes import HANDLE

        STD_ERROR_HANDLE = -12
        ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4

        def bool_errcheck(result, func, args):
            if not result:
                raise WinError()
            return args

        GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(
            ('GetStdHandle', windll.kernel32), ((1, 'nStdHandle'),),
        )

        GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
            ('GetConsoleMode', windll.kernel32),
            ((1, 'hConsoleHandle'), (2, 'lpMode')),
        )
        GetConsoleMode.errcheck = bool_errcheck

        SetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, DWORD)(
            ('SetConsoleMode', windll.kernel32),
            ((1, 'hConsoleHandle'), (1, 'dwMode')),
        )
        SetConsoleMode.errcheck = bool_errcheck

        # As of Windows 10, the Windows console supports (some) ANSI escape
        # sequences, but it needs to be enabled using `SetConsoleMode` first.
        #
        # More info on the escape sequences supported:
        # https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
        stderr = GetStdHandle(STD_ERROR_HANDLE)
        flags = GetConsoleMode(stderr)
        SetConsoleMode(stderr, flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING)