Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
    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)
Exemplo n.º 4
0
 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?")
Exemplo n.º 5
0
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 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 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)
Exemplo n.º 9
0
    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
Exemplo n.º 10
0
 def close(self):
     """Free resources"""
     try:
         if self.scm:
             win32service.CloseServiceHandle(self.handle)
             win32service.CloseServiceHandle(self.scm)
     except Exception as e:
         logging.info(e)
Exemplo n.º 11
0
 def close(self):
     """释放资源"""
     try:
         if self.scm:
             win32service.CloseServiceHandle(self.handle)
             win32service.CloseServiceHandle(self.scm)
     except Exception, e:
         self.log(e)
Exemplo n.º 12
0
    def delete(self):
        log.info("Trying to delete the winpmem service...")

        try:
            win32service.DeleteService(self.service)
            win32service.CloseServiceHandle(self.service)
            win32service.CloseServiceHandle(self.manager)
        except Exception as e:
            raise DetectorError("Unable to delete the service: {0}".format(e))
Exemplo n.º 13
0
def InstallService(pythonClassString,
                   serviceName,
                   displayName,
                   startType=None,
                   errorControl=None,
                   bRunInteractive=0,
                   serviceDeps=None,
                   userName=None,
                   password=None,
                   exeName=None,
                   perfMonIni=None,
                   perfMonDll=None,
                   exeArgs=None,
                   description=None):
    # Handle the default arguments.
    if startType is None:
        startType = win32service.SERVICE_DEMAND_START
    serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
    if bRunInteractive:
        serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
    if errorControl is None:
        errorControl = win32service.SERVICE_ERROR_NORMAL

    exeName = '"%s"' % LocatePythonServiceExe(
        exeName)  # None here means use default PythonService.exe
    commandLine = _GetCommandLine(exeName, exeArgs)
    hscm = win32service.OpenSCManager(None, None,
                                      win32service.SC_MANAGER_ALL_ACCESS)
    try:
        hs = win32service.CreateService(
            hscm,
            serviceName,
            displayName,
            win32service.SERVICE_ALL_ACCESS,  # desired access
            serviceType,  # service type
            startType,
            errorControl,  # error control type
            commandLine,
            None,
            0,
            serviceDeps,
            userName,
            password)
        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
        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)
Exemplo n.º 14
0
def delete(name, timeout=90):
    """
    Delete the named service

    Args:

        name (str): The name of the service to delete

        timeout (int):
            The time in seconds to wait for the service to be deleted before
            returning. This is necessary because a service must be stopped
            before it can be deleted. Default is 90 seconds

            .. versionadded:: 2017.7.9,2018.3.4

    Returns:
        bool: ``True`` if successful, otherwise ``False``. Also returns ``True``
            if the service is not present

    CLI Example:

    .. code-block:: bash

        salt '*' service.delete <service name>
    """
    handle_scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CONNECT)

    try:
        handle_svc = win32service.OpenService(
            handle_scm, name, win32service.SERVICE_ALL_ACCESS
        )
    except pywintypes.error as exc:
        win32service.CloseServiceHandle(handle_scm)
        if exc.winerror != 1060:
            raise CommandExecutionError(
                "Failed to open {}. {}".format(name, exc.strerror)
            )
        log.debug('Service "{}" is not present'.format(name))
        return True

    try:
        win32service.DeleteService(handle_svc)
    except pywintypes.error as exc:
        raise CommandExecutionError(
            "Failed to delete {}. {}".format(name, exc.strerror)
        )
    finally:
        log.debug("Cleaning up")
        win32service.CloseServiceHandle(handle_scm)
        win32service.CloseServiceHandle(handle_svc)

    end_time = time.time() + int(timeout)
    while name in get_all() and time.time() < end_time:
        time.sleep(1)

    return name not in get_all()
