Пример #1
0
  def Run(self, unused_arg):
    """This kills us with no cleanups."""
    logging.debug("Disabling service")

    win32serviceutil.ChangeServiceConfig(
        None, config_lib.CONFIG["Nanny.service_name"],
        startType=win32service.SERVICE_DISABLED)
    svc_config = QueryService(config_lib.CONFIG["Nanny.service_name"])
    if svc_config[1] == win32service.SERVICE_DISABLED:
      logging.info("Disabled service successfully")
      self.SendReply(string="Service disabled.")
    else:
      self.SendReply(string="Service failed to disable.")
Пример #2
0
    def is_installed(self):
        """Determines whether this service is installed on this system.

        Returns:
            True when this service is installed on this system and false
            when it was not installed on this system.
        """

        try:
            win32serviceutil.ChangeServiceConfig(self.class_name, self.name)
        except:
            return False
        return True
Пример #3
0
 def setup(cls, cmd, user=None, password=None, startup='manual', cwd=None, wait=0):
     from gramex.config import app_log
     name, service_name = cls._svc_display_name_, cls._svc_name_
     port = getattr(cls, '_svc_port_', None)
     if cwd is None:
         cwd = os.getcwd()
     info = (name, cwd, 'port %s' % port if port is not None else '')
     service_class = win32serviceutil.GetServiceClassString(cls)
     startup = cls.startup_map[startup]
     running = win32service.SERVICE_RUNNING
     if cmd[0] == 'install':
         win32serviceutil.InstallService(
             service_class, service_name, displayName=name, description=cls._svc_description_,
             startType=startup, userName=user, password=password)
         win32serviceutil.SetServiceCustomOption(cls._svc_name_, 'cwd', cwd)
         app_log.info('Installed service. %s will run from %s %s' % info)
     elif cmd[0] in {'update', 'change'}:
         win32serviceutil.ChangeServiceConfig(
             service_class, service_name, displayName=name, description=cls._svc_description_,
             startType=startup, userName=user, password=password)
         win32serviceutil.SetServiceCustomOption(cls._svc_name_, 'cwd', cwd)
         app_log.info('Updated service. %s will run from %s %s' % info)
     elif cmd[0] in {'remove', 'uninstall'}:
         try:
             win32serviceutil.StopService(service_name)
         except pywintypes.error as e:
             if e.args[0] != winerror.ERROR_SERVICE_NOT_ACTIVE:
                 raise
         win32serviceutil.RemoveService(service_name)
         app_log.info('Removed service. %s ran from %s %s' % info)
     elif cmd[0] == 'start':
         win32serviceutil.StartService(service_name, cmd[1:])
         if wait:
             win32serviceutil.WaitForServiceStatus(service_name, running, wait)
         app_log.info('Started service %s at %s %s' % info)
     elif cmd[0] == 'stop':
         if wait:
             win32serviceutil.StopServiceWithDeps(service_name, waitSecs=wait)
         else:
             win32serviceutil.StopService(service_name)
         app_log.info('Stopped service %s at %s %s' % info)
     elif cmd[0]:
         app_log.error('Unknown command: %s' % cmd[0])
Пример #4
0
def stop_services(services: list, disable_startup: bool = True) -> None:
    import win32serviceutil

    print('Number of services: %i' % len(services))
    print('Stopping services...')
    for service in services:
        print()
        try:
            if win32serviceutil.QueryServiceStatus(service[0])[1] == 4:
                win32serviceutil.StopService(service[0])
                print('%s stopped.' % service[1])
            else:
                print('%s was already stopped.' % service[1])
        except:
            print('\tCould not stop service %s!' % service[1])
        if disable_startup:
            try:
                win32serviceutil.ChangeServiceConfig(None, serviceName=service[0], startType='disabled', delayedstart=None)
                print('%s startup settings changed.' % service[1])
            except:
                print('\tCould not change settings of service %s!' % service[1])
                if service[1] == 'Update Orchestrator Service':
                    print('\tThis is an expected behaviour.')
    print('\nFinished stopping services.')
