示例#1
0
    def action_configure(self):
        hSCM = safe_open_scmanager()

        try:
            hSvc = safe_open_service(hSCM, self.resource.service_name)

            self._fix_start_type()

            try:
                win32service.ChangeServiceConfig(
                    hSvc, win32service.SERVICE_NO_CHANGE,
                    self.resource.start_type, win32service.SERVICE_NO_CHANGE,
                    None, None, 0, None, None, None,
                    self.resource.display_name)
                if self.resource.description:
                    try:
                        win32service.ChangeServiceConfig2(
                            hSvc, win32service.SERVICE_CONFIG_DESCRIPTION,
                            self.resource.description)
                    except NotImplementedError:
                        pass  ## ChangeServiceConfig2 and description do not exist on NT
            except win32api.error, details:
                raise Fail("Error configuring service {0}: {1}".format(
                    self.resource.service_name, details.winerror))
            finally:
                win32service.CloseServiceHandle(hSvc)
def ChangeServiceConfig(pythonClassString, serviceName, startType = None, errorControl = None, bRunInteractive = 0,
                        serviceDeps = None, userName = None, password = None,
                        exeName = None, displayName = None, perfMonIni = None, perfMonDll = None,
                        exeArgs = None, description = None, delayedstart = None):
    # Before doing anything, remove any perfmon counters.
    try:
        import perfmon
        perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName)
    except (ImportError, win32api.error):
        pass

    # The EXE location may have changed
    exeName = '"%s"' % LocatePythonServiceExe(exeName)

    # Handle the default arguments.
    if startType is None: startType = win32service.SERVICE_NO_CHANGE
    if errorControl is None: errorControl = win32service.SERVICE_NO_CHANGE

    hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
    serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
    if bRunInteractive:
        serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
    commandLine = _GetCommandLine(exeName, exeArgs)
    try:
        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        try:

            win32service.ChangeServiceConfig(hs,
                serviceType,  # service type
                startType,
                errorControl,       # error control type
                commandLine,
                None,
                0,
                serviceDeps,
                userName,
                password,
                displayName)
            if description is not None:
                try:
                    win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DESCRIPTION,description)
                except NotImplementedError:
                    pass    ## ChangeServiceConfig2 and description do not exist on NT
            if delayedstart is not None:
                try:
                    win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, delayedstart)
                except (win32service.error, NotImplementedError):
                    ## Delayed start only exists on Vista and later.  On Nt, will raise NotImplementedError since ChangeServiceConfig2
                    ## doensn't exist.  On Win2k and XP, will fail with ERROR_INVALID_LEVEL
                    ## Warn only if trying to set delayed to True
                    if delayedstart:
                        warnings.warn('Delayed Start not available on this system')
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
    InstallPythonClassString(pythonClassString, serviceName)
    # If I have performance monitor info to install, do that.
    if perfMonIni is not None:
        InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
    def Update(cls, startupMode="auto", username=None, password=None):
        # Handle the default arguments.
        if startupMode is None:
            startType = win32service.SERVICE_NO_CHANGE
        else:
            startType = cls._get_start_type(startupMode)

        hscm = win32service.OpenSCManager(None, None,
                                          win32service.SC_MANAGER_ALL_ACCESS)
        serviceType = win32service.SERVICE_WIN32_OWN_PROCESS

        commandLine = os.path.abspath(cls._exe_name_)

        try:
            hs = SmartOpenService(hscm, cls._svc_name_,
                                  win32service.SERVICE_ALL_ACCESS)
            try:
                win32service.ChangeServiceConfig(
                    hs,
                    serviceType,  # service type
                    startType,
                    win32service.SERVICE_NO_CHANGE,  # error control type
                    commandLine,
                    None,
                    0,
                    None,
                    username,
                    password,
                    cls._svc_display_name_)
                print "Service updated"
            finally:
                win32service.CloseServiceHandle(hs)
        finally:
            win32service.CloseServiceHandle(hscm)