Exemplo n.º 15
0
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)
Exemplo n.º 16
0
    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 err:
            _handle_winerror(err.args[1], err.args[2], err.args[0])

        if logger().DEBUG:
            logger().log(
                "[helper] service control manager opened (handle = {})".format(
                    hscm))
            logger().log("[helper] driver path: '{}'".format(
                os.path.abspath(self.driver_path)))

        try:
            hs = win32service.CreateService(
                hscm, SERVICE_NAME, DISPLAY_NAME,
                (win32service.SERVICE_QUERY_STATUS | win32service.SERVICE_START
                 | win32service.SERVICE_STOP),
                win32service.SERVICE_KERNEL_DRIVER,
                win32service.SERVICE_DEMAND_START,
                win32service.SERVICE_ERROR_NORMAL,
                os.path.abspath(self.driver_path), None, 0, u"", None, None)
            if hs:
                if logger().DEBUG:
                    logger().log(
                        "[helper] service '{}' created (handle = 0x{:08X})".
                        format(SERVICE_NAME, hs))
        except win32service.error as err:
            if (winerror.ERROR_SERVICE_EXISTS == err.args[0]):
                if logger().DEBUG:
                    logger().log(
                        "[helper] service '{}' already exists: {} ({:d})".
                        format(SERVICE_NAME, err.args[2], err.args[0]))
                try:
                    hs = win32service.OpenService(
                        hscm, SERVICE_NAME,
                        (win32service.SERVICE_QUERY_STATUS
                         | win32service.SERVICE_START
                         | win32service.SERVICE_STOP))  # SERVICE_ALL_ACCESS
                except win32service.error as err1:
                    _handle_winerror(err1.args[1], err1.args[2], err1.args[0])
            else:
                _handle_winerror(err.args[1], err.args[2], err.args[0])

        finally:
            win32service.CloseServiceHandle(hs)
            win32service.CloseServiceHandle(hscm)

        return True
    def Install(cls, startupMode="auto", username=None, password=None):
        print "Installing service %s" % (cls._svc_name_)

        # Configure master.xml, which drives the java subprocess32
        java_path = get_java_exe_path()
        java_args = _build_master_java_args(username)

        config_file_path = _get_config_file_path()

        xmlFileContents = _MasterXml()
        xmlFileContents.service.id = EMBEDDED_HBASE_MASTER_SERVICE
        xmlFileContents.service.name = EMBEDDED_HBASE_MASTER_SERVICE
        xmlFileContents.service.description = "This service runs " + EMBEDDED_HBASE_MASTER_SERVICE
        xmlFileContents.service.executable = java_path
        xmlFileContents.service.arguments = java_args

        xmlFile = open(config_file_path, "w")
        xmlFile.write(str(xmlFileContents))
        xmlFile.close()

        startType = cls._get_start_type(startupMode)
        serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
        errorControl = win32service.SERVICE_ERROR_NORMAL

        commandLine = os.path.abspath(cls._exe_name_)
        hscm = win32service.OpenSCManager(None, None,
                                          win32service.SC_MANAGER_ALL_ACCESS)
        try:
            try:
                hs = win32service.CreateService(
                    hscm,
                    cls._svc_name_,
                    cls._svc_display_name_,
                    win32service.SERVICE_ALL_ACCESS,  # desired access
                    serviceType,  # service type
                    startType,
                    errorControl,  # error control type
                    commandLine,
                    None,
                    0,
                    None,
                    username,
                    password)
                print "Service installed"
                win32service.CloseServiceHandle(hs)
            finally:
                win32service.CloseServiceHandle(hscm)
        except win32service.error, exc:
            if exc.winerror == winerror.ERROR_SERVICE_EXISTS:
                cls.Update(username, password)
            else:
                print "Error installing service: %s (%d)" % (exc.strerror,
                                                             exc.winerror)
                err = exc.winerror
Exemplo n.º 18
0
def StartService(serviceName, args = None, machine = None):
    hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_ALL_ACCESS)
    try:

        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        try:
            win32service.StartService(hs, args)
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
Exemplo n.º 19
0
def restartServiceWithDeps(serviceName):
    # stop the service recursively, looking for dependent services.
    # if it fails, attempt to restart the ones that were stopped
    # (so that things are left in the correct state)
    stopped_deps = list()
    hscm = win32service.OpenSCManager(None, None,
                                      win32service.SC_MANAGER_ALL_ACCESS)
    try:
        deps = win32serviceutil.__FindSvcDeps(serviceName)

        for dep in deps:
            hs = win32service.OpenService(hscm, dep,
                                          win32service.SERVICE_ALL_ACCESS)
            try:
                win32serviceutil.__StopServiceWithTimeout(hs)
                stopped_deps.insert(0, dep)
            except pywintypes.error as exc:
                if exc.winerror != winerror.ERROR_SERVICE_NOT_ACTIVE:
                    # walk through and start all the services that have been stopped
                    for restart_dep in stopped_deps:
                        try:
                            win32serviceutil.StartService(restart_dep)
                        except Exception:
                            # this is best effort, just continue restarting
                            pass
                    raise
            finally:
                win32service.CloseServiceHandle(hs)

        # all the deps are stopped.  Stop the one we really wanted to stop
        hs = win32service.OpenService(hscm, serviceName,
                                      win32service.SERVICE_ALL_ACCESS)
        try:
            win32serviceutil.__StopServiceWithTimeout(hs)
        except Exception:
            # if this fails to stop, then restart the dependent services we
            # already stopped.
            for restart_dep in stopped_deps:
                try:
                    win32serviceutil.StartService(restart_dep)
                except Exception:
                    # this is best effort, just continue restarting
                    pass
            raise
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)

    # everything's stopped.  Now just start it back up.  Don't need to restart
    # the dependent services.  If they're to be started, the config file will
    # indicate that, and the agent service will restart the subservices
    win32serviceutil.StartService(DATADOG_SERVICE)
