Python ctypes.WinError() Examples

The following are 30 code examples of ctypes.WinError(). 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 also want to check out all available functions/classes of the module ctypes , or try the search function .
Example #1
Source File: _environ.py    From bugatsinho.github.io with GNU General Public License v3.0 6 votes vote down vote up
def set_windows_env_var(key, value):
    """Set an env var.

    Raises:
        WindowsError
    """

    if not isinstance(key, text_type):
        raise TypeError("%r not of type %r" % (key, text_type))

    if not isinstance(value, text_type):
        raise TypeError("%r not of type %r" % (value, text_type))

    status = winapi.SetEnvironmentVariableW(key, value)
    if status == 0:
        raise ctypes.WinError() 
Example #2
Source File: windows_support.py    From lambda-chef-node-cleanup with Apache License 2.0 6 votes vote down vote up
def hide_file(path):
    """
    Set the hidden attribute on a file or directory.

    From http://stackoverflow.com/questions/19622133/

    `path` must be text.
    """
    __import__('ctypes.wintypes')
    SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
    SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
    SetFileAttributes.restype = ctypes.wintypes.BOOL

    FILE_ATTRIBUTE_HIDDEN = 0x02

    ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
    if not ret:
        raise ctypes.WinError() 
Example #3
Source File: windows_support.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def hide_file(path):
    """
    Set the hidden attribute on a file or directory.

    From http://stackoverflow.com/questions/19622133/

    `path` must be text.
    """
    __import__('ctypes.wintypes')
    SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
    SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
    SetFileAttributes.restype = ctypes.wintypes.BOOL

    FILE_ATTRIBUTE_HIDDEN = 0x02

    ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
    if not ret:
        raise ctypes.WinError() 
Example #4
Source File: windows_support.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def hide_file(path):
    """
    Set the hidden attribute on a file or directory.

    From http://stackoverflow.com/questions/19622133/

    `path` must be text.
    """
    __import__('ctypes.wintypes')
    SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
    SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
    SetFileAttributes.restype = ctypes.wintypes.BOOL

    FILE_ATTRIBUTE_HIDDEN = 0x02

    ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
    if not ret:
        raise ctypes.WinError() 
Example #5
Source File: windows_support.py    From jbox with MIT License 6 votes vote down vote up
def hide_file(path):
    """
    Set the hidden attribute on a file or directory.

    From http://stackoverflow.com/questions/19622133/

    `path` must be text.
    """
    __import__('ctypes.wintypes')
    SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
    SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
    SetFileAttributes.restype = ctypes.wintypes.BOOL

    FILE_ATTRIBUTE_HIDDEN = 0x02

    ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
    if not ret:
        raise ctypes.WinError() 
Example #6
Source File: winapi.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def EnumWindows():
    _EnumWindows = windll.user32.EnumWindows
    _EnumWindows.argtypes = [WNDENUMPROC, LPARAM]
    _EnumWindows.restype = bool

    EnumFunc = __EnumWndProc()
    lpEnumFunc = WNDENUMPROC(EnumFunc)
    if not _EnumWindows(lpEnumFunc, NULL):
        errcode = GetLastError()
        if errcode not in (ERROR_NO_MORE_FILES, ERROR_SUCCESS):
            raise ctypes.WinError(errcode)
    return EnumFunc.hwnd


# BOOL CALLBACK EnumChildProc(
#     HWND hwnd,
#     LPARAM lParam
# ); 
Example #7
Source File: winapi.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def EnumChildWindows(hWndParent=NULL):
    _EnumChildWindows = windll.user32.EnumChildWindows
    _EnumChildWindows.argtypes = [HWND, WNDENUMPROC, LPARAM]
    _EnumChildWindows.restype = bool

    EnumFunc = __EnumChildProc()
    lpEnumFunc = WNDENUMPROC(EnumFunc)
    SetLastError(ERROR_SUCCESS)
    _EnumChildWindows(hWndParent, lpEnumFunc, NULL)
    errcode = GetLastError()
    if errcode != ERROR_SUCCESS and errcode not in \
            (ERROR_NO_MORE_FILES, ERROR_SUCCESS):
        raise ctypes.WinError(errcode)
    return EnumFunc.hwnd


