def start_service(): with log_context({'instance', 'opsiclientd'}): logger.essential("opsiclientd service start") #logger.debug(os.environ) servicemanager.Initialize() servicemanager.PrepareToHostSingle(OpsiclientdService) servicemanager.StartServiceCtrlDispatcher()
def _main(): _configure_logging() if len(sys.argv) == 1 and \ sys.argv[0].endswith('.exe') and \ not sys.argv[0].endswith(r'win32\PythonService.exe'): # invoked as non-pywin32-PythonService.exe executable without # arguments # We assume here that we were invoked by the Windows Service # Control Manager (SCM) as a PyInstaller executable in order to # start our service. # Initialize the service manager and start our service. servicemanager.Initialize() servicemanager.PrepareToHostSingle(ExampleService) servicemanager.StartServiceCtrlDispatcher() else: # invoked with arguments, or without arguments as a regular # Python script # We support a "help" command that isn't supported by # `win32serviceutil.HandleCommandLine` so there's a way for # users who run this script from a PyInstaller executable to see # help. `win32serviceutil.HandleCommandLine` shows help when # invoked with no arguments, but without the following that would # never happen when this script is run from a PyInstaller # executable since for that case no-argument invocation is handled # by the `if` block above. if len(sys.argv) == 2 and sys.argv[1] == 'help': sys.argv = sys.argv[:1] win32serviceutil.HandleCommandLine(ExampleService)
def main(): """Installs the service using admin privileges. Privilege code taken from Jorenko's answer at https://stackoverflow.com/questions/130763/request-uac-elevation-from-within-a-python-script#answer-11746382""" print( 'Call this executable as "service_frozen.exe --startup=auto install" to install the service with autostart' ) logger.info('Service main running as frozen dist.') logger.info('Service called with args: %s', sys.argv) if not shell.IsUserAnAdmin(): # running as not admin new_args = sys.argv[1:] cmdline_params = ' '.join(new_args) logger.info('Rerun as admin params: %s', cmdline_params) val = shell.ShellExecuteEx( lpVerb='runas', lpFile=sys.executable, lpParameters=cmdline_params) # relaunch as admin else: logger.info('Service is admin') # running as not admin logger.info( 'Delegate to win32serviceutil.HandleCommandLine with params: %s', sys.argv) with open(LOG_PATH, 'a') as f: # cause calls to print() to be written to a file with contextlib.redirect_stdout(f): # the Windows Service framework calls this executable with no # args. if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(RegrOSService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(RegrOSService)
def __init__(self, args): super().__init__(args) # Create an event which we will use to wait on. The "service stop" # request will set this event. # * We must make it inheritable so we can pass it to the child # process via the cmd-line # * Must be manual reset so each child process and our service # all get woken from a single set of the event. sa = win32security.SECURITY_ATTRIBUTES() sa.bInheritHandle = True self.hWaitStop = win32event.CreateEvent(sa, True, False, None) self.args = args self.dirs = None self.runner_prefix = None # Patch up the service messages file in a frozen exe. # (We use the py2exe option that magically bundles the .pyd files # into the .zip file - so servicemanager.pyd doesn't exist.) if is_frozen and servicemanager.RunningAsService(): msg_file = os.path.join(os.path.dirname(sys.executable), "buildbot.msg") if os.path.isfile(msg_file): servicemanager.Initialize("BuildBot", msg_file) else: self.warning("Strange - '%s' does not exist" % (msg_file, ))
def run_service(app_service_class): """ .. note:: This function is only implemented for Windows and Systemd based linux distributions :param app_service_class: service class from :func:`get_service` Create an instance of `app_service_class` and run as service Example:: from netdef.service import get_service, run_service def run_app(): from . import main def get_template_config(): from . import defaultconfig return defaultconfig.template_config_string application_service = get_service("First-App", "First-App-Service", run_app, get_template_config) run_service(application_service) """ if "-r" in sys.argv: proj_path = pathlib.Path(sys.argv[-1]).expanduser().absolute() os.chdir(str(proj_path)) servicemanager.Initialize() servicemanager.PrepareToHostSingle(app_service_class) servicemanager.StartServiceCtrlDispatcher() else: proj_path = pathlib.Path(os.curdir).expanduser().absolute() app_service_class._exe_args_ = '-r "' + str(proj_path) + '"' win32serviceutil.HandleCommandLine(app_service_class)
def init(): if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(MyServiceFramework) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(MyServiceFramework)
def run() -> None: if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(UDSActorSvc) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(UDSActorSvc)
def main(): AllUsersProfile = os.environ.get('AllUsersProfile', 'C:\\ProgramData') logfile = os.path.join(AllUsersProfile, '%s-chalmers-service-log.txt' % getpass.getuser()) try: logfd = open(logfile, 'a', 1) except: # I guess we will have to leave it up to the windows event log traceback.print_exc() else: sys.stdout = sys.stderr = logfd print('---') print("Starting Chalmers Service", time.ctime()) sys.stdout.flush() try: from chalmers.windows.chalmers_service import ChalmersService import servicemanager servicemanager.Initialize(None, None) servicemanager.PrepareToHostSingle(ChalmersService) servicemanager.StartServiceCtrlDispatcher() finally: print("Exiting Chalmers Service", time.ctime()) sys.stdout.flush()
def manage_service(service, args): if len(args) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(service) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(service)
def windows_main(): # Windows script may be called for 4 different reason: # * post/pre install/remove script # * To run the service # * To run Bleemeo agent from the console # * To install/remove the service if ('--post-install' in sys.argv or '--pre-install' in sys.argv or '--pre-remove' in sys.argv): parser = argparse.ArgumentParser(description='Bleemeo agent') # Internal flag, used by installer parser.add_argument( '--post-install', default=False, action='store_true', help=argparse.SUPPRESS, ) parser.add_argument( '--pre-install', default=False, action='store_true', help=argparse.SUPPRESS, ) parser.add_argument( '--pre-remove', default=False, action='store_true', help=argparse.SUPPRESS, ) parser.add_argument( '--account', help=argparse.SUPPRESS, ) parser.add_argument( '--registration', help=argparse.SUPPRESS, ) args = parser.parse_args() if args.post_install: windows_postinstall(args) elif args.pre_install: windows_preinstall(args) elif args.pre_remove: windows_preremove(args) elif len(sys.argv) == 2 and sys.argv[1] == '--run-service': servicemanager.Initialize() servicemanager.PrepareToHostSingle(BleemeoAgentService) servicemanager.StartServiceCtrlDispatcher() elif len(sys.argv) == 1: # no argument, run bleemeo-agent on console try: core = bleemeo_agent.core.Core() core.run() finally: logging.info('Agent stopped') else: win32serviceutil.HandleCommandLine(BleemeoAgentService)
def runService(self): if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(PyService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(PyService) pass
def main(): if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(SMTPuttService) servicemanager.StartServiceCtrlDispatcher() else: SMTPuttService.handle_cmd()
def run_windows_service(action, host=None, port=None, exeName=None): # Prepare the arguments that are going to be used with the service # command line args = [ 'TraktForVLC', ] if action == 'install': args.extend(['--startup', 'auto']) if action is not None: args.append(action) # Prepare the args that will be passed to the service executable exe_args = [ 'service', ] if host is not None: exe_args.append('--host={}'.format(host)) if port is not None: exe_args.append('--port={}'.format(port)) # Prepare the class that represents the Windows Service class TraktForVLCWindowsService(win32serviceutil.ServiceFramework): _svc_name_ = 'TraktForVLC' _svc_display_name_ = 'TraktForVLC' _svc_description_ = 'TraktForVLC helper tool' _exe_name_ = exeName _exe_args_ = ' '.join(exe_args) def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): rc = None # noqa: F841 def stop_condition(): rc = win32event.WaitForSingleObject(self.hWaitStop, 0) return rc == win32event.WAIT_OBJECT_0 try: run_service(host, port, stop_condition=stop_condition) except Exception as e: LOGGER.exception(e) raise if len(args) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(TraktForVLCWindowsService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(TraktForVLCWindowsService, argv=args)
def win32_main(): import win32serviceutil import servicemanager from win_service import AppServerSvc if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(AppServerSvc) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(AppServerSvc)
def SvcDoRun(self): self.Start_MaayService() import servicemanager win32evtlogutil.AddSourceToRegistry(self._svc_name_, servicemanager.__file__) servicemanager.Initialize(self._svc_name_, servicemanager.__file__) servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ''))
def main(argv): del argv # Unused FakeFleetspeakSvc.ParseFlags() if flags.FLAGS.command: win32serviceutil.HandleCommandLine( FakeFleetspeakSvc, argv=[sys.argv[0], flags.FLAGS.command]) else: servicemanager.Initialize() servicemanager.PrepareToHostSingle(FakeFleetspeakSvc) servicemanager.StartServiceCtrlDispatcher()
def main(): """ Main method to install/start/stop/update/remove Axon service. :return: None """ if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(AxonService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(AxonService)
def servicemain(): if len(sys.argv) == 1: try: evtsrc_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(QUANTAXIS_WebService) servicemanager.Initialize('QUANTAXIS_WebService', evtsrc_dll) servicemanager.StartServiceCtrlDispatcher() except win32service.error as details: if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: win32serviceutil.usage() else: win32serviceutil.HandleCommandLine(QUANTAXIS_WebService)
def flush_win_logs(self, lines=None): #print("Flush_win_logs_called") # Flush the current logs to the win event logger #print("Flushing win logs") if lines is None: lines = self.log_messages_win if lines is None: print("NO WIN LOG LINES FOUND!") return False if len(lines) < 1: # Nothing to log? #print("No Lines?!") return True cp_lines = lines.copy() lines.clear() # Build up the output from the logs output = "" for line in cp_lines: l = line["msg"].strip() # Line might be packed together, split it out and then re-combine so it looks # correct in event log new_txt = "" parts = l.split("\n") for p in parts: new_txt += p.strip() + "\r\n" output += new_txt #output += line["msg"].strip() + "\r\n" #print(output) try: #servicemanager.SetEventSourceName("OPE") servicemanager.Initialize( self.service_name, "%programdata%\\ope\\Services\\OPEService\\servicemanager.pyd") except Exception as ex: print("Error setting source name for event logs!") try: # servicemanager.LogMsg( # servicemanager.EVENTLOG_INFORMATION_TYPE, # 0xF000, # generic message # (output, '') # ) servicemanager.LogInfoMsg(output) except Exception as ex: print("Error writing to windows event log!\n" + str(ex)) return True
def parse_command_line(cls): if len(sys.argv) == 1 and \ sys.argv[0].endswith('.exe') and \ not sys.argv[0].endswith(r'win32\PythonService.exe'): servicemanager.Initialize() servicemanager.PrepareToHostSingle(cls) servicemanager.StartServiceCtrlDispatcher() else: if len(sys.argv) == 2 and sys.argv[1] == 'help': sys.argv = sys.argv[:1] win32serviceutil.HandleCommandLine(cls)
def main(): if len(sys.argv) == 1: # service must be starting... # for the sake of debugging etc, we use win32traceutil to see # any unhandled exceptions and print statements. import win32traceutil print "service is starting..." print "(execute this script with '--help' if that isn't what you want)" servicemanager.Initialize() servicemanager.PrepareToHostSingle(NativeTestPipeService) # Now ask the service manager to fire things up for us... servicemanager.StartServiceCtrlDispatcher() print "service done!" else: win32serviceutil.HandleCommandLine(NativeTestPipeService)
def main(): if '--version' in sys.argv: print(version_string()) sys.exit(0) if run_in_foreground(): logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s') log_info('Running in foreground {}'.format(version_string())) ServiceManager().safe_monitor_thread() sys.exit(0) if len(sys.argv) == 1: servicemanager.Initialize('Service Manager', None) servicemanager.PrepareToHostSingle(ServiceManager) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(ServiceManager)
def handle_windowsservice(serviceclass): ''' This function handles a Windows service class. It displays the appropriate command line help, and validaes command line arguements. @param serviceclass: a reference to a overridden WindowsService class. ''' if len(sys.argv) == 1: try: import servicemanager, winerror evtsrc_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(serviceclass) servicemanager.Initialize(serviceclass.__name__, evtsrc_dll) servicemanager.StartServiceCtrlDispatcher() except win32service.error, details: if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: win32serviceutil.usage()
def generic_service_main(cls: Type[WindowsService], name: str) -> None: """ Call this from your command-line entry point to manage a service. - Via inherited functions, enables you to ``install``, ``update``, ``remove``, ``start``, ``stop``, and ``restart`` the service. - Via our additional code, allows you to run the service function directly from the command line in debug mode, using the ``debug`` command. - Run with an invalid command like ``help`` to see help (!). See https://mail.python.org/pipermail/python-win32/2008-April/007299.html Args: cls: class deriving from :class:`WindowsService` name: name of this service """ argc = len(sys.argv) if argc == 1: # noinspection PyUnresolvedReferences try: print("Trying to start service directly...") evtsrc_dll = os.path.abspath(servicemanager.__file__) # noinspection PyUnresolvedReferences servicemanager.PrepareToHostSingle(cls) # <-- sets up the service # noinspection PyUnresolvedReferences servicemanager.Initialize(name, evtsrc_dll) # noinspection PyUnresolvedReferences servicemanager.StartServiceCtrlDispatcher() # noinspection PyUnresolvedReferences except win32service.error as details: print("Failed: {}".format(details)) # print(repr(details.__dict__)) errnum = details.winerror # noinspection PyUnresolvedReferences if errnum == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: # noinspection PyUnresolvedReferences win32serviceutil.usage() elif argc == 2 and sys.argv[1] == 'debug': s = cls() s.run_debug() else: # noinspection PyUnresolvedReferences win32serviceutil.HandleCommandLine(cls)
def SvcDoRun(self): import servicemanager # Add these two lines and the source will be "PyMyService" win32evtlogutil.AddSourceToRegistry(self._svc_name_, servicemanager.__file__) servicemanager.Initialize(self._svc_name_, servicemanager.__file__) # servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, "")) servicemanager.LogInfoMsg("Info") # Event is 255 servicemanager.LogErrorMsg("Error") # Event is 255 servicemanager.LogWarningMsg("Warn") # Event is 255 # or servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, 0xF000, ("Info", )) # Event is 61440 servicemanager.LogMsg(servicemanager.EVENTLOG_ERROR_TYPE, 0xF001, ("Error", )) # Event is 61441 servicemanager.LogMsg(servicemanager.EVENTLOG_WARNING_TYPE, 0xF002, ("Warn", )) # Event is 61442
def main(): # starts in the main python directory. os.chdir(os.path.dirname(sys.executable)) if len(sys.argv) == 1: # service must be starting... # for the sake of debugging etc, we use win32traceutil to see # any unhandled exceptions and print statements. print("supervisor service is starting...") print( "(execute this script with '--help' if that isn't what you want)") servicemanager.Initialize() servicemanager.PrepareToHostSingle(SupervisorService) # Now ask the service manager to fire things up for us... servicemanager.StartServiceCtrlDispatcher() print("supervisor service done!") else: # file configuration supervisord.conf options, args, srv_argv = get_config_args(sys.argv[1:]) # print(args, srv_argv, sep='\n') parser = argparse.ArgumentParser(add_help=False) for opts in options: parser.add_argument(*opts['args'], **opts.get('kwargs', {})) options = parser.parse_args(args=args) if options.config: try: options.config.close() except OSError: pass if options.help: parser.print_help(file=sys.stdout) print() srv_argv.append('-h') elif options.config: with ConfigReg() as reg: reg.set(options.config.name) srv_argv.insert(0, sys.argv[0]) win32serviceutil.HandleCommandLine(SupervisorService, argv=srv_argv)
def generic_service_main(cls, name: str) -> None: # https://mail.python.org/pipermail/python-win32/2008-April/007299.html argc = len(sys.argv) if argc == 1: try: print("Trying to start service directly...") evtsrc_dll = os.path.abspath(servicemanager.__file__) # noinspection PyUnresolvedReferences servicemanager.PrepareToHostSingle(cls) # <-- sets up the service # noinspection PyUnresolvedReferences servicemanager.Initialize(name, evtsrc_dll) # noinspection PyUnresolvedReferences servicemanager.StartServiceCtrlDispatcher() except win32service.error as details: print("Failed: {}".format(details)) # print(repr(details.__dict__)) errnum = details.winerror if errnum == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: win32serviceutil.usage() elif argc == 2 and sys.argv[1] == 'debug': s = cls() s.run_debug() else: win32serviceutil.HandleCommandLine(cls)
LoggerWindowsService._svc_name_ = name if title: LoggerWindowsService._svc_display_name_ = title if description: LoggerWindowsService._svc_description_ = '%s, basedir: %s. Version %s' % ( description, basedir, product_version) win32serviceutil.HandleCommandLine(LoggerWindowsService, customInstallOptions='s:') if __name__ == '__main__': argv = sys.argv if len(argv) == 1 and isStandAlone(argv): servicemanager.Initialize() servicemanager.PrepareToHostSingle(LoggerWindowsService) servicemanager.Initialize(LoggerWindowsService._svc_name_, os.path.abspath(servicemanager.__file__)) servicemanager.StartServiceCtrlDispatcher() elif len(argv) == 1 or argv[1].lower() in ('/h', '/help', '-h', 'help', '--help', '/?'): _pout('--> Rosan Finance Inc.') _pout('--> DB Log System observer Windows service.') _pout('--> ') _pout( '--> Format: service.py [-s <config>] [options] install|update|remove|start [...]|stop|restart [...]|debug [...]' ) _pout('--> ') _pout('--> Parameters:')
fileopen = file("%s\\isjxwqjs" % (homedir_path), "r") for line in fileopen: # pull set-path, this is pulled from interactive shell and written when persistence is called set_path = line.rstrip() # specify filename to execute the SET interactive shell subprocess.Popen('%s' % (set_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) # sleep 30 mins time.sleep(1800) self.ReportServiceStatus(win32service.SERVICE_STOPPED) return if __name__ == '__main__': # f its called with arguments then run if len(sys.argv) == 1: try: evtsrc_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(aservice) servicemanager.Initialize('aservice', evtsrc_dll) servicemanager.StartServiceCtrlDispatcher() except win32service.error, details: if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: win32serviceutil.usage() else: win32serviceutil.HandleCommandLine(aservice)
class RelayKeysService(ServiceFramework): _svc_name_ = "RelayKeysDaemon" _svc_display_name_ = "Relay Keys Daemon" def __init__(self, args): ServiceFramework.__init__(self, args) self.hWaitStop = CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60) def _interrupt(self): rc = WaitForSingleObject(self.hWaitStop, 0) if rc == WAIT_OBJECT_0: raise SystemExit() def SvcStop(self): self.ReportServiceStatus(SERVICE_STOP_PENDING) SetEvent(self.hWaitStop) def SvcDoRun(self): relaykeysd.main(interrupt=self._interrupt) if __name__ == '__main__': # PyInstaller needs this if len(argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(RelayKeysService) servicemanager.StartServiceCtrlDispatcher() else: HandleCommandLine(RelayKeysService)