def ctl(self, command, raise_exc=True): # sending start signal via service control will not fail if # a service can accept start command but cannot change its state into 'Running' # we should instead poll a service state until we succeed or timeout if command.lower() == 'start': RUNNING = 4 TIMEOUT = 3 GENERIC_READ = win32con.GENERIC_READ SC_MANAGER_ALL_ACCESS = win32service.SC_MANAGER_ALL_ACCESS __handle = win32service.OpenSCManager(None, None, GENERIC_READ) handle = win32service.OpenService(__handle, self.name, SC_MANAGER_ALL_ACCESS) try: win32service.StartService(handle, None) except Exception, e: raise InitdError( 'Could not complete StartService command.\n, {0}'. format(e)) elapsed = 0 while elapsed < TIMEOUT and win32service.QueryServiceStatusEx( handle)['CurrentState'] != RUNNING: time.sleep(0.1) elapsed += 0.1 if win32service.QueryServiceStatusEx( handle)['CurrentState'] == RUNNING: return raise exceptions.Timeout( "{0} service failed to change its state" " into 'Running' after {1}-second timeout.".format( self.name, TIMEOUT))
def wait_status(self, status=win32service.SERVICE_RUNNING, timeout=SERVICE_WAIT_TIMEOUT): abort = Event() abort.clear() def die(): abort.set() timer = Timer(timeout, die) timer.start() current = None while True: if abort.is_set(): # If timeout is hit we abort. if self.debug: print "Timeout hit waiting service for status {0}, current status {1}".format(status, current['CurrentState']) return current = win32service.QueryServiceStatusEx(self.service) if current['CurrentState'] == status: timer.cancel() return time.sleep(1)
def is_agent_running(self, fail_if_running=False, fail_if_not_running=False): """Returns true if the agent service is running, as determined by this platform implementation. This will optionally raise an Exception with an appropriate error message if the agent is running or not runnning. @param fail_if_running: True if the method should raise an Exception with a platform-specific error message explaining how it determined the agent is running. @param fail_if_not_running: True if the method should raise an Exception with a platform-specific error message explaining how it determined the agent is not running. @type fail_if_running: bool @type fail_if_not_running: bool @return: True if the agent process is already running. @rtype: bool @raise AgentAlreadyRunning @raise AgentNotRunning """ hscm = None hs = None try: hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CONNECT) hs = win32serviceutil.SmartOpenService( hscm, _SCALYR_AGENT_SERVICE_, win32service.SERVICE_QUERY_STATUS) status = win32service.QueryServiceStatusEx(hs) state = status["CurrentState"] is_running = state in ( win32service.SERVICE_RUNNING, win32service.SERVICE_START_PENDING, ) if fail_if_running and is_running: pid = status["ProcessId"] raise AgentAlreadyRunning( "The operating system reports the Scalyr Agent Service is running with " "pid=%d" % pid) if fail_if_not_running and not is_running: raise AgentNotRunning( "The operating system reports the Scalyr Agent Service is not running" ) return state in ( win32service.SERVICE_RUNNING, win32service.SERVICE_START_PENDING, ) finally: if hs is not None: win32service.CloseServiceHandle(hs) if hscm is not None: win32service.CloseServiceHandle(hscm)
def stopService(): """Stop the running service and wait for its process to die. """ scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: serv = win32service.OpenService(scm, NVDAService._svc_name_, win32service.SERVICE_ALL_ACCESS) try: pid = win32service.QueryServiceStatusEx(serv)["ProcessId"] # Stop the service. win32service.ControlService(serv, win32service.SERVICE_CONTROL_STOP) # Wait for the process to exit. proc = AutoHANDLE( windll.kernel32.OpenProcess(SYNCHRONIZE, False, pid)) if not proc: return windll.kernel32.WaitForSingleObject(proc, INFINITE) finally: win32service.CloseServiceHandle(serv) finally: win32service.CloseServiceHandle(scm)
def start_service(*svcs): scm_h = Wsvc.OpenSCManager(None, None, Wsvc.SC_MANAGER_ENUMERATE_SERVICE) for svc in svcs: svc_h = Wsvc.OpenService( scm_h, svc, Wsvc.SERVICE_QUERY_STATUS | Wsvc.SERVICE_START) status = Wsvc.QueryServiceStatusEx(svc_h) if status["CurrentState"] == Wsvc.SERVICE_STOPPED: Wsvc.StartService(svc_h, None) Wsvc.CloseServiceHandle(svc_h) Wsvc.CloseServiceHandle(scm_h)
def is_running_as_nt_service(): @contextmanager def close_srv(srv): try: yield srv finally: ws.CloseServiceHandle(srv) with close_srv(ws.OpenSCManager(None, None, ws.SC_MANAGER_ALL_ACCESS)) as hscm: with close_srv(wsu.SmartOpenService(hscm, nt_service_name, ws.SERVICE_ALL_ACCESS)) as hs: info = ws.QueryServiceStatusEx(hs) return info['ProcessId'] == getppid()
def GetServiceStatus(self): serviceHandle = None try: serviceHandle = ServiceEntity.__getServiceHandle(self.ServiceName, self.__serviceConfigManagerHandle) result = win32service.QueryServiceStatusEx(serviceHandle) result['ServiceName'] = self.__serviceName.StringValue() result['DisplayName'] = self.Configurations['DisplayName'] statusEntity = ServiceStatusProcessEntity(**result) return statusEntity.Status finally: if serviceHandle: win32service.CloseServiceHandle(serviceHandle)
def check_windows_service_status(service_name): _schSCManager = safe_open_scmanager() try: _service_handle = safe_open_service(_schSCManager, service_name) try: if win32service.QueryServiceStatusEx(_service_handle)["CurrentState"] == win32service.SERVICE_STOPPED: raise ComponentIsNotRunning() finally: win32service.CloseServiceHandle(_service_handle) finally: win32service.CloseServiceHandle(_schSCManager)
def WindowsDebugEngineProcess_run(*args, **kwargs): started = kwargs['Started'] handlingFault = kwargs['HandlingFault'] handledFault = kwargs['HandledFault'] CommandLine = kwargs.get('CommandLine', None) Service = kwargs.get('Service', None) ProcessName = kwargs.get('ProcessName', None) ProcessID = kwargs.get('ProcessID', None) KernelConnectionString = kwargs.get('KernelConnectionString', None) SymbolsPath = kwargs.get('SymbolsPath', None) IgnoreFirstChanceGardPage = kwargs.get('IgnoreFirstChanceGardPage', None) IgnoreSecondChanceGardPage = kwargs.get('IgnoreSecondChanceGardPage', None) quit = kwargs['Quit'] Tempfile = kwargs['Tempfile'] WinDbg = kwargs['WinDbg'] TempfilePid = kwargs['TempfilePid'] FaultOnEarlyExit = kwargs['FaultOnEarlyExit'] dbg = None #print "WindowsDebugEngineProcess_run" # Hack for comtypes early version comtypes._ole32.CoInitializeEx(None, comtypes.COINIT_APARTMENTTHREADED) try: _eventHandler = _DbgEventHandler() _eventHandler.pid = None _eventHandler.handlingFault = handlingFault _eventHandler.handledFault = handledFault _eventHandler.IgnoreFirstChanceGardPage = IgnoreFirstChanceGardPage _eventHandler.IgnoreSecondChanceGardPage = IgnoreSecondChanceGardPage _eventHandler.quit = quit _eventHandler.Tempfile = Tempfile _eventHandler.TempfilePid = TempfilePid _eventHandler.FaultOnEarlyExit = FaultOnEarlyExit if KernelConnectionString: dbg = PyDbgEng.KernelAttacher( connection_string=KernelConnectionString, event_callbacks_sink=_eventHandler, output_callbacks_sink=_eventHandler, symbols_path=SymbolsPath, dbg_eng_dll_path=WinDbg) elif CommandLine: dbg = PyDbgEng.ProcessCreator( command_line=CommandLine, follow_forks=True, event_callbacks_sink=_eventHandler, output_callbacks_sink=_eventHandler, symbols_path=SymbolsPath, dbg_eng_dll_path=WinDbg) elif ProcessName: pid = None for x in range(10): print "WindowsDebugEngineThread: Attempting to locate process by name..." pid = GetProcessIdByName(ProcessName) if pid != None: break time.sleep(0.25) if pid == None: raise Exception("Error, unable to locate process '%s'" % ProcessName) dbg = PyDbgEng.ProcessAttacher( pid, event_callbacks_sink=_eventHandler, output_callbacks_sink=_eventHandler, symbols_path=SymbolsPath, dbg_eng_dll_path=WinDbg) elif ProcessID: print "Attaching by pid:", ProcessID pid = ProcessID dbg = PyDbgEng.ProcessAttacher( pid, event_callbacks_sink=_eventHandler, output_callbacks_sink=_eventHandler, symbols_path=SymbolsPath, dbg_eng_dll_path=WinDbg) elif Service: # Make sure service is running if win32serviceutil.QueryServiceStatus(Service)[1] != 4: try: # Some services auto-restart, if they do # this call will fail. win32serviceutil.StartService(Service) except: pass while win32serviceutil.QueryServiceStatus(Service)[1] == 2: time.sleep(0.25) if win32serviceutil.QueryServiceStatus(Service)[1] != 4: raise Exception( "WindowsDebugEngine: Unable to start service!") # Determin PID of service scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) hservice = win32service.OpenService(scm, Service, 0xF01FF) status = win32service.QueryServiceStatusEx(hservice) pid = status["ProcessId"] win32service.CloseServiceHandle(hservice) win32service.CloseServiceHandle(scm) dbg = PyDbgEng.ProcessAttacher( pid, event_callbacks_sink=_eventHandler, output_callbacks_sink=_eventHandler, symbols_path=SymbolsPath, dbg_eng_dll_path=WinDbg) else: raise Exception( "Didn't find way to start debugger... bye bye!!") _eventHandler.dbg = dbg started.set() dbg.event_loop_with_quit_event(quit) finally: if dbg != None: if dbg.idebug_client != None: dbg.idebug_client.EndSession( DbgEng.DEBUG_END_ACTIVE_TERMINATE) dbg.idebug_client.Release() elif dbg.idebug_control != None: dbg.idebug_control.EndSession( DbgEng.DEBUG_END_ACTIVE_TERMINATE) dbg.idebug_control.Release() dbg = None comtypes._ole32.CoUninitialize()
def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError('Failed to connect to the SCM: {0}'.format( exc[2])) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError('Failed To Open {0}: {1}'.format( name, exc[2])) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info[ 'ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret
def AddInfo(grph, node, entity_ids_arr): serviceNam = entity_ids_arr[0] sys.stderr.write("AddInfo serviceNam=%s\n" % serviceNam) machName_or_None, imper = lib_win32.MakeImpersonate("") hscm = win32service.OpenSCManager(machName_or_None, None, accessSCM) try: status = win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_ENUMERATE_DEPENDENTS hdnSrv = win32service.OpenService(hscm, serviceNam, status) lstSrvPairs = win32service.QueryServiceStatusEx(hdnSrv) win32service.CloseServiceHandle(hdnSrv) except Exception: exc = sys.exc_info()[1] # Probably "Access is denied" sys.stderr.write("AddInfo Caught:%s\n" % str(exc)) lstSrvPairs = dict() try: lstSrvPairs["Status"] = str(exc[2]) except: lstSrvPairs["Status"] = str(exc) # CheckPoint 0 # ControlsAccepted 1 # CurrentState 4 # ProcessId 3176 # ServiceFlags 0 # ServiceSpecificExitCode 0 # ServiceType 16 # WaitHint 0 # Win32ExitCode 0 for keySrv in lstSrvPairs: sys.stderr.write("AddInfo keySrv:%s\n" % keySrv) valSrv = lstSrvPairs[keySrv] if keySrv == "ProcessId": if int(valSrv) != 0: nodeProc = lib_common.gUriGen.PidUri(valSrv) grph.add((nodeProc, pc.property_pid, lib_common.NodeLiteral(valSrv))) grph.add((node, lib_common.MakeProp(keySrv), nodeProc)) elif keySrv == "ServiceType": svcTypSrc = "" svcTypInt = int(valSrv) if svcTypInt & win32service.SERVICE_KERNEL_DRIVER: svcTypSrc += "KERNEL_DRIVER " if svcTypInt & win32service.SERVICE_FILE_SYSTEM_DRIVER: svcTypSrc += "FILE_SYSTEM_DRIVER " #if svcTypInt & win32service.SERVICE_ADAPTER: svcTypSrc += "ADAPTER " #if svcTypInt & win32service.SERVICE_RECOGNIZER_DRIVER: svcTypSrc += "RECOGNIZER_DRIVER " if svcTypInt & win32service.SERVICE_WIN32_OWN_PROCESS: svcTypSrc += "WIN32_OWN_PROCESS " if svcTypInt & win32service.SERVICE_WIN32_SHARE_PROCESS: svcTypSrc += "WIN32_SHARE_PROCESS " if svcTypInt & win32service.SERVICE_WIN32: svcTypSrc += "WIN32 " if svcTypInt & win32service.SERVICE_INTERACTIVE_PROCESS: svcTypSrc += "INTERACTIVE_PROCESS " grph.add((node, lib_common.MakeProp(keySrv), lib_common.NodeLiteral(svcTypSrc))) elif keySrv == "CurrentState": statesArray = ("SERVICE_STOPPED", "SERVICE_START_PENDING", "SERVICE_STOP_PENDING", "SERVICE_RUNNING", "SERVICE_CONTINUE_PENDING", "SERVICE_PAUSE_PENDING", "SERVICE_PAUSED") # Fetches from the module a constant with this value. srcStatSrc = valSrv for srvStatVar in statesArray: if valSrv == getattr(win32service, srvStatVar): srcStatSrc = srvStatVar break grph.add((node, lib_common.MakeProp(keySrv), lib_common.NodeLiteral(srcStatSrc))) else: grph.add((node, lib_common.MakeProp(keySrv), lib_common.NodeLiteral(valSrv))) return
def get_current_status(self): return win32service.QueryServiceStatusEx( self._service_handle)["CurrentState"]
def status(self): if win32service.QueryServiceStatusEx( self._service_handle )["CurrentState"] == win32service.SERVICE_RUNNING: return True return False
def check_windows_service_status(service_name): _service_handle = win32service.OpenService(_schSCManager, service_name, win32service.SERVICE_ALL_ACCESS) if win32service.QueryServiceStatusEx( _service_handle)["CurrentState"] == win32service.SERVICE_STOPPED: raise ComponentIsNotRunning()