def checkRevSvc(): hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) print hscm try: revhs = win32service.OpenService(hscm, "revsvc", win32service.SERVICE_ALL_ACCESS) except: f1.write('not found revsvc\n') print 'not found revsvc' return 'not found' if revhs: revstatus = win32service.QueryServiceStatus(revhs) revstatus = getServiceStatus(revstatus) if revstatus == 'stopping': time.sleep(1.0) if revstatus == 'stopped': print 'rev stopped' f2.write('rev stopped \n') try: win32serviceutil.StartService("revsvc", None, None) print 'rev started' f2.write('rev started \n') time.sleep(5.0) except: print 'rev start failed' time.sleep(10.0) f1.write('rev start failed\n') else: print 'rev running' f3.write('rev running\n')
def Update(cls, startupMode="auto", username=None, password=None): # Handle the default arguments. if startupMode is None: startType = win32service.SERVICE_NO_CHANGE else: startType = cls._get_start_type(startupMode) hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) serviceType = win32service.SERVICE_WIN32_OWN_PROCESS commandLine = os.path.abspath(cls._exe_name_) try: hs = SmartOpenService(hscm, cls._svc_name_, win32service.SERVICE_ALL_ACCESS) try: win32service.ChangeServiceConfig( hs, serviceType, # service type startType, win32service.SERVICE_NO_CHANGE, # error control type commandLine, None, 0, None, username, password, cls._svc_display_name_) print "Service updated" finally: win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm)
def sc(serviceName): # 获取“服务管理器”的句柄 scHandle = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) # do something ... print 'got SCM handle : %(scHandle)s' % locals() # 获取某个服务的句柄 serviceHandle = win32service.OpenService(scHandle, serviceName, win32service.SC_MANAGER_ALL_ACCESS) # 利用句柄查询该服务的状态信息 status = win32service.QueryServiceStatus(serviceHandle) PrintServiceStatus(status) # 也可以直接通过服务的名称来查询状态 status = win32serviceutil.QueryServiceStatus(serviceName) # 停止该服务 if isServiceRunning(serviceName): status = win32service.ControlService(serviceHandle, win32service.SERVICE_CONTROL_STOP) PrintServiceStatus(status) # 启动该服务 if not isServiceRunning(serviceName): win32serviceutil.StartService(serviceName) PrintServiceStatus(win32serviceutil.QueryServiceStatus(serviceName)) # 释放所取得的所有句柄 win32service.CloseServiceHandle(serviceHandle) win32service.CloseServiceHandle(scHandle)
def checkService(svcName): import win32service, time hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: hs = win32service.OpenService(hscm, svcName, win32service.SERVICE_ALL_ACCESS) except: logfile.write('can not open %s at %s \n' % (svcName, time.ctime())) return False if hs: status = win32service.QueryServiceStatus(hs) status = getServiceStatus(status) if status == 'running': return True if status == 'stopped' or status == 'stopping': logfile.write('%s stopped at %s\n' % (svcName, time.ctime())) try: win32service.StartService(hs, None) warningfile.write('%s started at %s\n' % (svcName, time.ctime())) return True except: warningfile.write('trying to start %s failed at %s\n' % (svcName, time.ctime())) else: logfile.write('controlling %s => all failed at %s\n' % (svcName, time.ctime()))
def setupRecoverService(): svc_name = UDSActorSvc._svc_name_ # pylint: disable=protected-access try: hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: hs = win32serviceutil.SmartOpenService( hscm, svc_name, win32service.SERVICE_ALL_ACCESS) service_failure_actions = { 'ResetPeriod': 864000, # Time in ms after which to reset the failure count to zero. 'RebootMsg': u'', # Not using reboot option 'Command': u'', # Not using run-command option 'Actions': [ (win32service.SC_ACTION_RESTART, 5000), # action, delay in ms (win32service.SC_ACTION_RESTART, 5000) ] } win32service.ChangeServiceConfig2( hs, win32service.SERVICE_CONFIG_FAILURE_ACTIONS, service_failure_actions) finally: win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm)
def __init__(self, name): """ name: 服务的名称 """ self.name = name # 启动或停止服务时等待操作成功等待时间 self.wait_time = 0.5 # 启动或停止服务时最大等待时间,超过时返回超时提示 self.delay_time = 10 self.scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) if self.is_exists(): try: self.handle = win32service.OpenService( self.scm, self.name, win32service.SC_MANAGER_ALL_ACCESS) except Exception as e: self.log(e) else: print(f'服务 {self.name} 没有安装') try: win32serviceutil.HandleCommandLine(PythonService, 'install') except Exception as e: print(e)
def stop_delete_service(service_name): ''' Checks if the service is installed as running. If it is running, it will stop it. If it is stopped, then it will delete it. ''' hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: win32service.OpenService(hscm, service_name, win32service.SERVICE_ALL_ACCESS) # Already installed status = win32serviceutil.QueryServiceStatus(service_name) if status[1] == 4: # Stop the service win32serviceutil.StopService(service_name) time.sleep(3) #delete the service win32serviceutil.RemoveService(service_name) time.sleep(3) return True except win32api.error, details: if details[0] != winerror.ERROR_SERVICE_DOES_NOT_EXIST: print service_name + "is not being installed properly but have other problem." return False else: # Service is not being installed and ready for fresh installtion return True
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 __init__(self): self.dll_is_initialized = False self.hSCManager = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) self.hDriver = None self.__is_need_uninstall_driver = True self.__initialize()
def ListServices(filter): manager = None try: manager = win32service.OpenSCManager( 'localhost', None, win32service.SC_MANAGER_ENUMERATE_SERVICE) services = list( win32service.EnumServicesStatus(manager, win32service.SERVICE_WIN32)) nameLen = max([len(service[0]) for service in services]) displayLen = max([len(service[1]) for service in services]) + 2 services.sort(cmp=lambda x, y: cmp(x[0].lower(), y[0].lower())) format = '%-' + str(nameLen) + 's %-' + str(displayLen) + 's : %s' for service in services: if filter and not fnmatch.fnmatch(service[0], filter): continue status = GetCurrentStateStr(service[2][1]) print((format % (service[0], '"' + service[1] + '"', status[0]))) except Exception as inst: if len(inst.args) == 3: number = inst.args[0] function = inst.args[1] message = inst.args[2] print(('ERROR enumerating services: %#08x (%s): %s' % (number, function, message))) else: print(('ERROR enumerating services: %s' % inst)) finally: if manager: win32service.CloseServiceHandle(manager)
def __init__(self, driver, service, debug=False): self.driver = driver self.service_name = service self.manager = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CREATE_SERVICE) self.service = None self.debug = debug
def __init__(self, name): """ name: 服务的名称 """ self.name = name #启动或停止服务时等待操作成功等待时间 self.wait_time = 0.5 #启动或停止服务时最大等待时间,超过时返回超时提示 self.delay_time = 10 self.scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS ) if self.is_exists(): try: self.handle = win32service.OpenService( self.scm, self.name, win32service.SC_MANAGER_ALL_ACCESS ) except Exception as e: self.log(e) else: print('服务 %s 没有安装'.encode('gbk') % self.name)
def stopasync(self, args, config): """ Returns true if the server was already stopped """ self.check_node(args) if 0 != self.status(args, node_only=True): self.ctx.err("Server not running") return True elif self._isWindows(): svc_name = "OMERO.%s" % args.node output = self._query_service(svc_name) if 0 <= output.find("DOESNOTEXIST"): self.ctx.die( 203, "%s does not exist. Use 'start' first." % svc_name) hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) try: hs = win32service.OpenService( hscm, svc_name, win32service.SC_MANAGER_ALL_ACCESS) win32service.ControlService(hs, win32service.SERVICE_CONTROL_STOP) win32service.DeleteService(hs) self.ctx.out("%s service deleted." % svc_name) finally: win32service.CloseServiceHandle(hs) win32service.CloseServiceHandle(hscm) else: command = self._cmd("-e", "node shutdown %s" % self._node()) try: self.ctx.call(command) except NonZeroReturnCode, nzrc: self.ctx.rv = nzrc.rv self.ctx.out("Was the server already stopped?")
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 __init__(self, service, machinename=None, dbname=None): self.userv = service self.scmhandle = ws.OpenSCManager(machinename, dbname, ws.SC_MANAGER_ALL_ACCESS) self.sserv, self.lserv = self.getname() if (self.sserv or self.lserv) == None: sys.exit() self.handle = ws.OpenService(self.scmhandle, self.sserv, ws.SERVICE_ALL_ACCESS) self.sccss = "SYSTEM\\CurrentControlSet\\Services\\"
def check(self, instance): services = set(instance.get('services', [])) custom_tags = instance.get('tags', []) if not services: raise ValueError('No services defined in configuration.') # Old-style WMI wildcards if 'host' in instance: services = set(service.replace('%', '.*') for service in services) service_patterns = { service: re.compile(service, SERVICE_PATTERN_FLAGS) for service in services } services_unseen = set(services) try: scm_handle = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) except Exception as e: # no cov raise Exception('Unable to open SCManager: {}'.format(e)) type_filter = win32service.SERVICE_WIN32 state_filter = win32service.SERVICE_STATE_ALL service_statuses = win32service.EnumServicesStatus( scm_handle, type_filter, state_filter) for short_name, _, service_status in service_statuses: if 'ALL' not in services: for service, service_pattern in sorted( iteritems(service_patterns), reverse=True): self.log.debug( 'Service: %s with Short Name: %s and Pattern: %s', service, short_name, service_pattern.pattern) if service_pattern.match(short_name): services_unseen.discard(service) break else: continue state = service_status[1] status = self.STATE_TO_STATUS.get(state, self.UNKNOWN) tags = ['service:{}'.format(short_name)] tags.extend(custom_tags) self.service_check(self.SERVICE_CHECK_NAME, status, tags=tags) self.log.debug('service state for %s %s', short_name, status) if 'ALL' not in services: for service in services_unseen: status = self.CRITICAL tags = ['service:{}'.format(service)] tags.extend(custom_tags) self.service_check(self.SERVICE_CHECK_NAME, status, tags=tags) self.log.debug('service state for %s %s', service, status)
def ChangeServiceConfig(pythonClassString, serviceName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, displayName = None, perfMonIni = None, perfMonDll = None, exeArgs = None, description = None, delayedstart = None): # Before doing anything, remove any perfmon counters. try: import perfmon perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName) except (ImportError, win32api.error): pass # The EXE location may have changed exeName = '"%s"' % LocatePythonServiceExe(exeName) # Handle the default arguments. if startType is None: startType = win32service.SERVICE_NO_CHANGE if errorControl is None: errorControl = win32service.SERVICE_NO_CHANGE hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS) serviceType = win32service.SERVICE_WIN32_OWN_PROCESS if bRunInteractive: serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS commandLine = _GetCommandLine(exeName, exeArgs) try: hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS) try: win32service.ChangeServiceConfig(hs, serviceType, # service type startType, errorControl, # error control type commandLine, None, 0, serviceDeps, userName, password, displayName) if description is not None: try: win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DESCRIPTION,description) except NotImplementedError: pass ## ChangeServiceConfig2 and description do not exist on NT if delayedstart is not None: try: win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, delayedstart) except (win32service.error, NotImplementedError): ## Delayed start only exists on Vista and later. On Nt, will raise NotImplementedError since ChangeServiceConfig2 ## doensn't exist. On Win2k and XP, will fail with ERROR_INVALID_LEVEL ## Warn only if trying to set delayed to True if delayedstart: warnings.warn('Delayed Start not available on this system') finally: win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm) InstallPythonClassString(pythonClassString, serviceName) # If I have performance monitor info to install, do that. if perfMonIni is not None: InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
def _CreateService(service_name: str, description: str, command_line: str) -> None: """Creates a Windows service.""" logging.info("Creating service '%s'.", service_name) with contextlib.ExitStack() as stack: hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) stack.callback(win32service.CloseServiceHandle, hscm) hs = win32service.CreateService( hscm, service_name, service_name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_WIN32_OWN_PROCESS, win32service.SERVICE_AUTO_START, win32service.SERVICE_ERROR_NORMAL, command_line, None, 0, None, None, None) stack.callback(win32service.CloseServiceHandle, hs) service_failure_actions = { "ResetPeriod": SERVICE_RESET_FAIL_COUNT_DELAY_SEC, "RebootMsg": u"", "Command": u"", "Actions": [ (win32service.SC_ACTION_RESTART, SERVICE_RESTART_DELAY_MSEC), (win32service.SC_ACTION_RESTART, SERVICE_RESTART_DELAY_MSEC), (win32service.SC_ACTION_RESTART, SERVICE_RESTART_DELAY_MSEC), ] } win32service.ChangeServiceConfig2( hs, win32service.SERVICE_CONFIG_FAILURE_ACTIONS, service_failure_actions) win32service.ChangeServiceConfig2( hs, win32service.SERVICE_CONFIG_DESCRIPTION, description) logging.info("Successfully created service '%s'.", service_name)
def create(self, start_driver): if not start_driver: return logger().log("") logger().warn( "*******************************************************************" ) logger().warn("Chipsec should only be used on test systems!") logger().warn( "It should not be installed/deployed on production end-user systems." ) logger().warn("See WARNING.txt") logger().warn( "*******************************************************************" ) logger().log("") try: hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS ) # SC_MANAGER_CREATE_SERVICE except win32service.error, (hr, fn, msg): string = "OpenSCManager failed: %s (%d)" % (msg, hr) logger().error(string) raise OsHelperError(string, hr)
def svcStop(self, svc_name, machine=None): accessSCM = win32con.GENERIC_READ hscm = win32service.OpenSCManager(None, None, accessSCM) try: shandle = win32service.OpenService(hscm, svc_name, accessSCM) try: dependent_services = win32service.EnumDependentServices( shandle, win32service.SERVICE_ACTIVE) for (service_name, display_name, service_status) in dependent_services: if (service_status[1] == RUNNING): self.logger.info( "Stopping {} service because it is dependency of {}" .format(service_name, svc_name)) self.svcStop(service_name) finally: win32service.CloseServiceHandle(shandle) finally: win32service.CloseServiceHandle(hscm) status = win32serviceutil.StopService(svc_name, machine)[1] i = 0 while status == STOPPING: time.sleep(1) status = self.svcStatus(svc_name, machine) i = i + 1 if i > 60: self.logger.info("Timeout stopping %s service" % svc_name) raise TimeoutError return status
def get_services(self, services_loaded): scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) svcs = win32service.EnumServicesStatus(scm) for svc in svcs: try: sh_query_config = win32service.OpenService( scm, svc[0], win32service.SERVICE_QUERY_CONFIG) service_info = win32service.QueryServiceConfig(sh_query_config) short_name = svc[0] full_path = service_info[3] sv = self.check_if_service_already_loaded( short_name, full_path, services_loaded) if sv: sv.permissions = self.get_service_permissions(sv) if not sv: sk = Service() sk.name = short_name sk.display_name = svc[1] sk.full_path = full_path sk.paths = get_path_info(full_path) sk.permissions = self.get_service_permissions(sv) services_loaded.append(sk) except: pass return services_loaded
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 on_host_init_response(self, message): global_variables = message.body.get('global_variables') or [] for kv in global_variables: self._global_variables[kv['name']] = kv['value'].encode( 'utf-8') if kv['value'] else '' if 'chef' in message.body and message.body['chef']: if linux.os.windows_family: self._chef_client_bin = r'C:\opscode\chef\bin\chef-client.bat' self._chef_solo_bin = r'C:\opscode\chef\bin\chef-solo.bat' else: # Workaround for 'chef' behavior enabled, but chef not installed self._chef_client_bin = which('chef-client') self._chef_solo_bin = which('chef-solo') self._chef_data = message.chef.copy() if not self._chef_data.get('node_name'): self._chef_data['node_name'] = self.get_node_name() self._with_json_attributes = self._chef_data.get( 'json_attributes', {}) or {} if self._with_json_attributes: self._with_json_attributes = json.loads( self._with_json_attributes) self._run_list = self._chef_data.get('run_list') if self._run_list: self._with_json_attributes['run_list'] = json.loads( self._run_list) elif self._chef_data.get('role'): self._with_json_attributes['run_list'] = [ "role[%s]" % self._chef_data['role'] ] if linux.os.windows_family: # TODO: why not doing the same on linux? try: # Set startup type to 'manual' for chef-client service hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) try: hs = win32serviceutil.SmartOpenService( hscm, WIN_SERVICE_NAME, win32service.SERVICE_ALL_ACCESS) try: snc = win32service.SERVICE_NO_CHANGE # change only startup type win32service.ChangeServiceConfig( hs, snc, win32service.SERVICE_DEMAND_START, snc, None, None, 0, None, None, None, None) finally: win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm) win32serviceutil.StopService(WIN_SERVICE_NAME) except: e = sys.exc_info()[1] self._logger.warning('Could not stop chef service: %s' % e)
def InstallDriver(driver_path, service_name, driver_display_name): """Loads a driver and start it.""" hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: win32service.CreateService( hscm, service_name, driver_display_name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, driver_path, None, # No load ordering 0, # No Tag identifier None, # Service deps None, # User name None) # Password win32serviceutil.StartService(service_name) except pywintypes.error as e: # The following errors are expected: if e[0] not in [ winerror.ERROR_SERVICE_EXISTS, winerror.ERROR_SERVICE_MARKED_FOR_DELETE ]: raise RuntimeError("StartService failure: {0}".format(e))
def checkHlyctlSvc(): hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) print hscm try: hlyhs = win32service.OpenService(hscm, "hlyctlsvc", win32service.SERVICE_ALL_ACCESS) except: f1.write('can not open hlysvc\n') print 'can not open hlysvc' return 'cannot open' if hlyhs: hlystatus = win32service.QueryServiceStatus(hlyhs) hlystatus = getServiceStatus(hlystatus) if hlystatus == 'stopping': time.sleep(1.0) if hlystatus =='stopped': print 'hly stopped' f2.write('hly stopped \n') try: win32serviceutil.StartService("hlyctlsvc", None, None) print 'hly started' f2.write('hly started \n') time.sleep(5.0) except: print 'hly start failed' time.sleep(10.0) f1.write('hly start failed\n') else : print 'rev running' f3.write('rev running\n')
def load_driver(self): """Load the driver if possible.""" # Check the driver is somewhere accessible. if self.driver is None: # Valid values # http://superuser.com/questions/305901/possible-values-of-processor-architecture machine = platform.machine() if machine == "AMD64": driver = "winpmem_x64.sys" elif machine == "x86": driver = "winpmem_x86.sys" else: raise plugin.PluginError("Unsupported architecture") self.driver = rekall.get_resource("WinPmem/%s" % driver) # Try the local directory if self.driver is None: self.driver = os.path.join(os.getcwd(), "WinPmem", driver) self.session.logging.debug("Loading driver from %s", self.driver) if not os.access(self.driver, os.R_OK): raise plugin.PluginError("Driver file %s is not accessible." % self.driver) # Must have absolute path here. self.hScm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CREATE_SERVICE) try: self.hSvc = win32service.CreateService( self.hScm, self.name, self.name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, self.driver, None, 0, None, None, None) self.session.logging.debug("Created service %s", self.name) # Remember to cleanup afterwards. self.we_started_service = True except win32service.error as e: # Service is already there, try to open it instead. self.hSvc = win32service.OpenService( self.hScm, self.name, win32service.SERVICE_ALL_ACCESS) # Make sure the service is stopped. try: win32service.ControlService(self.hSvc, win32service.SERVICE_CONTROL_STOP) except win32service.error: pass try: win32service.StartService(self.hSvc, []) except win32service.error, e: self.session.logging.debug("%s: will try to continue", e)
def safe_open_scmanager(): try: _schSCManager = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) except win32api.error, details: raise Fail( "Error opening Service Control Manager on the local machine: {0}". format(details.winerror))
def get_service_permissions(self, s): hnd = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CONNECT) start = self.service_start(hnd, s) stop = self.service_stop(hnd, s) change_config = self.change_sercice_configuration(hnd, s) return {'start': start, 'stop': stop, 'change_config': change_config}
def create(self, start_driver): if not start_driver: return True self.show_warning() try: hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS ) # SC_MANAGER_CREATE_SERVICE except win32service.error as (hr, fn, msg): handle_winerror(fn, msg, hr)
def GenerateFromOperatingSystem(serviceName): # Just making sure that the service exists if not ServiceEntity.ServiceExists(serviceName.StringValue()): raise ValueError('Service "{0}" does not exists'.format(serviceName)) serviceConfigManagerHandle = win32service.OpenSCManager('', None, win32service.SC_MANAGER_ALL_ACCESS) serviceConfigurations = ServiceConfigurations.GenerateFromOperatingSystem(serviceConfigManagerHandle, serviceName) serviceConfigurations2 = ServiceConfigurations2.GenerateFromOperatingSystem(serviceConfigManagerHandle, serviceName) return ServiceEntity(serviceConfigManagerHandle, serviceName, serviceConfigurations, serviceConfigurations2)