def write(self, data): if _isDebug(): log.debug("Write: %r" % data) size = self._writeSize or len(data) buf = ctypes.create_string_buffer(size) buf.raw = data if not ctypes.windll.kernel32.WriteFile(self._writeFile, data, size, None, byref(self._writeOl)): if ctypes.GetLastError() != ERROR_IO_PENDING: if _isDebug(): log.debug("Write failed: %s" % ctypes.WinError()) raise ctypes.WinError() bytes = DWORD() ctypes.windll.kernel32.GetOverlappedResult(self._writeFile, byref(self._writeOl), byref(bytes), True)
def getCurrentSessionId(): if sys.platform == "win32": import ctypes from ctypes.wintypes import DWORD pid = os.getpid() result = DWORD() ok = ctypes.windll.kernel32.ProcessIdToSessionId(pid, ctypes.byref(result)) if not ok: error = ctypes.GetLastError() raise WindowsError(error) return result.value else: raise NotImplementedError()
def replace_transactional(source, destination): # Like os.replace, but tries to be actually atomic when possible on Windows. if windll: error_code = 50 # ERROR_NOT_SUPPORTED if windll.ktmw32: tx = windll.ktmw32.CreateTransaction(None, None, 0, 0, 0, 0, None) if tx != HANDLE(-1).value: try: error_code = 0 if windll.kernel32.MoveFileTransactedW( source, destination, windll.kernel32.MoveFileTransactedW.argtypes[2](), None, 0x1 | 0x2, tx) and windll.ktmw32.CommitTransaction( tx) else ctypes.GetLastError() finally: windll.kernel32.CloseHandle(tx) else: error_code = ctypes.GetLastError() if error_code: raise ctypes.WinError(error_code) else: raise NotImplementedError("transactional file systems not supported")
def _ctypes_is_local_pid_dead(pid): """True if pid doesn't correspond to live process on this machine""" handle = _OpenProcess(1, False, pid) # PROCESS_TERMINATE if not handle: errorcode = ctypes.GetLastError() if errorcode == 5: # ERROR_ACCESS_DENIED # Probably something alive we're not allowed to kill return False elif errorcode == 87: # ERROR_INVALID_PARAMETER return True raise ctypes.WinError(errorcode) _CloseHandle(handle) return False
def fcntl(fd, op, arg=0): if op == F_GETFD or op == F_GETFL: return 0 elif op == F_SETFD: # Check that the flag is CLOEXEC and translate if arg == FD_CLOEXEC: success = SetHandleInformation(fd, HANDLE_FLAG_INHERIT, arg) if not success: raise ctypes.GetLastError() else: raise ValueError("Unsupported arg") else: raise ValueError("Unsupported op")
def FindNextVolumeMountPoint (hSearch): u"""Find the next volume mount point which the system recognises in the set provided by a search handle returned by FindFirstVolumeMountPoint. If there are no more in this set, close the handle and return None. """ volume_mount_point_name = ctypes.create_unicode_buffer (u" " * VOLUME_NAME_LENGTH) if kernel32.FindNextVolumeMountPointW (hSearch, volume_mount_point_name, VOLUME_NAME_LENGTH) != 0: return volume_mount_point_name.value else: if ctypes.GetLastError () == winerror.ERROR_NO_MORE_FILES: FindVolumeMountPointClose (hSearch) return None else: return error (x_kernel32, "FindNextVolumeMountPoint")
def write(self, data: bytes): if not isinstance(data, bytes): raise TypeError("Expected argument 'data' to be of type 'bytes'") if _isDebug(): log.debug("Write: %r" % data) size, data = self._prepareWriteBuffer(data) if not ctypes.windll.kernel32.WriteFile(self._writeFile, data, size, None, byref(self._writeOl)): if ctypes.GetLastError() != ERROR_IO_PENDING: if _isDebug(): log.debug("Write failed: %s" % ctypes.WinError()) raise ctypes.WinError() byteData = DWORD() ctypes.windll.kernel32.GetOverlappedResult(self._writeFile, byref(self._writeOl), byref(byteData), True)
def __init__(self,pid): self.row_address = 0x01005338 self.col_address = 0x01005334 self.game_time_address = 0x100579C self.bome_count_address = 0x01005194 self.pid = pid self.block_start_address = 0x01005340 self.handle =OpenProcess(PROCESS_ALL_ACCESS,False,int(pid)) if not self.handle: print ("error get handle of pid %s" % pid) raise Exception("error %s" % ctypes.GetLastError() ) exit(1)
def run_shell_code(self,shellcode): shellcode_length = len(shellcode) arg_address = self.allocate(self.handle,0,shellcode_length,VIRTUAL_MEM,PAGE_READWRITE) whhh=self.write_buffer(self.handle,arg_address,shellcode,shellcode_length) thread_id = ctypes.c_ulong(0) thread =ctypes.windll.kernel32.CreateRemoteThread(self.handle,None,0,arg_address,None,0,ctypes.byref(thread_id)) if not thread: raise Exception('Error: %s' %ctypes.GetLastError()) ctypes.windll.kernel32.WaitForSingleObject(thread,0xFFFFFFFF) #一定要close要不会挂,暂时原因不知道 ctypes.windll.kernel32.CloseHandle(thread) #调试的时候这句要关闭,要不attach上去的时候地址就被处理了 ctypes.windll.kernel32.VirtualFreeEx(self.handle, arg_address, shellcode_length, MEM_DECOMMIT)
def _get_ir_receiver_paths(): DeviceInfoSet = SetupDiGetClassDevs(ctypes.byref(GUID_CLASS_IRBUS), NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE) if DeviceInfoSet == INVALID_HANDLE_VALUE: raise ctypes.WinError() DeviceInterfaceData = SP_DEVICE_INTERFACE_DATA() DeviceInterfaceData.cbSize = ctypes.sizeof(SP_DEVICE_INTERFACE_DATA) DeviceInfoData = SP_DEVINFO_DATA() DeviceInfoData.cbSize = ctypes.sizeof(SP_DEVINFO_DATA) MemberIndex = 0 device_paths = [] while True: if not SetupDiEnumDeviceInterfaces( DeviceInfoSet, None, ctypes.byref(GUID_CLASS_IRBUS), MemberIndex, ctypes.byref(DeviceInterfaceData)): err = ctypes.GetLastError() if err == ERROR_NO_MORE_ITEMS: break else: raise ctypes.WinError(err) RequiredSize = DWORD() SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, ctypes.byref(DeviceInterfaceData), None, 0, ctypes.byref(RequiredSize), ctypes.byref(DeviceInfoData)) DevicePath = ctypes.create_string_buffer(RequiredSize.value) pDeviceInterfaceDetailData = ctypes.cast( DevicePath, PSP_DEVICE_INTERFACE_DETAIL_DATA) pDeviceInterfaceDetailData.contents.cbSize = ctypes.sizeof( SP_DEVICE_INTERFACE_DETAIL_DATA) SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, ctypes.byref(DeviceInterfaceData), pDeviceInterfaceDetailData, RequiredSize.value, ctypes.byref(RequiredSize), None) device_path = ctypes.wstring_at( ctypes.addressof(pDeviceInterfaceDetailData.contents) + 4) device_paths += [device_path] MemberIndex += 1 SetupDiDestroyDeviceInfoList(DeviceInfoSet) return device_paths
def GetLongPathName(short_path): """Returns the Windows long path equivalent for a 'short' path.""" path = fs.extend(short_path) chars = windll.kernel32.GetLongPathNameW(path, None, 0) if chars: p = wintypes.create_unicode_buffer(chars) if windll.kernel32.GetLongPathNameW(path, p, chars): return fs.trim(p.value) err = ctypes.GetLastError() if err: # pylint: disable=undefined-variable msg = u'GetLongPathName(%s): %s (%d)' % (short_path, FormatError(err), err) raise WindowsError(err, msg.encode('utf-8'))
def set_apod_wallpaper(settings): image_path_cbuff = bytes(settings.processed_image_path,encoding='utf-8') key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0") win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") retval = ctypes.windll.user32.SystemParametersInfoA(win32con.SPI_SETDESKWALLPAPER, len(image_path_cbuff), image_path_cbuff, win32con.SPIF_SENDWININICHANGE | win32con.SPIF_UPDATEINIFILE) if retval == 0: logging.error("SystemParametersInfoA(SPI_SETDESKWALLPAPER) returned = %d", retval) retval = ctypes.GetLastError() logging.error("GetLastError= %d", retval) return False logging.info('APOD image processing complete. Set as wallpaper') return True
def open(self): """ Open device to query properties :return: context """ handle = _setupapi.SetupDiCreateDeviceInfoList(None, None) if handle == -1: err_no = ctypes.GetLastError() raise WindowsError(err_no, ctypes.FormatError(err_no)) try: dev_info = DeviceInfoData() if not _setupapi.SetupDiOpenDeviceInfoW( handle, ctypes.create_unicode_buffer(self._instance_id), None, DIOD_INHERIT_CLASSDRVS, ctypes.byref(dev_info)): err_no = ctypes.GetLastError() raise WindowsError(err_no, ctypes.FormatError(err_no)) self._handle = (handle, dev_info, self._handle) # Stack yield self finally: if self._handle is not None and \ self._handle[0] == handle: # If last handle is opened in this function, pop it self._handle = self._handle[2] _setupapi.SetupDiDestroyDeviceInfoList(handle) # Close handle
def exists(name: str) -> bool: event = ctypes.windll.kernel32.OpenEventW( WindowsNamedEvent.__SYNCHRONIZE | WindowsNamedEvent.__EVENT_MODIFY_STATE, False, name) if event == 0: if ctypes.GetLastError( ) == WindowsNamedEvent.__ERROR_FILE_NOT_FOUND: return False else: WindowsNamedEvent.__raise_last_error() else: result = ctypes.windll.kernel32.CloseHandle(event) if result == 0: WindowsNamedEvent.__raise_last_error() return True
def read_option(self, handle, option): """ Reads information about the internet connection, which may be a string or struct :param handle: The handle to query for the info :param option: The (int) option to get :return: A string, or one of the InternetCertificateInfo or InternetProxyInfo structs """ option_buffer_size = 8192 try_again = True while try_again: try_again = False to_read_was_read = wintypes.DWORD(option_buffer_size) option_buffer = ctypes.create_string_buffer(option_buffer_size) ref = ctypes.byref(option_buffer) success = wininet.InternetQueryOptionA(handle, option, ref, ctypes.byref(to_read_was_read)) if not success: if ctypes.GetLastError() != self.ERROR_INSUFFICIENT_BUFFER: raise NonHttpError(self.extract_error()) # The error was a buffer that was too small, so try again option_buffer_size = to_read_was_read.value try_again = True continue if option == self.INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: length = min(len(option_buffer), ctypes.sizeof(InternetCertificateInfo)) cert_info = InternetCertificateInfo() ctypes.memmove(ctypes.addressof(cert_info), option_buffer, length) return cert_info elif option == self.INTERNET_OPTION_PROXY: length = min(len(option_buffer), ctypes.sizeof(InternetProxyInfo)) proxy_info = InternetProxyInfo() ctypes.memmove(ctypes.addressof(proxy_info), option_buffer, length) return proxy_info else: option = b'' if to_read_was_read.value > 0: option += option_buffer.raw[:to_read_was_read.value] return option.decode('cp1252').rstrip("\x00")
def setup_console_event_listener(handler, enable): try: from xpra.platform.win32.common import SetConsoleCtrlHandler, ConsoleCtrlHandler from xpra.log import Logger log = Logger("win32") log("calling SetConsoleCtrlHandler(%s, %s)", handler, enable) ctypes_handler = ConsoleCtrlHandler(handler) result = SetConsoleCtrlHandler(ctypes_handler, enable) log("SetConsoleCtrlHandler(%s, %s)=%s", handler, enable, result) if result==0: log.error("Error: could not %s console control handler:", "set" if enable else "unset") log.error(" SetConsoleCtrlHandler: %r", ctypes.GetLastError()) return False return True except Exception as e: log.error("SetConsoleCtrlHandler error: %s", e) return False