Exemplo n.º 20
0
 def _get_service_handle(service_name,
                         service_access=win32service.SERVICE_QUERY_CONFIG,
                         scm_access=win32service.SC_MANAGER_CONNECT):
     hscm = win32service.OpenSCManager(None, None, scm_access)
     hs = None
     try:
         hs = win32service.OpenService(hscm, service_name, service_access)
         yield hs
     finally:
         if hs:
             win32service.CloseServiceHandle(hs)
         win32service.CloseServiceHandle(hscm)
Exemplo n.º 21
0
def QueryServiceStatus(serviceName, machine=None):
    hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_CONNECT)
    try:

        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_QUERY_STATUS)
        try:
            status = win32service.QueryServiceStatus(hs)
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
    return status
Exemplo n.º 22
0
def ControlService(serviceName, code, machine = None):
    hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_ALL_ACCESS)
    try:

        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        try:
            status = win32service.ControlService(hs, code)
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
    return status
Exemplo n.º 23
0
    def create(self, start_driver):
        if not start_driver: return True

        # check DRIVER_FILE_PATHS for the DRIVER_FILE_NAME
        self.driver_path    = None
        for path in DRIVER_FILE_PATHS:
            driver_path = os.path.join(path, DRIVER_FILE_NAME)
            if os.path.isfile(driver_path):
                self.driver_path = driver_path
                if logger().DEBUG: logger().log("[helper] found driver in {}".format(driver_path))
        if self.driver_path is None:
            if logger().DEBUG:
                logger().log("[helper] CHIPSEC Windows Driver Not Found")
            raise Exception("CHIPSEC Windows Driver Not Found")

        self.show_warning()

        try:
            hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS ) # SC_MANAGER_CREATE_SERVICE
        except win32service.error as err:
            _handle_winerror(err.args[1], err.args[2], err.args[0])
        if logger().DEBUG:
            logger().log( "[helper] service control manager opened (handle = {})".format(hscm) )
            logger().log( "[helper] driver path: '{}'".format(os.path.abspath(self.driver_path)) )

        try:
            hs = win32service.CreateService(
                 hscm,
                 SERVICE_NAME,
                 DISPLAY_NAME,
                 (win32service.SERVICE_QUERY_STATUS|win32service.SERVICE_START|win32service.SERVICE_STOP),
                 win32service.SERVICE_KERNEL_DRIVER,
                 win32service.SERVICE_DEMAND_START,
                 win32service.SERVICE_ERROR_NORMAL,
                 os.path.abspath(self.driver_path),
                 None, 0, u"", None, None )
            if hs:
                if logger().DEBUG: logger().log( "[helper] service '{}' created (handle = 0x{:08X})".format(SERVICE_NAME,int(hs)) )
        except win32service.error as err:
            if (winerror.ERROR_SERVICE_EXISTS == err.args[0]):
                if logger().DEBUG: logger().log( "[helper] service '{}' already exists: {} ({:d})".format(SERVICE_NAME, err.args[2], err.args[0]) )
                try:
                    hs = win32service.OpenService( hscm, SERVICE_NAME, (win32service.SERVICE_QUERY_STATUS|win32service.SERVICE_START|win32service.SERVICE_STOP) ) # SERVICE_ALL_ACCESS
                except win32service.error as _err:
                    _handle_winerror(_err.args[1], _err.args[2], _err.args[0])
            else:
                _handle_winerror(err.args[1], err.args[2], err.args[0])

        finally:
            win32service.CloseServiceHandle( hs )
            win32service.CloseServiceHandle( hscm )

        return True
Exemplo n.º 24
0
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)
Exemplo n.º 25
0
def InstallService(serviceName,
                   displayName,
                   startType=win32service.SERVICE_DEMAND_START,
                   serviceDeps=None,
                   errorControl=win32service.SERVICE_ERROR_NORMAL,
                   userName=None,
                   password=None,
                   description=None):
    """
    This is a copy of a more advanced usecase.
    For chalmers serviceName and displayName are required and the
    defaults should be sufficient
    """
    serviceType = win32service.SERVICE_WIN32_OWN_PROCESS

    script = abspath(service_script.__file__)

    if script.endswith('.pyc') or script.endswith('.pyo'):
        script = script[:-1]

    commandLine = "%s %s" % (sys.executable, script)

    hscm = win32service.OpenSCManager(None, None,
                                      win32service.SC_MANAGER_ALL_ACCESS)

    try:
        hs = win32service.CreateService(
            hscm,
            serviceName,
            displayName,
            win32service.SERVICE_ALL_ACCESS,  # desired access
            serviceType,  # service type
            startType,
            errorControl,  # error control type
            commandLine,
            None,
            0,
            serviceDeps,
            userName,
            password)

        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

        win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