Пример #5
0
 def config(self, svc_disp=None, svc_desp=None, svc_deps=None, username=None, password=None, exe_name=None, exe_args=None, startup=None, interactive=None):
     starttype = None
     delayedstart = None
     if startup is not None:
         mapping = {"manual": win32service.SERVICE_DEMAND_START,
                    "auto": win32service.SERVICE_AUTO_START,
                    "delayed": win32service.SERVICE_AUTO_START,
                    "disabled": win32service.SERVICE_DISABLED}
         try:
             starttype = mapping[startup.lower()]
         except KeyError:
             logger.info("'%s' is not a valid startup option", startup)
     
         if startup.lower() == "delayed":
             delayedstart = True
         elif startup.lower() == "auto":
             delayedstart = False
     
     try:
         win32serviceutil.ChangeServiceConfig(self.svc_clss, 
                                              self.svc_name,
                                              serviceDeps=svc_deps,
                                              startType=starttype,
                                              bRunInteractive=interactive,
                                              userName=username,
                                              password=password,
                                              exeName=exe_name,
                                              displayName=svc_disp,
                                              perfMonIni=None,
                                              perfMonDll=None,
                                              exeArgs=exe_args,
                                              description=svc_desp,
                                              delayedstart=delayedstart)
         logger.info("service '%s' updated", self.svc_name)
     except win32service.error as exc:
         logger.info("error changing service '%s' configuration: %s (%d)", self.svc_name, exc.strerror, exc.winerror)