# int WINAPI GetWindowText(
#   __in   HWND hWnd,
#   __out  LPTSTR lpString,
#   __in   int nMaxCount
# ); 
Example #8
Source File: winapi.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def GetWindowTextA(hWnd):
    _GetWindowTextA = windll.user32.GetWindowTextA
    _GetWindowTextA.argtypes = [HWND, LPSTR, ctypes.c_int]
    _GetWindowTextA.restype = ctypes.c_int

    nMaxCount = 0x1000
    dwCharSize = sizeof(CHAR)
    while 1:
        lpString = ctypes.create_string_buffer(nMaxCount)
        nCount = _GetWindowTextA(hWnd, lpString, nMaxCount)
        if nCount == 0:
            raise ctypes.WinError()
        if nCount < nMaxCount - dwCharSize:
            break
        nMaxCount += 0x1000
    return str(lpString.value) 
Example #9
Source File: winapi.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def GetWindowTextW(hWnd):
    _GetWindowTextW = windll.user32.GetWindowTextW
    _GetWindowTextW.argtypes = [HWND, LPWSTR, ctypes.c_int]
    _GetWindowTextW.restype = ctypes.c_int

    nMaxCount = 0x1000
    dwCharSize = sizeof(CHAR)
    while 1:
        lpString = ctypes.create_string_buffer(nMaxCount)
        nCount = _GetWindowTextW(hWnd, lpString, nMaxCount)
        if nCount == 0:
            raise ctypes.WinError()
        if nCount < nMaxCount - dwCharSize:
            break
        nMaxCount += 0x1000
    return str(lpString.value) 
Example #10
Source File: winapi.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def GetClassNameA(hWnd):
    _GetClassNameA = windll.user32.GetClassNameA
    _GetClassNameA.argtypes = [HWND, LPSTR, ctypes.c_int]
    _GetClassNameA.restype = ctypes.c_int

    nMaxCount = 0x1000
    dwCharSize = sizeof(CHAR)
    while 1:
        lpClassName = ctypes.create_string_buffer(nMaxCount)
        nCount = _GetClassNameA(hWnd, lpClassName, nMaxCount)
        if nCount == 0:
            raise ctypes.WinError()
        if nCount < nMaxCount - dwCharSize:
            break
        nMaxCount += 0x1000
    return str(lpClassName.value) 
Example #11
Source File: createminidump.py    From minidump with 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 #12
Source File: createminidump.py    From minidump with MIT License 6 votes vote down vote up
def enum_pids():
	
	max_array = c_ulong * 4096 # define long array to capture all the processes
	pProcessIds = max_array() # array to store the list of processes
	pBytesReturned = c_ulong() # the number of bytes returned in the array
	#EnumProcess 
	res = EnumProcesses(
		ctypes.byref(pProcessIds),
		ctypes.sizeof(pProcessIds),
		ctypes.byref(pBytesReturned)
	)
	if res == 0:
		logging.error(WinError(get_last_error()))
		return []
  
	# get the number of returned processes
	nReturned = int(pBytesReturned.value/ctypes.sizeof(c_ulong()))
	return [i for i in pProcessIds[:nReturned]]
	
#https://msdn.microsoft.com/en-us/library/windows/desktop/ms683217(v=vs.85).aspx 
Example #13
Source File: windows_support.py    From lambda-packs with MIT License 6 votes vote down vote up
def hide_file(path):
    """
    Set the hidden attribute on a file or directory.

    From http://stackoverflow.com/questions/19622133/

    `path` must be text.
    """
    __import__('ctypes.wintypes')
    SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
    SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
    SetFileAttributes.restype = ctypes.wintypes.BOOL

    FILE_ATTRIBUTE_HIDDEN = 0x02

    ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
    if not ret:
        raise ctypes.WinError() 