示例#4
0
    def on_host_init_response(self, message):
        global_variables = message.body.get('global_variables') or []
        for kv in global_variables:
            self._global_variables[kv['name']] = kv['value'].encode(
                'utf-8') if kv['value'] else ''

        if 'chef' in message.body and message.body['chef']:
            if linux.os.windows_family:
                self._chef_client_bin = r'C:\opscode\chef\bin\chef-client.bat'
                self._chef_solo_bin = r'C:\opscode\chef\bin\chef-solo.bat'
            else:
                # Workaround for 'chef' behavior enabled, but chef not installed
                self._chef_client_bin = which('chef-client')
                self._chef_solo_bin = which('chef-solo')

            self._chef_data = message.chef.copy()
            if not self._chef_data.get('node_name'):
                self._chef_data['node_name'] = self.get_node_name()

            self._with_json_attributes = self._chef_data.get(
                'json_attributes', {}) or {}
            if self._with_json_attributes:
                self._with_json_attributes = json.loads(
                    self._with_json_attributes)

            self._run_list = self._chef_data.get('run_list')
            if self._run_list:
                self._with_json_attributes['run_list'] = json.loads(
                    self._run_list)
            elif self._chef_data.get('role'):
                self._with_json_attributes['run_list'] = [
                    "role[%s]" % self._chef_data['role']
                ]

            if linux.os.windows_family:
                # TODO: why not doing the same on linux?
                try:
                    # Set startup type to 'manual' for chef-client service
                    hscm = win32service.OpenSCManager(
                        None, None, win32service.SC_MANAGER_ALL_ACCESS)
                    try:
                        hs = win32serviceutil.SmartOpenService(
                            hscm, WIN_SERVICE_NAME,
                            win32service.SERVICE_ALL_ACCESS)
                        try:
                            snc = win32service.SERVICE_NO_CHANGE
                            # change only startup type
                            win32service.ChangeServiceConfig(
                                hs, snc, win32service.SERVICE_DEMAND_START,
                                snc, None, None, 0, None, None, None, None)
                        finally:
                            win32service.CloseServiceHandle(hs)
                    finally:
                        win32service.CloseServiceHandle(hscm)

                    win32serviceutil.StopService(WIN_SERVICE_NAME)

                except:
                    e = sys.exc_info()[1]
                    self._logger.warning('Could not stop chef service: %s' % e)
示例#5
0
 def enable(self):
     if win32service.QueryServiceConfig(
             self._service_handle)[1] == win32service.SERVICE_DISABLED:
         win32service.ChangeServiceConfig(self._service_handle,
                                          win32service.SERVICE_NO_CHANGE,
                                          win32service.SERVICE_DEMAND_START,
                                          win32service.SERVICE_NO_CHANGE,
                                          None, None, 0, None, None, None,
                                          None)
示例#6
0
 def set_service_credentials(self, service_name, username, password):
     LOG.debug('Setting service credentials: %s', service_name)
     with self._get_service_handle(
             service_name, win32service.SERVICE_CHANGE_CONFIG) as hs:
         win32service.ChangeServiceConfig(hs,
                                          win32service.SERVICE_NO_CHANGE,
                                          win32service.SERVICE_NO_CHANGE,
                                          win32service.SERVICE_NO_CHANGE,
                                          None, None, False, None, username,
                                          password, None)
示例#7
0
 def set_start_type(self, start_type):
     """ Change the startup type of the service. """
     hService = winsvc.OpenService(self.scm_handle, self.ServiceName,
                                   winsvc.SERVICE_CHANGE_CONFIG)
     try:
         winsvc.ChangeServiceConfig(hService, winsvc.SERVICE_NO_CHANGE,
                                    start_type, winsvc.SERVICE_NO_CHANGE,
                                    None, None, False, None, None, None,
                                    None)
     except pywintypes.error, e:
         self.last_error = e.strerror
示例#8
0
	def OnOK(self):
		self.BeginWaitCursor()
		starttype = self.GetCheckedRadioButton(self.IDC_BOOT, self.IDC_DISABLED) - self.IDC_BOOT
		try:
			win32service.ChangeServiceConfig(self.service, win32service.SERVICE_NO_CHANGE, starttype,
				win32service.SERVICE_NO_CHANGE, None, None, 0, None, None, None, None)
		except:
			self.MessageBox('Unable to change startup configuration', None,
				win32con.MB_ICONEXCLAMATION)
		self.EndWaitCursor()
		return dialog.Dialog.OnOK(self)
