def installService(cls, name, display_name=None, stay_alive=True): cls._svc_name_ = name cls._svc_display_name_ = display_name or name try: module_path = modules[cls.__module__].__file__ except AttributeError: # maybe py2exe went by from sys import executable module_path = executable module_file = splitext(abspath(module_path))[0] cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__) if stay_alive: win32api.SetConsoleCtrlHandler(lambda x: True, True) try: win32serviceutil.InstallService( cls._svc_reg_class_, cls._svc_name_, cls._svc_display_name_, startType=win32service.SERVICE_AUTO_START) print 'Installing service %s... done' % name win32serviceutil.StartService(cls._svc_name_) print 'Starting service %s... done' % name print '\nAll done!' except Exception, x: print str(x)
def instart(cls, name, display_name=None, stay_alive=True): from os.path import splitext, abspath from sys import modules cls.__svc_name_ = name cls.__svc_display_name_ = display_name try: module_path = modules[cls.__module__].__file__ except AttributeError: from sys import executable module_path = executable module_file = splitext(abspath(module_path)) cls.__svc_reg_class = "%s.%s" % (module_file, cls.__name__) if stay_alive: win32api.SetConsoleCtrlHandler(lambda x: True, True) try: try: print "[+] TestModule Started : %s" % (name) win32serviceutil.QueryServiceStatus(cls.__name__) except: win32serviceutil.InstallService( cls.__svc_reg_class, cls.__svc_name_, cls.__svc_display_name_, startType=win32service.SERVICE_AUTO_START) print "[+] Service Has been installed" else: try: win32serviceutil.StartService(cls._svc_name_) except Exception, e: print "[!] %s : %s" % (e.__class__, str(e)) else:
def install(self): """Installs the service so it can be started and stopped (if it's not installed yet). Returns: True when installing the service was a success and false when it failed. """ # Build up wrapper script script_name = self.service.__class__.__name__ module_name = win32serviceutil.GetServiceClassString(self.service.__class__) module_name = module_name.replace('.' + script_name, '') print(module_name) print(script_name) # Enable auto-start if needed service_start_type = None if self.auto_start: win32api.SetConsoleCtrlHandler(lambda control_handler: True, True) service_start_type = win32service.SERVICE_AUTO_START # Install the service win32serviceutil.InstallService( self.class_name, self.name, self.name, startType = service_start_type, description = self.description )
def installService(nvdaDir): servicePath = os.path.join(nvdaDir, __name__ + ".exe") if not os.path.isfile(servicePath): raise RuntimeError("Could not find service executable") win32serviceutil.InstallService(None, NVDAService._svc_name_, NVDAService._svc_display_name_, startType=win32service.SERVICE_AUTO_START, exeName=servicePath, # Translators: The description of the NVDA service. description=_(u"Allows NVDA to run on the Windows Logon screen, UAC screen and other secure screens."))
def instart(cls, name, display_name=None, stay_alive=True): ''' Install and Start (auto) a Service cls : the class (derived from Service) that implement the Service name : Service name display_name : the name displayed in the service manager stay_alive : Service will stop on logout if False ''' cls._svc_name_ = name cls._svc_display_name_ = display_name or name try: module_path = modules[cls.__module__].__file__ except AttributeError: # maybe py2exe went by from sys import executable module_path = executable module_file = splitext(abspath(module_path))[0] cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__) if stay_alive: win32api.SetConsoleCtrlHandler(lambda x: True, True) try: win32serviceutil.InstallService( cls._svc_reg_class_, cls._svc_name_, cls._svc_display_name_, startType=win32service.SERVICE_AUTO_START) print "Install ok" win32serviceutil.StartService(cls._svc_name_) print 'Start ok' except Exception, x: print str(x)
def installService(nvdaDir): servicePath = os.path.join(nvdaDir, __name__ + ".exe") if not os.path.isfile(servicePath): raise RuntimeError("Could not find service executable") win32serviceutil.InstallService(None, NVDAService._svc_name_, NVDAService._svc_display_name_, startType=win32service.SERVICE_AUTO_START, exeName=servicePath)
def instart (): module_path = os.path.splitext(os.path.realpath(__file__))[0] class_name = "{}.{}".format(module_path, AppServerSvc.__name__) win32serviceutil.InstallService(class_name, SERVICE_NAME, SERVICE_DISPLAY_NAME, startType=win32service.SERVICE_AUTO_START, ) print('Install OK') win32serviceutil.StartService(SERVICE_NAME)
def do_install(self, arg): # see "collective.buildout.cluster.base.ClusterBase.install()" if not shell.IsUserAnAdmin(): print(ERR_MSG_NOT_ADMIN) return status = self._get_service_status() if status is not None: print 'ERROR: Zope is already installed as a Windows service.' return # TODO: Are return values from do_ methods are really taken care of? # http://docs.python.org/library/cmd.html: "The return value is a # flag indicating whether interpretation of commands # by the interpreter should stop." ret_code = 0 class_string = self._get_service_class_string() name = self._get_service_name() display_name = 'Zope instance at '+ self.options.directory if arg.lower() == 'auto': start_type = win32service.SERVICE_AUTO_START else: start_type = win32service.SERVICE_DEMAND_START try: win32serviceutil.InstallService(class_string, name, display_name, start_type) # put info in registry for the Windows Service class to use: instance_script = self.options.progname # for example # 'D:\\local\\Plone-4.0b5\\bin\\instance-script.py' # but the Windows Service must launch # 'D:\\local\\Plone-4.0b5\\bin\\instance.exe' script_suffix = '-script.py' pos = instance_script.rfind(script_suffix) instance_exe = instance_script[:pos] + '.exe' self._set_winreg_key('command', '"%s" console' % instance_exe) self._set_winreg_key('pid_filename', self.options.configroot.pid_filename) print 'Installed Zope as Windows Service "%s".' % name except pywintypes.error: traceback.print_exc() ret_code = 1 return ret_code
def w32_install_svc(start=False, server_only=True, programs=None): '''Install Windows Ramona Service''' import logging L = logging.getLogger('winsvc') directory = abspath(dirname( sys.argv[0])) # Find where console python prog is launched from ... cls = w32_ramona_service if cls._svc_name_ is None: cls.configure() try: module_path = modules[cls.__module__].__file__ except AttributeError: # maybe py2exe went by from sys import executable module_path = executable module_file = splitext(abspath(join(module_path, '..', '..', '..')))[0] cls._svc_reg_class_ = '{0}\\ramona.console.winsvc.{1}'.format( module_file, cls.__name__) win32api.SetConsoleCtrlHandler( lambda x: True, True) # Service will stop on logout if False # Prepare command line cmdline = [] if server_only: cmdline.append('-S') elif programs is not None: cmdline.extend(programs) # Install service win32serviceutil.InstallService( cls._svc_reg_class_, cls._svc_name_, cls._svc_display_name_, startType=win32service.SERVICE_AUTO_START, exeArgs=' '.join(cmdline), ) # Set directory from which Ramona server should be launched ... win32serviceutil.SetServiceCustomOption(cls._svc_name_, 'directory', directory) win32serviceutil.SetServiceCustomOption(cls._svc_name_, 'config', ';'.join(config_files)) L.debug("Service {0} installed".format(cls._svc_name_)) if start: x = win32serviceutil.StartService(cls._svc_name_) L.debug("Service {0} is starting ...".format(cls._svc_name_)) #TODO: Wait for service start to check start status ... L.debug("Service {0} started".format(cls._svc_name_)) return cls
def create(self, **kwargs): logger.info("installing service: %s", self.svc_name) try: win32serviceutil.InstallService(self.svc_clss, self.svc_name, self.svc_disp) self.config(**kwargs) logger.info("service installed") except win32service.error as exc: if exc.winerror == winerror.ERROR_SERVICE_EXISTS: self.config(**kwargs) else: logger.info("error installing service: %s (%d)", exc.strerror, exc.winerror)
def __install(args): if sys.platform.startswith('win'): if args.mode is None or args.mode == 'delayed': delayed_start = True else: delayed_start = False w32scu.InstallService(pythonClassString=args.py_class, serviceName=args.name, displayName=args.display_name, description=args.description, startType=w32svc.SERVICE_AUTO_START, delayedstart=delayed_start)
def install(cls, service_class, service_name, settings_file): settings_file = os.path.abspath(settings_file) service_class_path = get_class_path(service_class) service_class(settings_file) # validate settings win32serviceutil.InstallService(get_class_path(cls), service_name, service_name) win32serviceutil.SetServiceCustomOption(service_name, cls.SETTINGS_FILE_PARAM, settings_file) win32serviceutil.SetServiceCustomOption(service_name, cls.CLASS_PATH_PARAM, service_class_path)
def install(cls, username=None, password=None, start_type=None): if hasattr(cls, '_svc_reg_class_'): svc_class = cls._svc_reg_class_ else: svc_class = win32serviceutil.GetServiceClassString(cls) win32serviceutil.InstallService( svc_class, cls._svc_name_, cls._svc_display_name_, description=cls._svc_description_, userName=username, password=password, startType=start_type, )
def Install(cls): state = cls.__CurrentState() if state is not None: print("Service %s installed already." % cls._svc_name_) return modulePath = WindowsService.__getModuleFile() classString = os.path.splitext(modulePath)[0] + '.' + cls.__name__ win32serviceutil.InstallService( pythonClassString=classString, serviceName=cls._svc_name_, displayName=cls._svc_display_name_ or cls._svc_name_, description=cls._svc_description_ or cls._svc_display_name_ or cls._svc_name_, startType=win32service.SERVICE_AUTO_START) print("Service %s installed successfully." % cls._svc_name_)
def install(self, stay_alive=True): ''' stay_alive : Service will stop on logout if False ''' if stay_alive: win32api.SetConsoleCtrlHandler(lambda x: True, True) try: win32serviceutil.InstallService( self.cls._svc_reg_class_, self.cls._svc_name_, self.cls._svc_display_name_, startType = win32service.SERVICE_AUTO_START ) return True except Exception as e: # the service is already if e[0] in [1073]: return False else: raise
def __install(self, su_aware, cmd, binary): try: w32scu.InstallService(pythonClassString=self.python_class, serviceName=self.name, displayName=self.display_name, description=self.description, startType=w32svc.SERVICE_AUTO_START, delayedstart=True) except WinT.error, e: if e.args[0] == werr.ERROR_ACCESS_DENIED: if not su_aware: raise DaemonPrivilegeException( 'Windows daemon service installation failed: ' 'Administrator privileges are required!', 'ERROR_ACCESS_DENIED', e.args[0]) else: self.__elevate(binary=binary, cmd=cmd, timeout=self.setup_timeout)
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])
def insert_service(user, cmd, arg): from os import environ as env from os import getcwd as pwd from shutil import which # get servive name name = WinService.name() # get servise display name display = WinService.display_name() try: # install Servive wu.InstallService(wu.GetServiceClassString(WinService), name, display, userName=user) # success click.echo(f'INSTALLED: {name}') except ws.error as ex: raise click.ClickException(ex.strerror) except Exception as ex: raise click.ClickException(ex.strerror)
def installsvc(service): win32serviceutil.InstallService(service._svc_reg_class_, service._svc_name_, service._svc_display_name_, startType=win32service.SERVICE_AUTO_START, description=service._svc_description_)
elif o == "password": password = a elif o == "interactive": bRunInteractive = True if do_install: for k in service_klasses: svc_display_name = getattr(k, "_svc_display_name_", k._svc_name_) svc_deps = getattr(k, "_svc_deps_", None) win32serviceutil.InstallService( None, k._svc_name_, svc_display_name, exeName=sys.executable, userName=userName, password=password, startType=startType, bRunInteractive=bRunInteractive, serviceDeps=svc_deps, description=getattr(k, "_svc_description_", None), ) done = True if do_remove: for k in service_klasses: win32serviceutil.RemoveService(k._svc_name_) done = True if done: sys.exit(0) else:
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
def SvcDoRun(self): app.run(host='0.0.0.0', port=5008) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOPPED) exit() if __name__ == '__main__': try: servicemanager.Initialize() servicemanager.PrepareToHostSingle(BackendService) servicemanager.StartServiceCtrlDispatcher() except: try: win32serviceutil.StopService("IP_BACKEND") except: pass try: win32serviceutil.InstallService( win32serviceutil.GetServiceClassString(BackendService), BackendService._svc_name_, BackendService._svc_display_name_, startType=win32service.SERVICE_AUTO_START) except: pass win32serviceutil.StartService("IP_BACKEND")
from os.path import splitext, abspath from sys import modules cls = TestService try: module_path=modules[cls.__module__].__file__ except AttributeError: from sys import executable module_path=executable module_file = splitext(abspath(module_path)) cls.__svc_reg_class = "%s.%s" % (module_file,cls.__name__) win32api.SetConsoleCtrlHandler(lambda x: True,True) try: win32serviceutil.QueryServiceStatus(cls.__name__) except: win32serviceutil.InstallService( cls.__svc_reg_class, cls.__svc_name_, cls.__svc_display_name_, startType=win32service.SERVICE_AUTO_START ) print "[+] Service Has been installed" else: win32serviceutil.HandleCommandLine(cls,argv=["update"]) finally: win32serviceutil.HandleCommandLine(cls,argv=["debug"]) try: while True: time.sleep(1) except: exit()