Example #14
Source File: windows_support.py    From python-netsurv with MIT License 6 votes vote down vote up
def hide_file(path):
    """
    Set the hidden attribute on a file or directory.

    From http://stackoverflow.com/questions/19622133/

    `path` must be text.
    """
    __import__('ctypes.wintypes')
    SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
    SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
    SetFileAttributes.restype = ctypes.wintypes.BOOL

    FILE_ATTRIBUTE_HIDDEN = 0x02

    ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
    if not ret:
        raise ctypes.WinError() 
Example #15
Source File: _environ.py    From bugatsinho.github.io with GNU General Public License v3.0 6 votes vote down vote up
def get_windows_env_var(key):
    """Get an env var.

    Raises:
        WindowsError
    """

    if not isinstance(key, text_type):
        raise TypeError("%r not of type %r" % (key, text_type))

    buf = ctypes.create_unicode_buffer(32767)

    stored = winapi.GetEnvironmentVariableW(key, buf, 32767)
    if stored == 0:
        raise ctypes.WinError()
    return buf[:stored] 
Example #16
Source File: support.py    From jawfish with MIT License 6 votes vote down vote up
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
Example #17
Source File: registry.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def QueryValueEx(key, value_name):
    """This calls the Windows QueryValueEx function in a Unicode safe way."""
    size = 256
    data_type = ctypes.wintypes.DWORD()
    while True:
        tmp_size = ctypes.wintypes.DWORD(size)
        buf = ctypes.create_string_buffer(size)
        rc = RegQueryValueEx(key.handle, value_name, LPDWORD(),
                             ctypes.byref(data_type), ctypes.cast(buf, LPBYTE),
                             ctypes.byref(tmp_size))
        if rc != ERROR_MORE_DATA:
            break

        # We limit the size here to ~10 MB so the response doesn't get too big.
        if size > 10 * 1024 * 1024:
            raise WindowsError("Value too big to be read.")

        size *= 2

    if rc != ERROR_SUCCESS:
        raise ctypes.WinError(2)

    return (Reg2Py(buf, tmp_size.value, data_type.value), data_type.value) 
Example #18
Source File: support.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def _is_gui_available():
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        return bool(uof.dwFlags & WSF_VISIBLE) 
Example #19
Source File: windows_support.py    From python-netsurv with MIT License 6 votes vote down vote up
def hide_file(path):
    """
    Set the hidden attribute on a file or directory.

    From http://stackoverflow.com/questions/19622133/

    `path` must be text.
    """
    __import__('ctypes.wintypes')
    SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
    SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD
    SetFileAttributes.restype = ctypes.wintypes.BOOL

    FILE_ATTRIBUTE_HIDDEN = 0x02

    ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)
    if not ret:
        raise ctypes.WinError() 
Example #20
Source File: link.py    From core with MIT License 6 votes vote down vote up
def _create_windows(source, destination, link_type):
    """Creates hardlink at destination from source in Windows."""

    if link_type == HARDLINK:
        import ctypes
        from ctypes.wintypes import BOOL
        CreateHardLink = ctypes.windll.kernel32.CreateHardLinkW
        CreateHardLink.argtypes = [
            ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_void_p
        ]
        CreateHardLink.restype = BOOL

        res = CreateHardLink(destination, source, None)
        if res == 0:
            raise ctypes.WinError()
    else:
        raise NotImplementedError("Link type unrecognized.") 
Example #21
Source File: _print.py    From bugatsinho.github.io with GNU General Public License v3.0 5 votes vote down vote up
def _readline_windows():
    """Raises OSError"""

    try:
        fileno = sys.stdin.fileno()
    except (EnvironmentError, AttributeError):
        fileno = -1

    # In case stdin is replaced, read from that
    if fileno != 0:
        return _readline_windows_fallback()

    h = winapi.GetStdHandle(winapi.STD_INPUT_HANDLE)
    if h == winapi.INVALID_HANDLE_VALUE:
        return _readline_windows_fallback()

    buf_size = 1024
    buf = ctypes.create_string_buffer(buf_size * ctypes.sizeof(winapi.WCHAR))
    read = winapi.DWORD()

    text = u""
    while True:
        if winapi.ReadConsoleW(
                h, buf, buf_size, ctypes.byref(read), None) == 0:
            if not text:
                return _readline_windows_fallback()
            raise ctypes.WinError()
        data = buf[:read.value * ctypes.sizeof(winapi.WCHAR)]
        text += data.decode("utf-16-le", _surrogatepass)
        if text.endswith(u"\r\n"):
            return text[:-2] 