示例#9
0
def ChangeServiceConfig(pythonClassString, serviceName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, displayName = None, perfMonIni = None, perfMonDll = None, exeArgs = None, description = None):
    # Before doing anything, remove any perfmon counters.
    try:
        import perfmon
        perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName)
    except (ImportError, win32api.error):
        pass

    # The EXE location may have changed
    exeName = '"%s"' % LocatePythonServiceExe(exeName)

    # Handle the default arguments.
    if startType is None: startType = win32service.SERVICE_NO_CHANGE
    if errorControl is None: errorControl = win32service.SERVICE_NO_CHANGE

    hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
    serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
    if bRunInteractive:
        serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
    commandLine = _GetCommandLine(exeName, exeArgs)
    try:
        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        try:

            win32service.ChangeServiceConfig(hs,
                serviceType,  # service type
                startType,
                errorControl,       # error control type
                commandLine,
                None,
                0,
                serviceDeps,
                userName,
                password,
                displayName)
            if description is not None:
                try:
                    win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DESCRIPTION,description)
                except NotImplementedError:
                    pass    ## ChangeServiceConfig2 and description do not exist on NT

        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
    InstallPythonClassString(pythonClassString, serviceName)
    # If I have performance monitor info to install, do that.
    if perfMonIni is not None:
        InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
示例#10
0
 def setstartup(self, startuptype):
     self.startuptype = startuptype.lower()
     if self.startuptype == "boot":
         self.suptype = 0
     elif self.startuptype == "system":
         self.suptype = 1
     elif self.startuptype == "automatic":
         self.suptype = 2
     elif self.startuptype == "manual":
         self.suptype = 3
     elif self.startuptype == "disabled":
         self.suptype = 4
     self.snc = ws.SERVICE_NO_CHANGE
     ws.ChangeServiceConfig(self.handle, self.snc, self.suptype, \
                            self.snc, None, None, 0, None, None, None, self.lserv)
示例#11
0
    def enable(self):
        hSCM = safe_open_scmanager()

        try:
            hSvc = safe_open_service(hSCM, self.resource.service_name)

            if win32service.QueryServiceConfig(
                    hSvc)[1] == win32service.SERVICE_DISABLED:
                win32service.ChangeServiceConfig(
                    hSvc, win32service.SERVICE_NO_CHANGE,
                    win32service.SERVICE_DEMAND_START,
                    win32service.SERVICE_NO_CHANGE, None, None, 0, None, None,
                    None, None)
            win32service.CloseServiceHandle(hSvc)
        except win32api.error, details:
            raise Fail("Error enabling service {0}: {1}".format(
                self.resource.service_name, details.winerror))
示例#12
0
    def action_change_user(self):
        hSCM = safe_open_scmanager()

        try:
            hSvc = safe_open_service(hSCM, self.resource.service_name)

            self._fix_user_name()

            try:
                win32service.ChangeServiceConfig(
                    hSvc, win32service.SERVICE_NO_CHANGE,
                    win32service.SERVICE_NO_CHANGE,
                    win32service.SERVICE_NO_CHANGE, None, None, 0, None,
                    self.resource.username, self.resource.password, None)
            except win32api.error, details:
                raise Fail("Error changing user for service {0}: {1}".format(
                    self.resource.service_name, details.winerror))
            finally:
                win32service.CloseServiceHandle(hSvc)
示例#13
0
 def _SaveExistingService(self, serviceConfigManagerHandle, serviceStartNamePassword=None):
     serviceHandle = None
     try:
         serviceHandle = win32service.OpenService(serviceConfigManagerHandle,
                                                  self.configurations['ServiceName'].StringValue(),
                                                  win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_START)
         win32service.ChangeServiceConfig(serviceHandle,
                                          self.configurations['ServiceType'].Win32Value(),
                                          self.configurations['StartType'].Win32Value(),
                                          self.configurations['ErrorControl'].Win32Value(),
                                          self.configurations['BinaryPathName'].Win32Value(),
                                          self.configurations['LoadOrderGroup'].Win32Value(),
                                          0,
                                          self.configurations['Dependencies'].Win32Value(),
                                          self.configurations['ServiceStartName'].Win32Value(),
                                          serviceStartNamePassword,
                                          self.configurations['DisplayName'].Win32Value())
     finally:
         if serviceHandle:
             win32service.CloseServiceHandle(serviceHandle)
示例#14
0
    def setstartup(self, startuptype):
        sut = startuptype.lower()

        if sut == "boot":
            suptype_id = 0
        elif sut == "system":
            suptype_id = 1
        elif sut == "automatic":
            suptype_id = 2
        elif sut == "manual":
            suptype_id = 3
        elif sut == "disabled":
            suptype_id = 4

        if self.handle is None:
            self._log.info('The %s service does not exist.' % self.userv)
        else:
            ws.ChangeServiceConfig(self.handle, ws.SERVICE_NO_CHANGE,
                                   suptype_id, ws.SERVICE_NO_CHANGE, None,
                                   None, 0, None, None, None, self.lserv)
