def uninstall_program(program, log_path, version=None, ignore_exit_code=False, no_wait=False): """ Uninstall MSI by program name :param program: object of type InstalledProductInfo() :param version: program version to uninstall :param log_path: :param ignore_exit_code: :return: """ if program.guid is None: raise Exception("Can't uninstall program. No program.guid.") command = r'msiexec.exe /norestart /q /X{0} /l! "{1}"'.format( program.guid, log_path) exit_code = Core.get_instance().api.os.shell.cmd(command, ignore_exit_code=True, no_wait=no_wait) if exit_code == 3010: # Reboot required code logging.warning( 'WARNING: Installation requested a system reboot.\nYou may need to reboot the system manually to complete this installation.' ) elif exit_code != 0 and not ignore_exit_code: # Other errors rise exception raise RuntimeError('Installation "{0}" failed: ({1}) {2}'.format( program.name, exit_code, win32api.FormatMessageW(exit_code))) return exit_code
def __init__(self, func=None, err=0): if err: self.err = err else: self.err = win32api.GetLastError() self.message = win32api.FormatMessageW(self.err) self.args = (self.err, func, self.message)
def install(filename, log_path, optional_parameters: dict = None, ignore_exit_code=False, no_wait=False): """ Install MSI with options :param filename: :param log_path: :param optional_parameters: :param ignore_exit_code: :param no_wait: """ command = r'msiexec.exe /norestart /q /i "{0}" /l! "{1}" ALLUSERS=1'.format( filename, log_path) if optional_parameters: for k, v in optional_parameters.items(): if v and v != "": command += ' {0}="{1}"'.format(k, v) exit_code = Core.get_instance().api.os.shell.cmd(command, ignore_exit_code=True, no_wait=no_wait) if exit_code == 3010: # Reboot required code logging.warning( 'WARNING: Installation requested a system reboot.\nYou may need to reboot the system manually to complete this installation.' ) elif exit_code != 0 and not ignore_exit_code: # Other errors rise exception raise RuntimeError('Installation "{0}" failed: ({1}) {2}'.format( filename, exit_code, win32api.FormatMessageW(exit_code))) return exit_code
def runas_shell_user(cmd, executable=None, creationflags=0, cwd=None, startupinfo=None, return_handles=False): if not creationflags & win32con.DETACHED_PROCESS: creationflags |= win32con.CREATE_NEW_CONSOLE if cwd is None: cwd = os.getcwd() si = _STARTUPINFO() if startupinfo: startupinfo_update(startupinfo, si) pi = PROCESS_INFORMATION() try: htoken = duplicate_shell_token() except pywintypes.error as e: if e.winerror != winerror.ERROR_FILE_NOT_FOUND: raise return runas_session_user(cmd, executable, creationflags, cwd, startupinfo, return_handles) with enable_privileges(win32security.SE_IMPERSONATE_NAME): if not advapi32.CreateProcessWithTokenW( int(htoken), 0, executable, cmd, creationflags, None, cwd, ctypes.byref(si), ctypes.byref(pi)): error = ctypes.get_last_error() raise pywintypes.error(error, 'CreateProcessWithTokenW', win32api.FormatMessageW(error)) hProcess = pywintypes.HANDLE(pi.hProcess) hThread = pywintypes.HANDLE(pi.hThread) if return_handles: return hProcess, hThread return pi.dwProcessId, pi.dwThreadId
def adjust_token_privileges(htoken, state): prev_state = win32security.AdjustTokenPrivileges(htoken, False, state) error = win32api.GetLastError() if error == winerror.ERROR_NOT_ALL_ASSIGNED: raise pywintypes.error(error, 'AdjustTokenPrivileges', win32api.FormatMessageW(error)) return prev_state
def expandString(event): cachekey = event.SourceName + "/" + str(event.EventID) try: if cachekey in DLLMSGCACHE: dllName = DLLMSGCACHE[cachekey] if dllName is None: return "" try: dllHandle = DLLCACHE[event.SourceName][dllName] except KeyError: from IPython import embed embed() data = win32api.FormatMessageW( win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, event.EventID, LANGID, event.StringInserts) return data elif event.SourceName not in DLLCACHE: LOGGER.warn("Event source not in cache".format( event.SourceName, event.EventID)) DLLMSGCACHE[cachekey] = None else: for (dllName, dllHandle) in DLLCACHE[event.SourceName].items(): try: data = win32api.FormatMessageW( win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, event.EventID, LANGID, event.StringInserts) DLLMSGCACHE[cachekey] = dllName return data except win32api.error: pass # not in this DLL except SystemError, e: pass # print str(e) # from IPython import embed # embed() except pywintypes.error: pass LOGGER.warn("Unable to expand data for {} EventID: {}".format( event.SourceName, event.EventID)) DLLMSGCACHE[cachekey] = None # no DLLs known to expand this message # from IPython import embed # embed() return ""
def run(args, cwd=None, as_admin=False, cmd_window=False): """ Run an arbitrary command. """ if isinstance(args, str): args = [args] args = list(args) if cwd is None: cwd = os.getenv("USERPROFILE") if as_admin: subprocess.call(args, shell=True, cwd=cwd) else: # We have to do all this nonsense to spawn the process # as the logged in user, rather than as the administrator # that PyleWM is running as startup_info = STARTUPINFO() process_information = PROCESS_INFORMATION() shell_window = ctypes.windll.user32.GetShellWindow() thread_id, process_id = win32process.GetWindowThreadProcessId( shell_window) shell_handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, process_id) shell_token = win32security.OpenProcessToken(shell_handle, win32con.TOKEN_DUPLICATE) spawn_token = win32security.DuplicateTokenEx( shell_token, win32security.SecurityImpersonation, win32con.TOKEN_QUERY | win32con.TOKEN_ASSIGN_PRIMARY | win32con.TOKEN_DUPLICATE | win32con.TOKEN_ADJUST_DEFAULT | 0x0100, win32security.TokenPrimary, None) escaped_commandline = "" for arg in args: escaped_commandline += '"' escaped_commandline += arg escaped_commandline += '" ' # Try to lookup where the exe is from PATH executable = args[0] if not os.path.isfile(executable): executable = shutil.which(executable) success = ctypes.windll.advapi32.CreateProcessWithTokenW( int(spawn_token), 0, executable, escaped_commandline, win32con.CREATE_NO_WINDOW if not cmd_window else win32con.CREATE_NEW_CONSOLE, None, os.getcwd(), ctypes.pointer(startup_info), ctypes.pointer(process_information)) if not success: error = ctypes.get_last_error() raise pywintypes.error(error, 'CreateProcessWithTokenW', win32api.FormatMessageW(error))
def FormatMessage(eventLogRecord, logType="Application"): """Given a tuple from ReadEventLog, and optionally where the event record came from, load the message, and process message inserts. Note that this function may raise win32api.error. See also the function SafeFormatMessage which will return None if the message can not be processed. """ # From the event log source name, we know the name of the registry # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % ( logType, eventLogRecord.SourceName, ) # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName) try: dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";") # Win2k etc appear to allow multiple DLL names data = None for dllName in dllNames: try: # Expand environment variable strings in the message DLL path name, # in case any are there. dllName = win32api.ExpandEnvironmentStrings(dllName) dllHandle = win32api.LoadLibraryEx( dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE) try: data = win32api.FormatMessageW( win32con.FORMAT_MESSAGE_FROM_HMODULE, dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts, ) finally: win32api.FreeLibrary(dllHandle) except win32api.error: pass # Not in this DLL - try the next if data is not None: break finally: win32api.RegCloseKey(handle) return data or "" # Don't want "None" ever being returned.
def open(self, flags_and_attributes=win32file.FILE_FLAG_NO_BUFFERING): """ This will create a handle to usb device using the device_path Args: Returns: handle: usb device win32 HANDLE """ http_usb_handle = win32file.CreateFile( self.device_path, win32file.GENERIC_WRITE | win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, flags_and_attributes, None) if http_usb_handle == win32file.INVALID_HANDLE_VALUE: error_code = win32api.GetLastError() error_message = win32api.FormatMessageW(error_code) raise IOError("Open Failed code {} message {}".format( error_code, error_message)) return http_usb_handle
def uninstall(filename, log_path, ignore_exit_code=False, no_wait=False): """ Uninstall MSI with options :param filename: :param log_path: :param ignore_exit_code: :return: """ command = r'msiexec.exe /norestart /q /X "{0}" /l! "{1}"'.format( filename, log_path) exit_code = Core.get_instance().api.os.shell.cmd(command, ignore_exit_code=True, no_wait=no_wait) if exit_code == 3010: # Reboot required code logging.warning( 'WARNING: Installation requested a system reboot.\nYou may need to reboot the system manually to complete this installation.' ) elif exit_code != 0 and not ignore_exit_code: # Other errors rise exception raise RuntimeError('Installation "{0}" failed: ({1}) {2}'.format( filename, exit_code, win32api.FormatMessageW(exit_code))) return exit_code
def error(exception, context="", message=""): errno = win32api.GetLastError() message = message or win32api.FormatMessageW(errno) raise exception(errno, context, message)