Example #22
Source File: _print.py    From bugatsinho.github.io with GNU General Public License v3.0 5 votes vote down vote up
def _encode_codepage(codepage, text):
    """
    Args:
        codepage (int)
        text (text)
    Returns:
        `bytes`

    Encode text using the given code page. Will not fail if a char
    can't be encoded using that codepage.
    """

    assert isinstance(text, text_type)

    if not text:
        return b""

    size = (len(text.encode("utf-16-le", _surrogatepass)) //
            ctypes.sizeof(winapi.WCHAR))

    # get the required buffer size
    length = winapi.WideCharToMultiByte(
        codepage, 0, text, size, None, 0, None, None)
    if length == 0:
        raise ctypes.WinError()

    # decode to the buffer
    buf = ctypes.create_string_buffer(length)
    length = winapi.WideCharToMultiByte(
        codepage, 0, text, size, buf, length, None, None)
    if length == 0:
        raise ctypes.WinError()
    return buf[:length] 
Example #23
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def _handle_errors(rv):
        if not rv:
            raise WinError() 
Example #24
Source File: _environ.py    From bugatsinho.github.io with GNU General Public License v3.0 5 votes vote down vote up
def read_windows_environ():
    """Returns a unicode dict of the Windows environment.

    Raises:
        WindowsEnvironError
    """

    res = winapi.GetEnvironmentStringsW()
    if not res:
        raise ctypes.WinError()

    res = ctypes.cast(res, ctypes.POINTER(ctypes.c_wchar))

    done = []
    current = u""
    i = 0
    while 1:
        c = res[i]
        i += 1
        if c == u"\x00":
            if not current:
                break
            done.append(current)
            current = u""
            continue
        current += c

    dict_ = {}
    for entry in done:
        try:
            key, value = entry.split(u"=", 1)
        except ValueError:
            continue
        key = _norm_key(key)
        dict_[key] = value

    status = winapi.FreeEnvironmentStringsW(res)
    if status == 0:
        raise ctypes.WinError()

    return dict_ 
Example #25
Source File: exceptions.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def __init__(self, message):
        message += " ({err})".format(err=ctypes.WinError())
        super(PyperclipWindowsException, self).__init__(message) 
Example #26
Source File: windows.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def set_close_exec(fd: int) -> None:
    success = SetHandleInformation(fd, HANDLE_FLAG_INHERIT, 0)
    if not success:
        raise ctypes.WinError()  # type: ignore 
Example #27
Source File: test_etw.py    From pywintrace with Apache License 2.0 5 votes vote down vote up
def makeRequest(cls):
        """
        Issue a WININET request based on the class parameters.

        :return: None
        """
        hInternet = wi.InternetOpenW(
            cls.user_agent,
            wi.INTERNET_OPEN_TYPE_DIRECT, None, None, 0)
        if hInternet is None:
            raise ct.WinError()

        hSession = wi.InternetConnectW(hInternet, cls.url, cls.port, None, None, wi.INTERNET_SERVICE_HTTP, 0, 0)
        if hSession is None:
            raise ct.WinError()

        hRequest = wi.HttpOpenRequestW(hSession, cls.verb, '', None, None, None, 0, 0)
        if hRequest is None:
            raise ct.WinError()

        request_sent = wi.HttpSendRequestW(hRequest, None, 0, None, 0)
        if request_sent == 0:
            raise ct.WinError()

        # Setup the necessary parameters to read the server's response
        buff_size = wt.DWORD(cls.size)
        buf = (ct.c_char * buff_size.value)()
        keep_reading = 1
        bytes_read = wt.DWORD(-1)
        response_str = str()

        while keep_reading == 1 and bytes_read.value != 0:
            # Read the entire response.
            keep_reading = wi.InternetReadFile(hRequest, buf, buff_size, ct.byref(bytes_read))
            response_str += str(buf.value)

        return response_str 