示例#15
0
    def on_host_init_response(self, message):
        self._global_variables = message.body.get('global_variables') or []
        # global_variables = message.body.get('global_variables') or []
        # for kv in global_variables:
        #     self._global_variables[kv['name']] = kv['value'].encode('utf-8') if kv['value'] else ''

        if 'chef' in message.body and message.body['chef']:
            self._hir_data = message.body.copy()
            self._chef_data = message.chef.copy()
            if not self._chef_data.get('node_name'):
                self._chef_data['node_name'] = self.get_node_name()
            self._chef_data['first_bootstrap'] = True

            self._with_json_attributes = extract_json_attributes(
                self._chef_data)

            if linux.os.windows_family:
                # TODO: why not doing the same on linux?
                try:
                    # Set startup type to 'manual' for chef-client service
                    hscm = win32service.OpenSCManager(
                        None, None, win32service.SC_MANAGER_ALL_ACCESS)
                    try:
                        hs = win32serviceutil.SmartOpenService(
                            hscm, WIN_SERVICE_NAME,
                            win32service.SERVICE_ALL_ACCESS)
                        try:
                            snc = win32service.SERVICE_NO_CHANGE
                            # change only startup type
                            win32service.ChangeServiceConfig(
                                hs, snc, win32service.SERVICE_DEMAND_START,
                                snc, None, None, 0, None, None, None, None)
                        finally:
                            win32service.CloseServiceHandle(hs)
                    finally:
                        win32service.CloseServiceHandle(hscm)

                    win32serviceutil.StopService(WIN_SERVICE_NAME)
                except:
                    e = sys.exc_info()[1]
                    self._logger.warning('Could not stop chef service: %s' % e)
示例#16
0
 def setstartup(self, startuptype):
     self.startuptype = startuptype.lower()
     self.snc = win32service.SERVICE_NO_CHANGE
     win32service.ChangeServiceConfig(self.handle, self.snc, self.suptype,
                                      self.snc, None, None, 0, None, None,
                                      None, self.lserv)
