Exemplo n.º 1
0
def manage_service(service, args):
    if len(args) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(service)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(service)
Exemplo n.º 2
0
def run() -> None:
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(UDSActorSvc)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(UDSActorSvc)
Exemplo n.º 3
0
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)
Exemplo n.º 5
0
def start_service():
    with log_context({'instance', 'opsiclientd'}):
        logger.essential("opsiclientd service start")
        #logger.debug(os.environ)
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(OpsiclientdService)
        servicemanager.StartServiceCtrlDispatcher()
Exemplo n.º 6
0
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()
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
 def runService(self):
     if len(sys.argv) == 1:
         servicemanager.Initialize()
         servicemanager.PrepareToHostSingle(PyService)
         servicemanager.StartServiceCtrlDispatcher()
     else:
         win32serviceutil.HandleCommandLine(PyService)
     pass
Exemplo n.º 11
0
def main():

    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(SMTPuttService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        SMTPuttService.handle_cmd()
Exemplo n.º 12
0
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)
Exemplo n.º 13
0
Arquivo: namsd.py Projeto: openxzx/fms
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)
Exemplo n.º 14
0
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()
Exemplo n.º 15
0
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)
Exemplo n.º 16
0
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)
Exemplo n.º 17
0
    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)
Exemplo n.º 18
0
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)
Exemplo n.º 19
0
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)
Exemplo n.º 20
0
 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()
Exemplo n.º 21
0
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)
Exemplo n.º 22
0
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)
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
        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:')
        _pout('--> ')
        _pout('-->   <config>              :')
        _pout(
            '-->         Name of the script config-file from current directory, by default: `logger.config`,'
Exemplo n.º 25
0
        sm.LogMsg(sm.EVENTLOG_INFORMATION_TYPE, event_id,
                  (self._svc_name_, ''))


if __name__ == '__main__':
    as_service, log = handle_launch('main')
    log.info(f'sys.argv={argv}')

    if len(argv) == 1:

        if as_service:
            log.info('Initialization win-service...')

            sm.Initialize()
            sm.PrepareToHostSingle(OneCSentryService)
            sm.StartServiceCtrlDispatcher()

        else:
            log.debug('Start API debug...')

            onec_sentry = app.OneCSentry()
            onec_sentry.watch()

    else:
        log.info('Command line processing...')

        if 'debug' in argv:
            config = Config()
            log.info('Add args in "argv": ' f'{CONFIG_KEY}, {config.file}')
            argv.append(CONFIG_KEY)
            argv.append(config.file)
Exemplo n.º 26
0
 def start(cls):
     servicemanager.Initialize()
     servicemanager.PrepareToHostSingle(cls)
     servicemanager.StartServiceCtrlDispatcher()
Exemplo n.º 27
0
# -*- coding:utf-8 -*-
import win32serviceutil
import win32service
import win32event
import sys
import os
#设置编码
reload(sys)
sys.setdefaultencoding('utf-8')

#windows服务中显示的名字
class zlsService(win32serviceutil.ServiceFramework):
    _svc_name_ = 'web_movie'  ###可以根据自己喜好修改
    _svc_display_name_ = 'web_movie'  ###可以根据自己喜好修改
    _svc_description_ = 'web_movie'  ###可以根据自己喜好修改
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.stop_event = win32event.CreateEvent(None, 0, 0, None)
        self.run = True
    def SvcDoRun(self):
        from web_movie import app
        while True:
            try:
                app.run()
            except:
                pass
    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stop_event)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)