Example #28
Source File: etw.py    From pywintrace with Apache License 2.0 5 votes vote down vote up
def stop(self):
        """
        Wraps the necessary processes needed for stopping an ETW provider session.

        :return: Does not return anything
        """
        # don't stop if we don't have a handle, or it's the kernel trace and we started it ourself
        if (
            (self.session_handle.value == 0 and self.kernel_trace is False)
            or (self.kernel_trace is True and self.kernel_trace_was_running is True)
        ):
            return

        if self.kernel_trace is False:
            for provider in self.providers:

                status = et.EnableTraceEx2(self.session_handle,
                                           ct.byref(provider.guid),
                                           et.EVENT_CONTROL_CODE_DISABLE_PROVIDER,
                                           provider.level,
                                           provider.any_bitmask,
                                           provider.all_bitmask,
                                           0,
                                           None)
                if status != tdh.ERROR_SUCCESS:
                    raise ct.WinError(status)

        status = et.ControlTraceW(self.session_handle,
                                  self.session_name,
                                  self.session_properties.get(),
                                  et.EVENT_TRACE_CONTROL_STOP)
        if status != tdh.ERROR_SUCCESS:
            raise ct.WinError(status)

        et.CloseTrace(self.session_handle) 
Example #29
Source File: etw.py    From pywintrace with Apache License 2.0 5 votes vote down vote up
def start(self):
        """
        Wraps the necessary processes needed for starting an ETW provider session.

        :return:  Does not return anything.
        """
        self.kernel_trace_was_running = False
        if self.kernel_trace is True:
            provider = self.providers[0]  # there should only be one provider
            self.session_properties.get().contents.Wnode.Guid = provider.guid
            self.session_properties.get().contents.LogFileMode |= et.EVENT_TRACE_SYSTEM_LOGGER_MODE

            if provider.any_bitmask:
                self.session_properties.get().contents.EnableFlags = provider.any_bitmask
            else:
                self.session_properties.get().contents.EnableFlags = et.DEFAULT_NT_KERNEL_LOGGER_FLAGS

        status = et.StartTraceW(ct.byref(self.session_handle), self.session_name, self.session_properties.get())
        if status != tdh.ERROR_SUCCESS:
            if self.kernel_trace is True and status == tdh.ERROR_ALREADY_EXISTS:
                self.kernel_trace_was_running = True
            raise ct.WinError(status)

        if self.kernel_trace is False:
            for provider in self.providers:

                if provider.params:
                    provider.params.contents.SourceId = self.session_properties.get().contents.Wnode.Guid

                status = et.EnableTraceEx2(self.session_handle,
                                           ct.byref(provider.guid),
                                           et.EVENT_CONTROL_CODE_ENABLE_PROVIDER,
                                           provider.level,
                                           provider.any_bitmask,
                                           provider.all_bitmask,
                                           0,
                                           provider.params)
                if status != tdh.ERROR_SUCCESS:
                    raise ct.WinError(status) 
Example #30
Source File: etw.py    From pywintrace with Apache License 2.0 5 votes vote down vote up
def start(self):
        """
        Starts a trace consumer.

        :return: Returns True on Success or False on Failure
        """
        self.trace_handle = et.OpenTraceW(ct.byref(self.trace_logfile))
        if self.trace_handle == et.INVALID_PROCESSTRACE_HANDLE:
            raise ct.WinError()

        # For whatever reason, the restype is ignored
        self.trace_handle = et.TRACEHANDLE(self.trace_handle)
        self.process_thread = threading.Thread(target=self._run, args=(self.trace_handle, self.end_capture))
        self.process_thread.daemon = True
        self.process_thread.start()