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 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 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 _set_credentials(service_option, new_value, err_msg: str): if not SERVICE_NAME: manager_logger.error(err_msg) return try: win32serviceutil.SetServiceCustomOption(serviceName=SERVICE_NAME, option=service_option, value=new_value) except Exception as e: manager_logger.error(e)
def customOptionHandler(opts): "This is only called when the service is installed." fFoundConfigFile = 0 for opt, val in opts: if opt == "-c": # This installs the location of the Edna configuration file into: # HKLM\SYSTEM\CurrentControlSet\Services\Edna\Parameters\ConfigurationFile win32serviceutil.SetServiceCustomOption(EdnaSvc._svc_name_, "ConfigurationFile", val) fFoundConfigFile = 1 if not fFoundConfigFile: print "Error: You forgot to pass in a path to your Edna configuration file., use the '-c' option." raise ConfigFileNotFound
def customOptionHandler(opts): #This is only called when the service is installed. fFoundConfigFile = 0 for opt, val in opts: if opt == "-c": # This installs the location of the configuration file: win32serviceutil.SetServiceCustomOption( HarmonyService._svc_name_, "LoggingConfiguration", val) fFoundConfigFile = 1 if not fFoundConfigFile: print "Error: You forgot to pass in a path to your logging configuration file., use the '-c' option." raise ConfigFileNotFound
def bind_service(ctx, cmd, arg): from os import environ as env from os import getcwd as pwd from sys import prefix from shutil import which # get servive name name = WinService.name() try: # verify commad if not which(cmd): raise RuntimeError(f'command ({cmd}) not found') # set working directory wu.SetServiceCustomOption(name, 'cwd', pwd()) # get virtual environment wu.SetServiceCustomOption(name, 'env', env.get('VIRTUAL_ENV', prefix)) # set command line wu.SetServiceCustomOption(name, 'cmd', ' '.join([cmd] + list(arg))) # success click.echo(f'BINDED: {name}') except ws.error as ex: raise click.ClickException(ex.strerror) except Exception as ex: raise click.ClickException(ex.strerror)
def HandleCustomOptions(*args, **kwargs): opts = dict(args[0]) if args else {} home = AutoConf.get_home(opts.get('-h', None)) win32serviceutil.SetServiceCustomOption(WardenService._svc_name_, 'WARDEN_HOME', home)
def handle_command_line(argv): options_pattern = "c:v:n:d:p:" optlist, args = getopt.getopt(sys.argv[1:], options_pattern) if not optlist: usage() return if not args: usage() return if len(args) == 1 and args[0] == 'list': print "List of wsgi services (display names) installed: " print listServices() return cmd_cfg_file = None override = {} for opt, val in optlist: if opt == '-c': cmd_cfg_file = val elif opt == '-n': override['svc_name'] = val elif opt == '-d': override['svc_display_name'] = val elif opt == '-v': override['virtual_env'] = os.path.abspath(val) elif opt == '-p': override['http_port'] = val if not cmd_cfg_file: print "Incorrect parameters" usage() return try: ds = ServiceSettings(os.path.abspath(cmd_cfg_file), override) class A(object): pass ds.transferEssential(A) win32serviceutil.HandleCommandLine( A, serviceClassString=getServiceClassString(PasteWinService, argv), argv=argv, customInstallOptions=options_pattern) win32serviceutil.SetServiceCustomOption(ds.getSvcName(), 'wsgi_ini_file', os.path.abspath(cmd_cfg_file)) for key, value in override.items(): win32serviceutil.SetServiceCustomOption(ds.getSvcName(), 'wsgi_' + key, value) if override: win32serviceutil.SetServiceCustomOption(ds.getSvcName(), 'wsgi_override_keys', ' '.join(override.keys())) except SystemExit, e: if e.code == 1: custom_usage()
def _checkConfig(self): # Locate our child process runner (but only when run from source) if not is_frozen: # Running from source python_exe = os.path.join(sys.prefix, "python.exe") if not os.path.isfile(python_exe): # for ppl who build Python itself from source. python_exe = os.path.join(sys.prefix, "PCBuild", "python.exe") if not os.path.isfile(python_exe): # virtualenv support python_exe = os.path.join(sys.prefix, "Scripts", "python.exe") if not os.path.isfile(python_exe): self.error("Can not find python.exe to spawn subprocess") return False me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = me[:-1] self.runner_prefix = '"%s" "%s"' % (python_exe, me) else: # Running from a py2exe built executable - our child process is # us (but with the funky cmdline args!) self.runner_prefix = '"' + sys.executable + '"' # Now our arg processing - this may be better handled by a # twisted/buildbot style config file - but as of time of writing, # MarkH is clueless about such things! # Note that the "arguments" you type into Control Panel for the # service do *not* persist - they apply only when you click "start" # on the service. When started by Windows, args are never presented. # Thus, it is the responsibility of the service to persist any args. # so, when args are presented, we save them as a "custom option". If # they are not presented, we load them from the option. self.dirs = [] if len(self.args) > 1: dir_string = os.pathsep.join(self.args[1:]) save_dirs = True else: dir_string = win32serviceutil.GetServiceCustomOption(self, "directories") save_dirs = False if not dir_string: self.error("You must specify the buildbot directories as " "parameters to the service.\nStopping the service.") return False dirs = dir_string.split(os.pathsep) for d in dirs: d = os.path.abspath(d) sentinal = os.path.join(d, "buildbot.tac") if os.path.isfile(sentinal): self.dirs.append(d) else: msg = "Directory '%s' is not a buildbot dir - ignoring" \ % (d, ) self.warning(msg) if not self.dirs: self.error("No valid buildbot directories were specified.\n" "Stopping the service.") return False if save_dirs: dir_string = os.pathsep.join(self.dirs) win32serviceutil.SetServiceCustomOption(self, "directories", dir_string) return True
def set_config_file(cls, path): win32serviceutil.SetServiceCustomOption(cls._svc_name_, "config", os.path.abspath(path))
import filesvcsender, win32serviceutil argv = r'["-s", "localhost", "-l", "FileSender", "-f", r"F:\xmlBlaster\demo\omniorbpy\filesvcsender.log"]' win32serviceutil.SetServiceCustomOption( filesvcsender.XMLBlasterFileSenderService, "argv", argv)
def setconfig(ip, port, key): win32serviceutil.SetServiceCustomOption('n2txd', 'host', ip) win32serviceutil.SetServiceCustomOption('n2txd', 'port', int(port)) win32serviceutil.SetServiceCustomOption('n2txd', 'key', key)
print('Install OK') win32serviceutil.StartService(SERVICE_NAME) if __name__ == '__main__': is_installed = True SID = win32serviceutil.GetServiceCustomOption(SERVICE_NAME, 'sid') if SID is None: # SID is missing, ask for it from user prompt_string = """ ######################################## Hint: You can paste into this window by right clicking the window header and selecting 'Edit' > 'Paste' ######################################## Please enter your Server ID: """ SID = raw_input(prompt_string) win32serviceutil.SetServiceCustomOption(SERVICE_NAME, 'sid', SID) is_installed = False if len(sys.argv) == 1: if not is_installed: instart() else: servicemanager.Initialize() servicemanager.PrepareToHostSingle(AppServerSvc) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(AppServerSvc)
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========================================================================================= import os import sys import win32serviceutil this_dir_name = os.path.dirname(__file__) app_path = os.path.abspath(os.path.join(this_dir_name, '..')) app_name = os.path.split(app_path)[1] envname = 'ciocenv31' if len(sys.argv) == 2: envname = sys.argv[1] virtualenv = os.path.abspath( os.path.join( os.environ.get('CIOC_ENV_ROOT', os.path.join(app_path, '..', '..')), envname)) win32serviceutil.SetServiceCustomOption("PyCioc" + app_name, 'wsgi_virtual_env', virtualenv)
def handle_command_line(argv): options_pattern = "c:v:n:d:p:" optlist, args = getopt.getopt(sys.argv[1:], options_pattern) if not optlist: usage() return if not args: usage() return if len(args) == 1 and args[0] == "list": print("List of wsgi services (display names) installed: ") print(listServices()) return cmd_cfg_file = None override = {} for opt, val in optlist: if opt == "-c": cmd_cfg_file = val elif opt == "-n": override["svc_name"] = val elif opt == "-d": override["svc_display_name"] = val elif opt == "-v": override["virtual_env"] = os.path.abspath(val) elif opt == "-p": override["http_port"] = val if not cmd_cfg_file: print("Incorrect parameters") usage() return try: ds = ServiceSettings(os.path.abspath(cmd_cfg_file), override) class A: pass ds.transferEssential(A) win32serviceutil.HandleCommandLine( A, serviceClassString=getServiceClassString(PasteWinService, argv), argv=argv, customInstallOptions=options_pattern, ) win32serviceutil.SetServiceCustomOption(ds.getSvcName(), "wsgi_ini_file", os.path.abspath(cmd_cfg_file)) for key, value in override.items(): win32serviceutil.SetServiceCustomOption(ds.getSvcName(), "wsgi_" + key, value) if override: win32serviceutil.SetServiceCustomOption( ds.getSvcName(), "wsgi_override_keys", " ".join(list(override.keys()))) except SystemExit as e: if e.code == 1: custom_usage()