示例#17
0
def modify(
    name,
    bin_path=None,
    exe_args=None,
    display_name=None,
    description=None,
    service_type=None,
    start_type=None,
    start_delayed=None,
    error_control=None,
    load_order_group=None,
    dependencies=None,
    account_name=None,
    account_password=None,
    run_interactive=None,
):
    # pylint: disable=anomalous-backslash-in-string
    """
    Modify a service's parameters. Changes will not be made for parameters that
    are not passed.

    .. versionadded:: 2016.11.0

    Args:
        name (str):
            The name of the service. Can be found using the
            ``service.get_service_name`` function

        bin_path (str):
            The path to the service executable. Backslashes must be escaped, eg:
            ``C:\\path\\to\\binary.exe``

        exe_args (str):
            Any arguments required by the service executable

        display_name (str):
            The name to display in the service manager

        description (str):
            The description to display for the service

        service_type (str):
            Specifies the service type. Default is ``own``. Valid options are as
            follows:

            - kernel: Driver service
            - filesystem: File system driver service
            - adapter: Adapter driver service (reserved)
            - recognizer: Recognizer driver service (reserved)
            - own (default): Service runs in its own process
            - share: Service shares a process with one or more other services

        start_type (str):
            Specifies the service start type. Valid options are as follows:

            - boot: Device driver that is loaded by the boot loader
            - system: Device driver that is started during kernel initialization
            - auto: Service that automatically starts
            - manual: Service must be started manually
            - disabled: Service cannot be started

        start_delayed (bool):
            Set the service to Auto(Delayed Start). Only valid if the start_type
            is set to ``Auto``. If service_type is not passed, but the service
            is already set to ``Auto``, then the flag will be set.

        error_control (str):
            The severity of the error, and action taken, if this service fails
            to start. Valid options are as follows:

            - normal: Error is logged and a message box is displayed
            - severe: Error is logged and computer attempts a restart with the
              last known good configuration
            - critical: Error is logged, computer attempts to restart with the
              last known good configuration, system halts on failure
            - ignore: Error is logged and startup continues, no notification is
              given to the user

        load_order_group (str):
            The name of the load order group to which this service belongs

        dependencies (list):
            A list of services or load ordering groups that must start before
            this service

        account_name (str):
            The name of the account under which the service should run. For
            ``own`` type services this should be in the ``domain\\username``
            format. The following are examples of valid built-in service
            accounts:

            - NT Authority\\LocalService
            - NT Authority\\NetworkService
            - NT Authority\\LocalSystem
            - .\\LocalSystem

        account_password (str):
            The password for the account name specified in ``account_name``. For
            the above built-in accounts, this can be None. Otherwise a password
            must be specified.

        run_interactive (bool):
            If this setting is True, the service will be allowed to interact
            with the user. Not recommended for services that run with elevated
            privileges.

    Returns:
        dict: a dictionary of changes made

    CLI Example:

    .. code-block:: bash

        salt '*' service.modify spooler start_type=disabled

    """
    # pylint: enable=anomalous-backslash-in-string
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx
    handle_scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CONNECT)

    try:
        handle_svc = win32service.OpenService(
            handle_scm,
            name,
            win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG,
        )
    except pywintypes.error as exc:
        raise CommandExecutionError("Failed To Open {}: {}".format(name, exc.strerror))

    config_info = win32service.QueryServiceConfig(handle_svc)

    changes = dict()

    # Input Validation
    if bin_path is not None:
        # shlex.quote the path to the binary
        bin_path = _cmd_quote(bin_path)
        if exe_args is not None:
            bin_path = "{} {}".format(bin_path, exe_args)
        changes["BinaryPath"] = bin_path

    if service_type is not None:
        if service_type.lower() in SERVICE_TYPE:
            service_type = SERVICE_TYPE[service_type.lower()]
            if run_interactive:
                service_type = service_type | win32service.SERVICE_INTERACTIVE_PROCESS
        else:
            raise CommandExecutionError("Invalid Service Type: {}".format(service_type))
    else:
        if run_interactive is True:
            service_type = config_info[0] | win32service.SERVICE_INTERACTIVE_PROCESS
        elif run_interactive is False:
            service_type = config_info[0] ^ win32service.SERVICE_INTERACTIVE_PROCESS
        else:
            service_type = win32service.SERVICE_NO_CHANGE

    if service_type is not win32service.SERVICE_NO_CHANGE:
        flags = list()
        for bit in SERVICE_TYPE:
            if isinstance(bit, int) and service_type & bit:
                flags.append(SERVICE_TYPE[bit])

        changes["ServiceType"] = flags if flags else service_type

    if start_type is not None:
        if start_type.lower() in SERVICE_START_TYPE:
            start_type = SERVICE_START_TYPE[start_type.lower()]
        else:
            raise CommandExecutionError("Invalid Start Type: {}".format(start_type))
        changes["StartType"] = SERVICE_START_TYPE[start_type]
    else:
        start_type = win32service.SERVICE_NO_CHANGE

    if error_control is not None:
        if error_control.lower() in SERVICE_ERROR_CONTROL:
            error_control = SERVICE_ERROR_CONTROL[error_control.lower()]
        else:
            raise CommandExecutionError(
                "Invalid Error Control: {}".format(error_control)
            )
        changes["ErrorControl"] = SERVICE_ERROR_CONTROL[error_control]
    else:
        error_control = win32service.SERVICE_NO_CHANGE

    if account_name is not None:
        changes["ServiceAccount"] = account_name
    if account_name in ["LocalSystem", "LocalService", "NetworkService"]:
        account_password = ""

    if account_password is not None:
        changes["ServiceAccountPassword"] = "******"

    if load_order_group is not None:
        changes["LoadOrderGroup"] = load_order_group

    if dependencies is not None:
        changes["Dependencies"] = dependencies

    if display_name is not None:
        changes["DisplayName"] = display_name

    win32service.ChangeServiceConfig(
        handle_svc,
        service_type,
        start_type,
        error_control,
        bin_path,
        load_order_group,
        0,
        dependencies,
        account_name,
        account_password,
        display_name,
    )

    if description is not None:
        win32service.ChangeServiceConfig2(
            handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description
        )
        changes["Description"] = description

    if start_delayed is not None:
        # You can only set delayed start for services that are set to auto start
        # Start type 2 is Auto
        # Start type -1 is no change
        if (start_type == -1 and config_info[1] == 2) or start_type == 2:
            win32service.ChangeServiceConfig2(
                handle_svc,
                win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO,
                start_delayed,
            )
            changes["StartTypeDelayed"] = start_delayed
        else:
            changes["Warning"] = 'start_delayed: Requires start_type "auto"'

    win32service.CloseServiceHandle(handle_scm)
    win32service.CloseServiceHandle(handle_svc)

    return changes
示例#18
0
 def _set_service_startup_type(self, service, start_type):
     win32service.ChangeServiceConfig(service,
                                      win32service.SERVICE_NO_CHANGE,
                                      start_type,
                                      win32service.SERVICE_NO_CHANGE, None,
                                      None, 0, None, None, None, None)