我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.WinDLL()。
def command_detach(self): detach_threads() # unload debugger DLL global debugger_dll_handle if debugger_dll_handle is not None: k32 = ctypes.WinDLL('kernel32') k32.FreeLibrary.argtypes = [ctypes.c_void_p] k32.FreeLibrary(debugger_dll_handle) debugger_dll_handle = None with _SendLockCtx: write_bytes(conn, DETC) detach_process() for callback in DETACH_CALLBACKS: callback() raise DebuggerExitException()
def get_windows_disks(self): """ Return disks available on Windows machine :return: list of characters representing available disks """ disks = list() import ctypes kernel32 = ctypes.WinDLL('kernel32') SEM_FAILCRITICALERRORS = 1 SEM_NOOPENFILEERRORBOX = 0x8000 SEM_FAIL = SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS oldmode = ctypes.c_uint() kernel32.SetThreadErrorMode(SEM_FAIL, ctypes.byref(oldmode)) for s in string.ascii_uppercase: n = s + WINDOWS_DISK_SUFFIX if os.path.exists(n): disks.append(n) kernel32.SetThreadErrorMode(oldmode, ctypes.byref(oldmode)) return disks
def load_call_dict(call_dict, lib): """Loads argument/return types from the call dictionary @param call_dict: call dictionary. Keyed by function name; values are [return type, argtype0, argtype 1...] @type call_dict: dict @param lib: library where functions specified in L{call_dict} live. @type lib: ctypes.WinDLL or ctypes.CDLL """ for funcname in call_dict: func = getattr(lib, funcname) args = call_dict[funcname] func.restype = args[0] if len(args) <= 1: func.argtypes = None else: func.argtypes = args[1:]
def __loaddll(self, fp=None): if fp != None: if os.path.exists(fp): self.nnotesdll = ctypes.WinDLL(fp) else: self.nnotesdll = None else: self.nnotesdll = None try: # If we already have the COM/DDE interface to Notes, then nlsxbe.dll # is already loaded, so we can just try and get nnotes.dll leaving # Windows to search in its default search path self.nnotesdll = ctypes.WinDLL('nnotes.dll') except OSError: # Try harder for p in notesDllPathList: fp = os.path.join(p, 'nnotes.dll') if os.path.exists(fp): self.nnotesdll = ctypes.WinDLL(fp) break
def psloadlib(name): """ Loads driver library :param name: driver name :type name: str :returns: ctypes reference to the library :rtype: object """ result = None try: if sys.platform == 'win32': result = ctypes.WinDLL(find_library(name)) else: result = cdll.LoadLibrary(find_library(name)) except OSError as ex: print name, "import(%d): Library not found" % sys.exc_info()[-1].tb_lineno return result
def get(): '''get Returns the library.Library singleton for nifgen. ''' global _instance global _instance_lock with _instance_lock: if _instance is None: try: library_type = _get_library_type() if library_type == 'windll': ctypes_library = ctypes.WinDLL(_get_library_name()) else: assert library_type == 'cdll' ctypes_library = ctypes.CDLL(_get_library_name()) except OSError: raise errors.DriverNotInstalledError() _instance = library.Library(ctypes_library) return _instance
def get(): '''get Returns the library.Library singleton for niscope. ''' global _instance global _instance_lock with _instance_lock: if _instance is None: try: library_type = _get_library_type() if library_type == 'windll': ctypes_library = ctypes.WinDLL(_get_library_name()) else: assert library_type == 'cdll' ctypes_library = ctypes.CDLL(_get_library_name()) except OSError: raise errors.DriverNotInstalledError() _instance = library.Library(ctypes_library) return _instance
def get(): '''get Returns the library.Library singleton for niswitch. ''' global _instance global _instance_lock with _instance_lock: if _instance is None: try: library_type = _get_library_type() if library_type == 'windll': ctypes_library = ctypes.WinDLL(_get_library_name()) else: assert library_type == 'cdll' ctypes_library = ctypes.CDLL(_get_library_name()) except OSError: raise errors.DriverNotInstalledError() _instance = library.Library(ctypes_library) return _instance
def get(): '''get Returns the library.Library singleton for nimodinst. ''' global _instance global _instance_lock with _instance_lock: if _instance is None: try: library_type = _get_library_type() if library_type == 'windll': ctypes_library = ctypes.WinDLL(_get_library_name()) else: assert library_type == 'cdll' ctypes_library = ctypes.CDLL(_get_library_name()) except OSError: raise errors.DriverNotInstalledError() _instance = library.Library(ctypes_library) return _instance
def get(): '''get Returns the library.Library singleton for nidmm. ''' global _instance global _instance_lock with _instance_lock: if _instance is None: try: library_type = _get_library_type() if library_type == 'windll': ctypes_library = ctypes.WinDLL(_get_library_name()) else: assert library_type == 'cdll' ctypes_library = ctypes.CDLL(_get_library_name()) except OSError: raise errors.DriverNotInstalledError() _instance = library.Library(ctypes_library) return _instance
def get(): '''get Returns the library.Library singleton for nidcpower. ''' global _instance global _instance_lock with _instance_lock: if _instance is None: try: library_type = _get_library_type() if library_type == 'windll': ctypes_library = ctypes.WinDLL(_get_library_name()) else: assert library_type == 'cdll' ctypes_library = ctypes.CDLL(_get_library_name()) except OSError: raise errors.DriverNotInstalledError() _instance = library.Library(ctypes_library) return _instance
def win32_get_app_data_path(*args): shell32 = ctypes.WinDLL("shell32.dll") SHGetFolderPath = shell32.SHGetFolderPathW SHGetFolderPath.argtypes = ( ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_wchar_p) SHGetFolderPath.restype = ctypes.c_uint32 CSIDL_LOCAL_APPDATA = 0x001c MAX_PATH = 260 buf = ctypes.create_unicode_buffer(MAX_PATH) res = SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, 0, buf) if res != 0: raise Exception("Could not deterime APPDATA path") return os.path.join(buf.value, *args)
def remove_ca(self, name): import ctypes import ctypes.wintypes class CERT_CONTEXT(ctypes.Structure): _fields_ = [ ('dwCertEncodingType', ctypes.wintypes.DWORD), ('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)), ('cbCertEncoded', ctypes.wintypes.DWORD), ('pCertInfo', ctypes.c_void_p), ('hCertStore', ctypes.c_void_p),] crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode()) store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode()) pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None) while pCertCtx: certCtx = CERT_CONTEXT.from_address(pCertCtx) certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded) cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, certdata) if hasattr(cert, 'get_subject'): cert = cert.get_subject() cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '') if cert_name and name.lower() == cert_name.split()[0].lower(): crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx)) pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx) return 0
def remove_cert(name): if os.name == 'nt': import ctypes, ctypes.wintypes class CERT_CONTEXT(ctypes.Structure): _fields_ = [ ('dwCertEncodingType', ctypes.wintypes.DWORD), ('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)), ('cbCertEncoded', ctypes.wintypes.DWORD), ('pCertInfo', ctypes.c_void_p), ('hCertStore', ctypes.c_void_p),] crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode()) store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode()) pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None) while pCertCtx: certCtx = CERT_CONTEXT.from_address(pCertCtx) certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded) cert = crypto.load_certificate(crypto.FILETYPE_ASN1, certdata) if hasattr(cert, 'get_subject'): cert = cert.get_subject() cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '') if cert_name and name == cert_name: crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx)) pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx) return 0 return -1
def test_self_iat_hook_multithread(): """Test IAT hook in current process with multi thread trigger""" cp = windows.current_process # Might change this to XP compat ? kernelbase_mod = [m for m in cp.peb.modules if m.name == "kernelbase.dll"][0] LdrLoadDll = [n for n in kernelbase_mod.pe.imports['ntdll.dll'] if n.name == "LdrLoadDll"][0] calling_thread = set([]) @windows.hooks.LdrLoadDllCallback def MyHook(*args, **kwargs): calling_thread.add(windows.current_thread.tid) return kwargs["real_function"]() x = LdrLoadDll.set_hook(MyHook) # Trigger from local thread ctypes.WinDLL("kernel32.dll") assert calling_thread == set([windows.current_thread.tid]) # Trigger from another thread k32 = [m for m in cp.peb.modules if m.name == "kernel32.dll"][0] load_libraryA = k32.pe.exports["LoadLibraryA"] with cp.allocated_memory(0x1000) as addr: cp.write_memory(addr, "DLLNOTFOUND.NOT_A_REAL_DLL" + "\x00") t = cp.create_thread(load_libraryA, addr) t.wait() assert len(calling_thread) == 2 x.disable()
def _get_func_addr(dll_name, func_name): # Load the DLL ctypes.WinDLL(dll_name) modules = windows.current_process.peb.modules if not dll_name.lower().endswith(".dll"): dll_name += ".dll" mod = [x for x in modules if x.name == dll_name][0] return mod.pe.exports[func_name]
def get_func_addr(dll_name, func_name): # Load the DLL ctypes.WinDLL(dll_name) modules = windows.current_process.peb.modules if not dll_name.lower().endswith(".dll"): dll_name += ".dll" mod = [x for x in modules if x.name == dll_name][0] return mod.pe.exports[func_name]
def _command_line_to_args_list(cmdline): """splits a string into a list using Windows command line syntax.""" args_list = [] if cmdline and cmdline.strip(): from ctypes import c_int, c_voidp, c_wchar_p from ctypes import byref, POINTER, WinDLL clta = WinDLL('shell32').CommandLineToArgvW clta.argtypes = [c_wchar_p, POINTER(c_int)] clta.restype = POINTER(c_wchar_p) lf = WinDLL('kernel32').LocalFree lf.argtypes = [c_voidp] pNumArgs = c_int() r = clta(cmdline, byref(pNumArgs)) if r: for index in range(0, pNumArgs.value): if sys.hexversion >= 0x030000F0: argval = r[index] else: argval = r[index].encode('ascii', 'replace') args_list.append(argval) lf(r) else: sys.stderr.write('Error parsing script arguments:\n') sys.stderr.write(cmdline + '\n') return args_list
def __init__(self, tzres_loc='tzres.dll'): # Load the user32 DLL so we can load strings from tzres user32 = ctypes.WinDLL('user32') # Specify the LoadStringW function user32.LoadStringW.argtypes = (wintypes.HINSTANCE, wintypes.UINT, wintypes.LPWSTR, ctypes.c_int) self.LoadStringW = user32.LoadStringW self._tzres = ctypes.WinDLL(tzres_loc) self.tzres_loc = tzres_loc
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
def remove_windows_ca(name): import ctypes import ctypes.wintypes class CERT_CONTEXT(ctypes.Structure): _fields_ = [ ('dwCertEncodingType', ctypes.wintypes.DWORD), ('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)), ('cbCertEncoded', ctypes.wintypes.DWORD), ('pCertInfo', ctypes.c_void_p), ('hCertStore', ctypes.c_void_p),] try: crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode()) store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode()) pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None) while pCertCtx: certCtx = CERT_CONTEXT.from_address(pCertCtx) certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded) cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, certdata) if hasattr(cert, 'get_subject'): cert = cert.get_subject() cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '') if cert_name and name == cert_name: crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx)) pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx) except Exception as e: logging.warning('CertUtil.remove_windows_ca failed: %r', e)
def remove_windows_ca(name): import ctypes import ctypes.wintypes class CERT_CONTEXT(ctypes.Structure): _fields_ = [ ('dwCertEncodingType', ctypes.wintypes.DWORD), ('pbCertEncoded', ctypes.POINTER(ctypes.wintypes.BYTE)), ('cbCertEncoded', ctypes.wintypes.DWORD), ('pCertInfo', ctypes.c_void_p), ('hCertStore', ctypes.c_void_p),] try: crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode()) store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode()) pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, None) while pCertCtx: certCtx = CERT_CONTEXT.from_address(pCertCtx) certdata = ctypes.string_at(certCtx.pbCertEncoded, certCtx.cbCertEncoded) cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, certdata) if hasattr(cert, 'get_subject'): cert = cert.get_subject() cert_name = next((v for k, v in cert.get_components() if k == 'CN'), '') if cert_name and name == cert_name: crypt32.CertDeleteCertificateFromStore(crypt32.CertDuplicateCertificateContext(pCertCtx)) pCertCtx = crypt32.CertEnumCertificatesInStore(store_handle, pCertCtx) except Exception as e: xlog.warning('CertUtil.remove_windows_ca failed: %r', e)
def get_capslock_state(): state = False if platform.system() == "Windows": hllDll = ctypes.WinDLL ("User32.dll") VK_CAPITAL = 0x14 if hllDll.GetKeyState(VK_CAPITAL): state = True else: state = False else: if subprocess.check_output('xset q | grep LED', shell=True)[65] == 50 : state = False if subprocess.check_output('xset q | grep LED', shell=True)[65] == 51 : state = True return state
def get_load_func(type, candidates): def _load_library(find_library=None): exec_path = sys._MEIPASS l = None for candidate in candidates: # Do linker's path lookup work to force load bundled copy. if os.name == 'posix' and sys.platform == 'darwin': libs = glob.glob("%s/%s*.dylib*" % (exec_path, candidate)) elif sys.platform == 'win32' or sys.platform == 'cygwin': libs = glob.glob("%s\\%s*.dll" % (exec_path, candidate)) else: libs = glob.glob("%s/%s*.so*" % (exec_path, candidate)) for libname in libs: try: # NOTE: libusb01 is using CDLL under win32. # (see usb.backends.libusb01) if sys.platform == 'win32' and type != 'libusb01': l = ctypes.WinDLL(libname) else: l = ctypes.CDLL(libname) if l is not None: break except: l = None if l is not None: break else: raise OSError('USB library could not be found') if type == 'libusb10': if not hasattr(l, 'libusb_init'): raise OSError('USB library could not be found') return l return _load_library # NOTE: Need to keep in sync with future PyUSB updates.
def load_lib(): """Find and load libspacepy Normally this will be in the directory where spacepy is installed, under libspacepy. @return: the open library @rtype: ctypes.CDLL or ctypes.WinDLL """ libdir = os.path.dirname(os.path.abspath(__file__)) if sys.platform == 'win32': libnames = ['spacepy.dll'] elif sys.platform == 'darwin': libnames = ['libspacepy.dylib', 'libspacepy.so', 'spacepy.dylib', 'spacepy.so'] else: libnames = ['libspacepy.so'] if sysconfig: ext = sysconfig.get_config_var('SO') if ext: libnames.append('libspacepy' + ext) libnames.append('spacepy' + ext) libpath = None for n in libnames: libpath = os.path.join(libdir, n) if os.path.exists(libpath): break if libpath and os.path.exists(libpath): return ctypes.CDLL(libpath) else: return None