Exemplo n.º 26
0
def QueryService(svc_name):
    """Query service and get its config."""
    hscm = win32service.OpenSCManager(None, None,
                                      win32service.SC_MANAGER_ALL_ACCESS)
    result = None
    try:
        hs = win32serviceutil.SmartOpenService(hscm, svc_name,
                                               win32service.SERVICE_ALL_ACCESS)
        result = win32service.QueryServiceConfig(hs)
        win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)

    return result
Exemplo n.º 27
0
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):
    # 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

        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)
Exemplo n.º 28
0
	def ReloadData(self):
		service = self.GetSelService()
		self.listCtrl.SetRedraw(0)
		self.listCtrl.ResetContent()
		svcs = win32service.EnumServicesStatus(self.scm)
		i = 0
		self.data = []
		for svc in svcs:
			try:
				status = ('Unknown', 'Stopped', 'Starting', 'Stopping', 'Running',
					'Continuing', 'Pausing', 'Paused')[svc[2][1]]
			except:
				status = 'Unknown'
			s = win32service.OpenService(self.scm, svc[0], win32service.SERVICE_ALL_ACCESS)
			cfg = win32service.QueryServiceConfig(s)
			try:
				startup = ('Boot', 'System', 'Automatic', 'Manual', 'Disabled')[cfg[1]]
			except:
				startup = 'Unknown'
			win32service.CloseServiceHandle(s)

			# svc[2][2] control buttons
			pos = self.listCtrl.AddString(str(svc[1]) + '\t' + status + '\t' + startup)
			self.listCtrl.SetItemData(pos, i)
			self.data.append(tuple(svc[2]) + (svc[1], svc[0], ))
			i = i + 1

			if service and service[1] == svc[0]:
				self.listCtrl.SetCurSel(pos)
		self.OnListEvent(self.IDC_LIST, win32con.LBN_SELCHANGE)
		self.listCtrl.SetRedraw(1)
Exemplo n.º 29
0
    def start( self ):

        (type, state, ca, exitcode, svc_exitcode, checkpoint, waithint) = win32service.QueryServiceStatus( self.hs )
        if logger().VERBOSE: logger().log( "[helper] starting chipsec service: handle = 0x%x, type = 0x%x, state = 0x%x" % (self.hs, type, state) )

        if win32service.SERVICE_RUNNING == state:
            if logger().VERBOSE: logger().log( "[helper] chipsec service already running" )
        else:
            try:
                win32service.StartService( self.hs, None );
                state = win32service.QueryServiceStatus( self.hs )[1]
                while win32service.SERVICE_START_PENDING == state:
                    time.sleep( 1 )
                    state = win32service.QueryServiceStatus( self.hs )[1]
                if win32service.SERVICE_RUNNING == state:
                    if logger().VERBOSE: logger().log( "[helper] chipsec service started (SERVICE_RUNNING)" )
            except win32service.error, (hr, fn, msg):
                if logger().VERBOSE: logger().log_bad(traceback.format_exc())
                if (winerror.ERROR_ALREADY_EXISTS == hr or winerror.ERROR_SERVICE_ALREADY_RUNNING == hr):
                    if logger().VERBOSE: logger().log( "[helper] chipsec service already exists: %s (%d)" % (msg, hr) )
                else:
                    win32service.CloseServiceHandle( self.hs )
                    self.hs = None
                    string  = "StartService failed: %s (%d)" % (msg, hr)
                    logger().error( string )
                    raise OsHelperError(string,hr)
Exemplo n.º 30
0
    def remove_service(self, also_close_as=True):
        self.session.logging.debug("Removing service %s",
                                   self.plugin_args.service_name)

        # Make sure the handle is closed.
        if also_close_as:
            self.session.physical_address_space.close()

        # Stop the service if it's running.
        if not self.hSvc:
            try:
                self.hSvc = win32service.OpenService(
                    self.hScm, self.plugin_args.service_name,
                    win32service.SERVICE_ALL_ACCESS)
            except win32service.error:
                self.session.logging.debug("%s service does not exist.",
                                           self.plugin_args.service_name)

        if self.hSvc:
            self.session.logging.debug("Stopping service: %s",
                                       self.plugin_args.service_name)
            try:
                win32service.ControlService(self.hSvc,
                                            win32service.SERVICE_CONTROL_STOP)
            except win32service.error as e:
                self.session.logging.debug("Error stopping service: %s", e)

            self.session.logging.debug("Deleting service: %s",
                                       self.plugin_args.service_name)
            try:
                win32service.DeleteService(self.hSvc)
            except win32service.error as e:
                self.session.logging.debug("Error deleting service: %s", e)

            win32service.CloseServiceHandle(self.hSvc)