Пример #6
0
def HandleCommandLine(cls,
                      command,
                      customInstallOptions="",
                      customOptionHandler=None):
    """Utility function allowing services to process the command line.
    Allows standard commands such as 'start', 'stop', 'debug', 'install' etc.
    Install supports 'standard' command line options prefixed with '--', such as
    --username, --password, etc.  In addition,
    the function allows custom command line options to be handled by the calling function.
    """
    err = 0

    serviceName = cls._svc_name_
    serviceDisplayName = cls._svc_display_name_
    serviceClassString = "aservice"

    # Pull apart the command line
    import getopt
    opts = []
    args = []

    userName = None
    password = None
    perfMonIni = perfMonDll = None
    startup = None
    delayedstart = None
    interactive = None
    waitSecs = 0
    for opt, val in opts:
        if opt == '--username':
            userName = val
        elif opt == '--password':
            password = val
        elif opt == '--perfmonini':
            perfMonIni = val
        elif opt == '--perfmondll':
            perfMonDll = val
        elif opt == '--interactive':
            interactive = 1
        elif opt == '--startup':
            map = {
                "manual": win32service.SERVICE_DEMAND_START,
                "auto": win32service.SERVICE_AUTO_START,
                "delayed": win32service.
                SERVICE_AUTO_START,  ## ChangeServiceConfig2 called later
                "disabled": win32service.SERVICE_DISABLED
            }
            try:
                startup = map[val.lower()]
            except KeyError:
                print("'%s' is not a valid startup option" % val)
            if val.lower() == "delayed":
                delayedstart = True
            elif val.lower() == "auto":
                delayedstart = False
            ## else no change
        elif opt == '--wait':
            try:
                waitSecs = int(val)
            except ValueError:
                print("--wait must specify an integer number of seconds.")

    arg = command
    knownArg = 0
    # First we process all arguments which pass additional args on
    if arg == "start":
        knownArg = 1
        print("Starting service %s" % (serviceName))
        try:
            win32serviceutil.StartService(serviceName, args[1:])
            if waitSecs:
                WaitForServiceStatus(serviceName, win32service.SERVICE_RUNNING,
                                     waitSecs)
        except Exception as ex:
            print("Error starting service:", ex)

    elif arg == "restart":
        knownArg = 1
        print("Restarting service %s" % (serviceName))
        RestartService(serviceName, args[1:])
        if waitSecs:
            WaitForServiceStatus(serviceName, win32service.SERVICE_RUNNING,
                                 waitSecs)

    elif arg == "debug":
        knownArg = 1
        if not hasattr(sys, "frozen"):
            # non-frozen services use pythonservice.exe which handles a
            # -debug option
            svcArgs = " ".join(args[1:])
            try:
                exeName = LocateSpecificServiceExe(serviceName)
            except Exception as ex:
                print("The service does not appear to be installed.")
                print("Please install the service before debugging it.")
                sys.exit(1)
            try:
                os.system("%s -debug %s %s" % (exeName, serviceName, svcArgs))
            # ^C is used to kill the debug service.  Sometimes Python also gets
            # interrupted - ignore it...
            except KeyboardInterrupt:
                pass
        else:
            # py2exe services don't use pythonservice - so we simulate
            # debugging here.
            DebugService(cls, args)

    #if not knownArg and len(args)!=1:
    #    usage() # the rest of the cmds don't take addn args

    if arg == "install":
        knownArg = 1
        try:
            serviceDeps = cls._svc_deps_
        except AttributeError:
            serviceDeps = None
        try:
            exeName = cls._exe_name_
        except AttributeError:
            exeName = None  # Default to PythonService.exe
        try:
            exeArgs = cls._exe_args_
        except AttributeError:
            exeArgs = None
        try:
            description = cls._svc_description_
        except AttributeError:
            description = None
        print("Installing service %s" % (serviceName, ))
        # Note that we install the service before calling the custom option
        # handler, so if the custom handler fails, we have an installed service (from NT's POV)
        # but is unlikely to work, as the Python code controlling it failed.  Therefore
        # we remove the service if the first bit works, but the second doesnt!
        try:
            win32serviceutil.InstallService(serviceClassString,
                                            serviceName,
                                            serviceDisplayName,
                                            serviceDeps=serviceDeps,
                                            startType=startup,
                                            bRunInteractive=interactive,
                                            userName=userName,
                                            password=password,
                                            exeName=exeName,
                                            perfMonIni=perfMonIni,
                                            perfMonDll=perfMonDll,
                                            exeArgs=exeArgs,
                                            description=description,
                                            delayedstart=delayedstart)
            if customOptionHandler:
                customOptionHandler(*(opts, ))
            print("Service installed")
        except win32service.error as exc:
            if exc.winerror == winerror.ERROR_SERVICE_EXISTS:
                arg = "update"  # Fall through to the "update" param!
            else:
                print("Error installing service: %s (%d)" %
                      (exc.strerror, exc.winerror))
                err = exc.winerror
        except ValueError as ex:  # Can be raised by custom option handler.
            print("Error installing service: ", ex.message)
            err = -1
            # xxx - maybe I should remove after _any_ failed install - however,
            # xxx - it may be useful to help debug to leave the service as it failed.
            # xxx - We really _must_ remove as per the comments above...
            # As we failed here, remove the service, so the next installation
            # attempt works.
            try:
                RemoveService(serviceName)
            except win32api.error:
                print(
                    "Warning - could not remove the partially installed service."
                )

    if arg == "update":
        knownArg = 1
        try:
            serviceDeps = cls._svc_deps_
        except AttributeError:
            serviceDeps = None
        try:
            exeName = cls._exe_name_
        except AttributeError:
            exeName = None  # Default to PythonService.exe
        try:
            exeArgs = cls._exe_args_
        except AttributeError:
            exeArgs = None
        try:
            description = cls._svc_description_
        except AttributeError:
            description = None
        print("Changing service configuration")
        try:
            win32serviceutil.ChangeServiceConfig(
                serviceClassString,
                serviceName,
                serviceDeps=serviceDeps,
                startType=startup,
                bRunInteractive=interactive,
                userName=userName,
                password=password,
                exeName=exeName,
                displayName=serviceDisplayName,
                perfMonIni=perfMonIni,
                perfMonDll=perfMonDll,
                exeArgs=exeArgs,
                description=description,
                delayedstart=delayedstart)
            if customOptionHandler:
                customOptionHandler(*(opts, ))
            print("Service updated")
        except win32service.error as exc:
            print("Error changing service configuration: %s (%d)" %
                  (exc.strerror, exc.winerror))
            err = exc.winerror

    elif arg == "remove":
        knownArg = 1
        print("Removing service %s" % (serviceName))
        try:
            RemoveService(serviceName)
            print("Service removed")
        except win32service.error as exc:
            print("Error removing service: %s (%d)" %
                  (exc.strerror, exc.winerror))
            err = exc.winerror
    elif arg == "stop":
        knownArg = 1
        print("Stopping service %s" % (serviceName))
        try:
            if waitSecs:
                StopServiceWithDeps(serviceName, waitSecs=waitSecs)
            else:
                StopService(serviceName)
        except win32service.error as exc:
            print("Error stopping service: %s (%d)" %
                  (exc.strerror, exc.winerror))
            err = exc.winerror
    if not knownArg:
        err = -1
        print("Unknown command - '%s'" % arg)
        #usage()
    return err