INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Compare software package versions Args: ver1 (str): A software version to compare oper (str): The operand to use to compare ver2 (str): A software version to compare Returns: bool: True if the comparison is valid, otherwise False CLI Example: .. code-block:: bash ...
def compare_versions(ver1='', oper='==', ver2=''): ''' Compare software package versions Args: ver1 (str): A software version to compare oper (str): The operand to use to compare ver2 (str): A software version to compare Returns: bool: True if the comparison is valid, o...
Makes the following changes from the RawConfigParser: 1. Strip leading tabs from non-section-header lines. 2. Treat 8 spaces at the beginning of a line as a tab. 3. Treat lines beginning with a tab as options. 4. Drops support for continuation lines. 5. Multiple values for a giv...
def _read(self, fp, fpname): ''' Makes the following changes from the RawConfigParser: 1. Strip leading tabs from non-section-header lines. 2. Treat 8 spaces at the beginning of a line as a tab. 3. Treat lines beginning with a tab as options. 4. Drops support for continu...
Based on the string-checking code from the SafeConfigParser's set() function, this enforces string values for config options.
def _string_check(self, value, allow_list=False): ''' Based on the string-checking code from the SafeConfigParser's set() function, this enforces string values for config options. ''' if self._optcre is self.OPTCRE or value: is_list = isinstance(value, list) ...
Adds an optional "as_list" argument to ensure a list is returned. This is helpful when iterating over an option which may or may not be a multivar.
def get(self, section, option, as_list=False): ''' Adds an optional "as_list" argument to ensure a list is returned. This is helpful when iterating over an option which may or may not be a multivar. ''' ret = super(GitConfigParser, self).get(section, option) if as...
This is overridden from the RawConfigParser merely to change the default value for the 'value' argument.
def set(self, section, option, value=''): ''' This is overridden from the RawConfigParser merely to change the default value for the 'value' argument. ''' self._string_check(value) super(GitConfigParser, self).set(section, option, value)
This function is unique to the GitConfigParser. It will add another value for the option if it already exists, converting the option's value to a list if applicable. If "value" is a list, then any existing values for the specified section and option will be replaced with the list being ...
def set_multivar(self, section, option, value=''): ''' This function is unique to the GitConfigParser. It will add another value for the option if it already exists, converting the option's value to a list if applicable. If "value" is a list, then any existing values for the spe...
Remove an option with a value matching the expression. Works on single values and multivars.
def remove_option_regexp(self, section, option, expr): ''' Remove an option with a value matching the expression. Works on single values and multivars. ''' if not section or section == self.DEFAULTSECT: sectdict = self._defaults else: try: ...
Makes the following changes from the RawConfigParser: 1. Prepends options with a tab character. 2. Does not write a blank line between sections. 3. When an option's value is a list, a line for each option is written. This allows us to support multivars like a remote's "fetch" option....
def write(self, fp_): ''' Makes the following changes from the RawConfigParser: 1. Prepends options with a tab character. 2. Does not write a blank line between sections. 3. When an option's value is a list, a line for each option is written. This allows us to support...
Read a CSV into Pillar :param str path: Absolute path to a CSV file. :param str idkey: (Optional) The column name of minion IDs. :param str namespace: (Optional) A pillar key to namespace the values under. :param list fieldnames: (Optional) if the first row of the CSV is not column names they m...
def ext_pillar( mid, pillar, path, idkey='id', namespace=None, fieldnames=None, restkey=None, restval=None, dialect='excel'): ''' Read a CSV into Pillar :param str path: Absolute path to a CSV file. :param str idkey: (Optional) The...
Set a value in an OpenStack configuration file. filename The full path to the configuration file section The section in which the parameter will be set parameter The parameter to change value The value to set CLI Example: .. code-block:: bash salt-c...
def set_(filename, section, parameter, value): ''' Set a value in an OpenStack configuration file. filename The full path to the configuration file section The section in which the parameter will be set parameter The parameter to change value The value to set ...
Get a value from an OpenStack configuration file. filename The full path to the configuration file section The section from which to search for the parameter parameter The parameter to return CLI Example: .. code-block:: bash salt-call openstack_config.get /etc/...
def get(filename, section, parameter): ''' Get a value from an OpenStack configuration file. filename The full path to the configuration file section The section from which to search for the parameter parameter The parameter to return CLI Example: .. code-block::...
Ensure an ACE is present
def present(name, objectType, user, permission, acetype, propagation): ''' Ensure an ACE is present ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} tRet = __salt__['win_dacl.check_ace'](name, objectType, user, permission, acetype, propagation, ...
Ensure an object is inheriting ACLs from its parent
def inherit(name, objectType, clear_existing_acl=False): ''' Ensure an object is inheriting ACLs from its parent ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} tRet = __salt__['win_dacl.check_inheritance'](name, objectType) if tRet['result...
Ensure an object is not inheriting ACLs from its parent
def disinherit(name, objectType, copy_inherited_acl=True): ''' Ensure an object is not inheriting ACLs from its parent ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} tRet = __salt__['win_dacl.check_inheritance'](name, objectType) if tRet['...
Update the progress bar
def output(ret, bar, **kwargs): # pylint: disable=unused-argument ''' Update the progress bar ''' if 'return_count' in ret: val = ret['return_count'] # Avoid to fail if targets are behind a syndic. In this case actual return count will be # higher than targeted by MoM itself. ...
Initialize and return a progress bar iter
def progress_iter(progress): ''' Initialize and return a progress bar iter ''' widgets = [progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.Timer(), ' Returns: [', progressbar.Counter(), '/{0}]'.format(progress['minion_count'])] bar = progressbar.ProgressBar(widgets=widgets, maxval=...
Convert a preseed file to an SLS file
def mksls(src, dst=None): ''' Convert a preseed file to an SLS file ''' ps_opts = {} with salt.utils.files.fopen(src, 'r') as fh_: for line in fh_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('#'): continue if not line...
helper function to recursively update the namespaces of an item
def _updateNamespace(item, new_namespace): ''' helper function to recursively update the namespaces of an item ''' temp_item = '' i = item.tag.find('}') if i >= 0: temp_item = item.tag[i+1:] else: temp_item = item.tag item.tag = '{{{0}}}{1}'.format(new_namespace, temp_ite...
helper function to add the reg key to each policies element definitions if the key attribute is not defined to make xpath searching easier for each child in the policy <elements> item
def _updatePolicyElements(policy_item, regkey): ''' helper function to add the reg key to each policies element definitions if the key attribute is not defined to make xpath searching easier for each child in the policy <elements> item ''' for child in policy_item.getiterator(): if 'valu...
attempts to remove the "encoding='unicode'" from an xml file as lxml does not support that on a windows node currently see issue #38100
def _remove_unicode_encoding(xml_file): ''' attempts to remove the "encoding='unicode'" from an xml file as lxml does not support that on a windows node currently see issue #38100 ''' with salt.utils.files.fopen(xml_file, 'rb') as f: xml_content = f.read() modified_xml = re.sub(r' en...
helper function to process all ADMX files in the specified policy_def_path and build a single XML doc that we can search/use for ADMX policy processing
def _load_policy_definitions(path='c:\\Windows\\PolicyDefinitions', language='en-US'): ''' helper function to process all ADMX files in the specified policy_def_path and build a single XML doc that we can search/use for ADMX policy processing ''' # Fallback to the System...
build a namespace map for an ADMX element
def _buildElementNsmap(using_elements): ''' build a namespace map for an ADMX element ''' thisMap = {} for e in using_elements: thisMap[e.attrib['prefix']] = e.attrib['namespace'] return thisMap
Loads audit.csv defaults into a dict in __context__ called 'lgpo.audit_defaults'. The dictionary includes fieldnames and all configurable policies as keys. The values are used to create/modify the ``audit.csv`` file. The first entry is `fieldnames` used to create the header for the csv file. The rest of...
def _get_audit_defaults(option=None): ''' Loads audit.csv defaults into a dict in __context__ called 'lgpo.audit_defaults'. The dictionary includes fieldnames and all configurable policies as keys. The values are used to create/modify the ``audit.csv`` file. The first entry is `fieldnames` used to c...
Get the Advanced Auditing policy as configured in ``C:\\Windows\\Security\\Audit\\audit.csv`` Args: option (str): The name of the setting as it appears in audit.csv Returns: bool: ``True`` if successful, otherwise ``False``
def _findOptionValueAdvAudit(option): ''' Get the Advanced Auditing policy as configured in ``C:\\Windows\\Security\\Audit\\audit.csv`` Args: option (str): The name of the setting as it appears in audit.csv Returns: bool: ``True`` if successful, otherwise ``False`` ''' if '...
Helper function that sets the Advanced Audit settings in the two .csv files on Windows. Those files are located at: C:\\Windows\\Security\\Audit\\audit.csv C:\\Windows\\System32\\GroupPolicy\\Machine\\Microsoft\\Windows NT\\Audit\\audit.csv Args: option (str): The name of the option to set ...
def _set_audit_file_data(option, value): ''' Helper function that sets the Advanced Audit settings in the two .csv files on Windows. Those files are located at: C:\\Windows\\Security\\Audit\\audit.csv C:\\Windows\\System32\\GroupPolicy\\Machine\\Microsoft\\Windows NT\\Audit\\audit.csv Args: ...
Helper function that updates the current applied settings to match what has just been set in the audit.csv files. We're doing it this way instead of running `gpupdate` Args: option (str): The name of the option to set value (str): The value to set. ['None', '0', '1', '2', '3'] Returns:...
def _set_auditpol_data(option, value): ''' Helper function that updates the current applied settings to match what has just been set in the audit.csv files. We're doing it this way instead of running `gpupdate` Args: option (str): The name of the option to set value (str): The value...
Helper function to update the Advanced Audit policy on the machine. This function modifies the two ``audit.csv`` files in the following locations: C:\\Windows\\Security\\Audit\\audit.csv C:\\Windows\\System32\\GroupPolicy\\Machine\\Microsoft\\Windows NT\\Audit\\audit.csv Then it applies those settings...
def _setOptionValueAdvAudit(option, value): ''' Helper function to update the Advanced Audit policy on the machine. This function modifies the two ``audit.csv`` files in the following locations: C:\\Windows\\Security\\Audit\\audit.csv C:\\Windows\\System32\\GroupPolicy\\Machine\\Microsoft\\Windows ...
Helper function that loads secedit data. It runs `secedit /export /cfg <file_name>` which creates a file that contains the secedit data. Returns: str: The contents of the file generated by the secedit command
def _load_secedit_data(): ''' Helper function that loads secedit data. It runs `secedit /export /cfg <file_name>` which creates a file that contains the secedit data. Returns: str: The contents of the file generated by the secedit command ''' try: f_exp = os.path.join(__opts__['...
Helper function that looks for the passed option in the secedit data
def _get_secedit_value(option): ''' Helper function that looks for the passed option in the secedit data ''' secedit_data = _get_secedit_data() for _line in secedit_data: if _line.startswith(option): return _line.split('=')[1].strip() return 'Not Defined'
Helper function to write secedit data to the database
def _write_secedit_data(inf_data): ''' Helper function to write secedit data to the database ''' # Set file names f_sdb = os.path.join(__opts__['cachedir'], 'secedit-{0}.sdb'.format(UUID)) f_inf = os.path.join(__opts__['cachedir'], 'secedit-{0}.inf'.format(UUID)) try: # Write the ch...
helper function to transform the policy value into something that more closely matches how the policy is displayed in the gpedit GUI
def _transform_value(value, policy, transform_type): ''' helper function to transform the policy value into something that more closely matches how the policy is displayed in the gpedit GUI ''' t_kwargs = {} if 'Transform' in policy: if transform_type in policy['Transform']: ...
helper function to validate specified value is appropriate for the policy if the 'Settings' key is a list, the value will check that it is in the list if the 'Settings' key is a dict we will try to execute the function name from the 'Function' key, passing the value and additional arguments from ...
def _validateSetting(value, policy): ''' helper function to validate specified value is appropriate for the policy if the 'Settings' key is a list, the value will check that it is in the list if the 'Settings' key is a dict we will try to execute the function name from the 'Function' key, passin...
helper function to add an account right to a user
def _addAccountRights(sidObject, user_right): ''' helper function to add an account right to a user ''' try: if sidObject: _polHandle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS) user_rights_list = [user_right] _ret = win32security.LsaA...
helper function to remove an account right from a user
def _delAccountRights(sidObject, user_right): ''' helper function to remove an account right from a user ''' try: _polHandle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS) user_rights_list = [user_right] _ret = win32security.LsaRemoveAccountRights(_polHandle...
helper function to return all the user rights assignments/users
def _getRightsAssignments(user_right): ''' helper function to return all the user rights assignments/users ''' sids = [] polHandle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS) sids = win32security.LsaEnumerateAccountsWithUserRight(polHandle, user_right) return sids
helper function to take the 'displayName' attribute of an element and find the value from the ADML data adml_xml_data :: XML data of all ADML files to search display_name :: the value of the displayName attribute from the ADMX entry to search the ADML data for
def _getAdmlDisplayName(adml_xml_data, display_name): ''' helper function to take the 'displayName' attribute of an element and find the value from the ADML data adml_xml_data :: XML data of all ADML files to search display_name :: the value of the displayName attribute from the ADMX entry ...
helper function to check for a presentation label for a policy element
def _getAdmlPresentationRefId(adml_data, ref_id): ''' helper function to check for a presentation label for a policy element ''' search_results = adml_data.xpath('//*[@*[local-name() = "refId"] = "{0}"]'.format(ref_id)) prepended_text = '' if search_results: for result in search_results:...
helper function to retrieve the full policy name if needed
def _getFullPolicyName(policy_item, policy_name, return_full_policy_names, adml_language): ''' helper function to retrieve the full policy name if needed ''' adml_data = _get_policy_resources(language=adml_language) if policy_name ...
helper function to do a search of Policy data from a registry.pol file returns True if the regex search_string is found, otherwise False
def _regexSearchRegPolData(search_string, policy_data): ''' helper function to do a search of Policy data from a registry.pol file returns True if the regex search_string is found, otherwise False ''' if policy_data: if search_string: match = re.search(search_string, policy_data,...
helper function to do a search of Policy data from a registry.pol file returns the "data" field https://msdn.microsoft.com/en-us/library/aa374407(VS.85).aspx [key;value;type;size;data]
def _getDataFromRegPolData(search_string, policy_data, return_value_name=False): ''' helper function to do a search of Policy data from a registry.pol file returns the "data" field https://msdn.microsoft.com/en-us/library/aa374407(VS.85).aspx [key;value;type;size;data] ''' value = None v...
helper function to process an enabled/disabled/true/falseList set if test_items is True, it will determine if the policy is enabled or disabled returning True if all items are configured in the registry.pol file and false if they are not if test_items is False, the expected strings for the items will ...
def _checkListItem(policy_element, policy_name, policy_key, xpath_object, policy_file_data, test_items=True): ''' helper function to process an enabled/disabled/true/falseList set if test_items is True, it will determine if the policy is enabled or disabled returning True if all items are configured in...
helper function to process the parent of a value item object if test_item is True, it will determine if the policy is enabled/disabled returns True if the value is configured in the registry.pol file, otherwise returns False if test_item is False, the expected search string will be returned value type...
def _checkValueItemParent(policy_element, policy_name, policy_key, policy_valueName, xpath_object, policy_file_data, check_deleted=False, test_item=True): ''' helper function to process the parent of a value item object if test_item is True, it will determ...
helper function similar to _processValueItem to build a search string for a known key/value/type/data
def _buildKnownDataSearchString(reg_key, reg_valueName, reg_vtype, reg_data, check_deleted=False): ''' helper function similar to _processValueItem to build a search string for a known key/value/type/data ''' registry = Registry() this_element_value = None exp...
helper function to process a value type item and generate the expected string in the Registry.pol file element - the element to process reg_key - the registry key associated with the element (some inherit from their parent policy) reg_valuename - the registry valueName associated with the...
def _processValueItem(element, reg_key, reg_valuename, policy, parent_element, check_deleted=False, this_element_value=None): ''' helper function to process a value type item and generate the expected string in the Registry.pol file element - the element to process reg_key - t...
rewrite of _getAllAdminTemplateSettingsFromRegPolFile where instead of looking only at the contents of the file, we're going to loop through every policy and look in the registry.pol file to determine if it is enabled/disabled/not configured
def _checkAllAdmxPolicies(policy_class, adml_language='en-US', return_full_policy_names=False, hierarchical_return=False, return_not_configured=False): ''' rewrite of _getAllAdminTemplateSettingsFromRegPolFil...
helper function to build a list containing parent elements of the ADMX policy
def _build_parent_list(policy_definition, return_full_policy_names, adml_language): ''' helper function to build a list containing parent elements of the ADMX policy ''' parent_list = [] policy_namespace = list(policy_definition.nsmap.keys())[0] ...
helper function to recursively walk up the ADMX namespaces and build the hierarchy for the policy
def _admx_policy_parent_walk(path, policy_namespace, parent_category, policy_nsmap, return_full_policy_names, adml_language): ''' helper function to recursively walk u...
helper function to read a reg policy file and return decoded data
def _read_regpol_file(reg_pol_path): ''' helper function to read a reg policy file and return decoded data ''' returndata = None if os.path.exists(reg_pol_path): with salt.utils.files.fopen(reg_pol_path, 'rb') as pol_file: returndata = pol_file.read() return returndata
helper function to do a search of Policy data from a registry.pol file for a policy_regpath and policy_regkey combo
def _regexSearchKeyValueCombo(policy_data, policy_regpath, policy_regkey): ''' helper function to do a search of Policy data from a registry.pol file for a policy_regpath and policy_regkey combo ''' if policy_data: specialValueRegex = salt.utils.stringutils.to_bytes(r'(\*\*Del\.|\*\*DelVals\...
helper function to actually write the data to a Registry.pol file also updates/edits the gpt.ini file to include the ADM policy extensions to let the computer know user and/or machine registry policy files need to be processed data_to_write: data to write into the user/machine registry.pol file po...
def _write_regpol_data(data_to_write, policy_file_path, gpt_ini_path, gpt_extension, gpt_extension_guid): ''' helper function to actually write the data to a Registry.pol file also updates/edits the gpt.ini file to ...
helper function to take a list of strings for registry.pol file data and update existing strings or append the strings
def _policyFileReplaceOrAppendList(string_list, policy_data): ''' helper function to take a list of strings for registry.pol file data and update existing strings or append the strings ''' if not policy_data: policy_data = b'' # we are going to clean off the special pre-fixes, so we get ...
helper function to take a ADMX policy string for registry.pol file data and update existing string or append the string to the data
def _policyFileReplaceOrAppend(this_string, policy_data, append_only=False): ''' helper function to take a ADMX policy string for registry.pol file data and update existing string or append the string to the data ''' # we are going to clean off the special pre-fixes, so we get only the valuename ...
r''' helper function to prep/write adm template data to the Registry.pol file each file begins with REGFILE_SIGNATURE (u'\u5250\u6765') and REGISTRY_FILE_VERSION (u'\x01\00') https://msdn.microsoft.com/en-us/library/aa374407(VS.85).aspx + https://msdn.microsoft.com/en-us/library/cc232696.aspx ...
def _writeAdminTemplateRegPolFile(admtemplate_data, adml_language='en-US', registry_class='Machine'): r''' helper function to prep/write adm template data to the Registry.pol file each file begins with REGFILE_SIGNATURE (u'\u5250\u6765') a...
helper function to parse/read a GPO Startup/Shutdown script file psscript.ini and script.ini file definitions are here https://msdn.microsoft.com/en-us/library/ff842529.aspx https://msdn.microsoft.com/en-us/library/dd303238.aspx
def _getScriptSettingsFromIniFile(policy_info): ''' helper function to parse/read a GPO Startup/Shutdown script file psscript.ini and script.ini file definitions are here https://msdn.microsoft.com/en-us/library/ff842529.aspx https://msdn.microsoft.com/en-us/library/dd303238.aspx ''' ...
helper function to write local GPO startup/shutdown script scripts are stored in scripts.ini and psscripts.ini files in ``WINDIR\\System32\\GroupPolicy\\Machine|User\\Scripts`` these files have the hidden attribute set files have following format: empty line [Startup] 0CmdLine...
def _writeGpoScript(psscript=False): ''' helper function to write local GPO startup/shutdown script scripts are stored in scripts.ini and psscripts.ini files in ``WINDIR\\System32\\GroupPolicy\\Machine|User\\Scripts`` these files have the hidden attribute set files have following format: ...
r''' Returns information about a specified policy Args: policy_name (str): The name of the policy to lookup policy_class (str): The class of policy, i.e. machine, user, both adml_language (str): The ADML language to use for Administrative Template dat...
def get_policy_info(policy_name, policy_class, adml_language='en-US'): r''' Returns information about a specified policy Args: policy_name (str): The name of the policy to lookup policy_class (str): The class of policy, i.e. ma...
(success_flag, policy_xml_item, policy_name_list, message)
def _lookup_admin_template(policy_name, policy_class, adml_language='en-US'): ''' (success_flag, policy_xml_item, policy_name_list, message) ''' policy_aliases = [] admx_policy_definitions = _get_policy_definitions(language=adml_language) adm...
Get a policy value Args: policy_class (str): Some policies are both user and computer, by default all policies will be pulled, but this can be used to retrieve only a specific policy class User/USER/user = retrieve user policies Machine/MACHINE/machine/Compu...
def get(policy_class=None, return_full_policy_names=True, hierarchical_return=False, adml_language='en-US', return_not_configured=False): ''' Get a policy value Args: policy_class (str): Some policies are both user and computer, by default all policies will ...
Set a single computer policy Args: name (str): The name of the policy to configure setting (str): The setting to configure the named policy with cumulative_rights_assignments (bool): Determine how user rights assignment policies are configured. If True,...
def set_computer_policy(name, setting, cumulative_rights_assignments=True, adml_language='en-US'): ''' Set a single computer policy Args: name (str): The name of the policy to configure setting (str): ...
Set a local server policy. Args: computer_policy (dict): A dictionary of "policyname: value" pairs of computer policies to set. 'value' should be how it is displayed in the gpedit GUI, i.e. if a setting can be 'Enabled'/'Disabled', then that should be passed ...
def set_(computer_policy=None, user_policy=None, cumulative_rights_assignments=True, adml_language='en-US'): ''' Set a local server policy. Args: computer_policy (dict): A dictionary of "policyname: value" pairs of computer policies to set. 'value...
converts a number of seconds to days
def _seconds_to_days(cls, val, **kwargs): ''' converts a number of seconds to days ''' zero_value = kwargs.get('zero_value', 0) if val is not None: if val == zero_value: return 0 return val / 86400 else: return 'Not Defi...
converts a number of days to seconds
def _days_to_seconds(cls, val, **kwargs): ''' converts a number of days to seconds ''' zero_value = kwargs.get('zero_value', 0) if val is not None: if val == 0: return zero_value return val * 86400 else: return 'Not Defi...
converts a binary 0/1 to Disabled/Enabled
def _binary_enable_zero_disable_one_conversion(cls, val, **kwargs): ''' converts a binary 0/1 to Disabled/Enabled ''' try: if val is not None: if ord(val) == 0: return 'Disabled' elif ord(val) == 1: retur...
converts Enabled/Disabled to unicode char to write to a REG_BINARY value
def _binary_enable_zero_disable_one_reverse_conversion(cls, val, **kwargs): ''' converts Enabled/Disabled to unicode char to write to a REG_BINARY value ''' if val is not None: if val.upper() == 'DISABLED': return chr(0) elif val.upper() == 'ENABLE...
converts 0/1/2 for dasd reg key
def _dasd_conversion(cls, val, **kwargs): ''' converts 0/1/2 for dasd reg key ''' if val is not None: if val == '0' or val == 0 or val == '': return 'Administrators' elif val == '1' or val == 1: return 'Administrators and Power User...
converts DASD String values to the reg_sz value
def _dasd_reverse_conversion(cls, val, **kwargs): ''' converts DASD String values to the reg_sz value ''' if val is not None: if val.upper() == 'ADMINISTRATORS': # "" also shows 'administrators' in the GUI return '0' elif val.upper(...
checks that a value is in an inclusive range The value for 0 used by Max Password Age is actually 0xffffffff
def _in_range_inclusive(cls, val, **kwargs): ''' checks that a value is in an inclusive range The value for 0 used by Max Password Age is actually 0xffffffff ''' minimum = kwargs.get('min', 0) maximum = kwargs.get('max', 1) zero_value = kwargs.get('zero_value', 0)...
converts the binary value in the registry for driver signing into the correct string representation
def _driver_signing_reg_conversion(cls, val, **kwargs): ''' converts the binary value in the registry for driver signing into the correct string representation ''' log.debug('we have %s for the driver signing value', val) if val is not None: # since this is fr...
converts the string value seen in the GUI to the correct registry value for secedit
def _driver_signing_reg_reverse_conversion(cls, val, **kwargs): ''' converts the string value seen in the GUI to the correct registry value for secedit ''' if val is not None: if val.upper() == 'SILENTLY SUCCEED': return ','.join(['3', '0']) ...
converts a list of pysid objects to string representations
def _sidConversion(cls, val, **kwargs): ''' converts a list of pysid objects to string representations ''' if isinstance(val, six.string_types): val = val.split(',') usernames = [] for _sid in val: try: userSid = win32security.Looku...
converts a list of usernames to sid objects
def _usernamesToSidObjects(cls, val, **kwargs): ''' converts a list of usernames to sid objects ''' if not val: return val if isinstance(val, six.string_types): val = val.split(',') sids = [] for _user in val: try: ...
converts true/false/None to the GUI representation of the powershell startup/shutdown script order
def _powershell_script_order_conversion(cls, val, **kwargs): ''' converts true/false/None to the GUI representation of the powershell startup/shutdown script order ''' log.debug('script order value = %s', val) if val is None or val == 'None': return 'Not Confi...
converts powershell script GUI strings representations to True/False/None
def _powershell_script_order_reverse_conversion(cls, val, **kwargs): ''' converts powershell script GUI strings representations to True/False/None ''' if val.upper() == 'Run Windows PowerShell scripts first'.upper(): return 'true' elif val.upper() == 'Run Wind...
Retrieves the key or value from a dict based on the item kwarg lookup dict to search for item kwarg value_lookup bool to determine if item should be compared to keys or values
def _dict_lookup(cls, item, **kwargs): ''' Retrieves the key or value from a dict based on the item kwarg lookup dict to search for item kwarg value_lookup bool to determine if item should be compared to keys or values ''' log.debug('item == %s', item) val...
kwarg value_lookup bool to determine if item_list should be compared to keys or values kwarg test_zero is used to determine if 0 should be tested when value_lookup is false lookup should be a dict with integers for keys if value_lookup is True, item is expected to be a list ...
def _dict_lookup_bitwise_add(cls, item, **kwargs): ''' kwarg value_lookup bool to determine if item_list should be compared to keys or values kwarg test_zero is used to determine if 0 should be tested when value_lookup is false lookup should be a dict with integers for keys ...
transform for a REG_MULTI_SZ to properly handle "Not Defined"
def _multi_string_put_transform(cls, item, **kwargs): ''' transform for a REG_MULTI_SZ to properly handle "Not Defined" ''' if isinstance(item, list): return item elif isinstance(item, six.string_types): if item.lower() == 'not defined': re...
transfrom for a REG_SZ to properly handle "Not Defined"
def _string_put_transform(cls, item, **kwargs): ''' transfrom for a REG_SZ to properly handle "Not Defined" ''' if isinstance(item, six.string_types): if item.lower() == 'not defined': return None else: return item
Returns snapshot data from a D-Bus response. A snapshot D-Bus response is a dbus.Struct containing the information related to a snapshot: [id, type, pre_snapshot, timestamp, user, description, cleanup_algorithm, userdata] id: dbus.UInt32 type: dbus.UInt16 pre_snapshot: dbus.UInt32 ti...
def _snapshot_to_data(snapshot): ''' Returns snapshot data from a D-Bus response. A snapshot D-Bus response is a dbus.Struct containing the information related to a snapshot: [id, type, pre_snapshot, timestamp, user, description, cleanup_algorithm, userdata] id: dbus.UInt32 type: dbu...
Returns a error message from a snapper DBusException
def _dbus_exception_to_reason(exc, args): ''' Returns a error message from a snapper DBusException ''' error = exc.get_dbus_name() if error == 'error.unknown_config': return "Unknown configuration '{0}'".format(args['config']) elif error == 'error.illegal_snapshot': return 'Inval...
List available snapshots CLI example: .. code-block:: bash salt '*' snapper.list_snapshots config=myconfig
def list_snapshots(config='root'): ''' List available snapshots CLI example: .. code-block:: bash salt '*' snapper.list_snapshots config=myconfig ''' try: snapshots = snapper.ListSnapshots(config) return [_snapshot_to_data(s) for s in snapshots] except dbus.DBusExc...
Get detailed information about a given snapshot CLI example: .. code-block:: bash salt '*' snapper.get_snapshot 1
def get_snapshot(number=0, config='root'): ''' Get detailed information about a given snapshot CLI example: .. code-block:: bash salt '*' snapper.get_snapshot 1 ''' try: snapshot = snapper.GetSnapshot(config, int(number)) return _snapshot_to_data(snapshot) except d...
List all available configs CLI example: .. code-block:: bash salt '*' snapper.list_configs
def list_configs(): ''' List all available configs CLI example: .. code-block:: bash salt '*' snapper.list_configs ''' try: configs = snapper.ListConfigs() return dict((config[0], config[2]) for config in configs) except dbus.DBusException as exc: raise Com...
Set configuration values CLI example: .. code-block:: bash salt '*' snapper.set_config SYNC_ACL=True Keys are case insensitive as they will be always uppercased to snapper convention. The above example is equivalent to: .. code-block:: bash salt '*' snapper.set_config sync_acl=...
def set_config(name='root', **kwargs): ''' Set configuration values CLI example: .. code-block:: bash salt '*' snapper.set_config SYNC_ACL=True Keys are case insensitive as they will be always uppercased to snapper convention. The above example is equivalent to: .. code-block:: ...
Returns the last existing created snapshot
def _get_last_snapshot(config='root'): ''' Returns the last existing created snapshot ''' snapshot_list = sorted(list_snapshots(config), key=lambda x: x['id']) return snapshot_list[-1]
Converts a numeric dbus snapper status into a string CLI Example: .. code-block:: bash salt '*' snapper.status_to_string <dbus_status>
def status_to_string(dbus_status): ''' Converts a numeric dbus snapper status into a string CLI Example: .. code-block:: bash salt '*' snapper.status_to_string <dbus_status> ''' status_tuple = ( dbus_status & 0b000000001, dbus_status & 0b000000010, dbus_status & 0b000000100, ...
Retrieves all values from a given configuration CLI example: .. code-block:: bash salt '*' snapper.get_config
def get_config(name='root'): ''' Retrieves all values from a given configuration CLI example: .. code-block:: bash salt '*' snapper.get_config ''' try: config = snapper.GetConfig(name) return config except dbus.DBusException as exc: raise CommandExecutionErro...
Creates a new Snapper configuration name Name of the new Snapper configuration. subvolume Path to the related subvolume. fstype Filesystem type of the subvolume. template Configuration template to use. (Default: default) extra_opts Extra Snapper configuration...
def create_config(name=None, subvolume=None, fstype=None, template=None, extra_opts=None): ''' Creates a new Snapper configuration name Name of the new Snapper configuration. subvolume Path to the related subvolume....
Creates an snapshot config Configuration name. snapshot_type Specifies the type of the new snapshot. Possible values are single, pre and post. pre_number For post snapshots the number of the pre snapshot must be provided. description Description for the s...
def create_snapshot(config='root', snapshot_type='single', pre_number=None, description=None, cleanup_algorithm='number', userdata=None, **kwargs): ''' Creates an snapshot config Configuration name. snapshot_type Specifies the type of the new snap...
Deletes an snapshot config Configuration name. (Default: root) snapshots_ids List of the snapshots IDs to be deleted. CLI example: .. code-block:: bash salt '*' snapper.delete_snapshot 54 salt '*' snapper.delete_snapshot config=root 54 salt '*' snapper.delete...
def delete_snapshot(snapshots_ids=None, config="root"): ''' Deletes an snapshot config Configuration name. (Default: root) snapshots_ids List of the snapshots IDs to be deleted. CLI example: .. code-block:: bash salt '*' snapper.delete_snapshot 54 salt '*' sn...
Modify attributes of an existing snapshot. config Configuration name. (Default: root) snapshot_id ID of the snapshot to be modified. cleanup Change the cleanup method of the snapshot. (str) description Change the description of the snapshot. (str) userdata ...
def modify_snapshot(snapshot_id=None, description=None, userdata=None, cleanup=None, config="root"): ''' Modify attributes of an existing snapshot. config Configuration name. (Default: root) snapshot_id ID ...
Returns numerical interval based on optionals num_pre, num_post values
def _get_num_interval(config, num_pre, num_post): ''' Returns numerical interval based on optionals num_pre, num_post values ''' post = int(num_post) if num_post else 0 pre = int(num_pre) if num_pre is not None else _get_last_snapshot(config)['id'] return pre, post
Checks if a file is a text file
def _is_text_file(filename): ''' Checks if a file is a text file ''' type_of_file = os.popen('file -bi {0}'.format(filename), 'r').read() return type_of_file.startswith('text')
Runs a function from an execution module creating pre and post snapshots and associating the salt job id with those snapshots for easy undo and cleanup. function Salt function to call. config Configuration name. (default: "root") description A description for the snapshots...
def run(function, *args, **kwargs): ''' Runs a function from an execution module creating pre and post snapshots and associating the salt job id with those snapshots for easy undo and cleanup. function Salt function to call. config Configuration name. (default: "root") des...
Returns a comparison between two snapshots config Configuration name. num_pre first snapshot ID to compare. Default is last snapshot num_post last snapshot ID to compare. Default is 0 (current state) CLI example: .. code-block:: bash salt '*' snapper.status ...
def status(config='root', num_pre=None, num_post=None): ''' Returns a comparison between two snapshots config Configuration name. num_pre first snapshot ID to compare. Default is last snapshot num_post last snapshot ID to compare. Default is 0 (current state) CLI exam...
Undo all file changes that happened between num_pre and num_post, leaving the files into the state of num_pre. .. warning:: If one of the files has changes after num_post, they will be overwritten The snapshots are used to determine the file list, but the current version of the files wi...
def undo(config='root', files=None, num_pre=None, num_post=None): ''' Undo all file changes that happened between num_pre and num_post, leaving the files into the state of num_pre. .. warning:: If one of the files has changes after num_post, they will be overwritten The snapshots are us...
Returns pre/post snapshots made by a given Salt jid Looks for 'salt_jid' entries into snapshots userdata which are created when 'snapper.run' is executed.
def _get_jid_snapshots(jid, config='root'): ''' Returns pre/post snapshots made by a given Salt jid Looks for 'salt_jid' entries into snapshots userdata which are created when 'snapper.run' is executed. ''' jid_snapshots = [x for x in list_snapshots(config) if x['userdata'].get("salt_jid") == j...
Undo the changes applied by a salt job jid The job id to lookup config Configuration name. CLI Example: .. code-block:: bash salt '*' snapper.undo_jid jid=20160607130930720112
def undo_jid(jid, config='root'): ''' Undo the changes applied by a salt job jid The job id to lookup config Configuration name. CLI Example: .. code-block:: bash salt '*' snapper.undo_jid jid=20160607130930720112 ''' pre_snapshot, post_snapshot = _get_jid_sn...
Returns the differences between two snapshots config Configuration name. filename if not provided the showing differences between snapshots for all "text" files num_pre first snapshot ID to compare. Default is last snapshot num_post last snapshot ID to compare...
def diff(config='root', filename=None, num_pre=None, num_post=None): ''' Returns the differences between two snapshots config Configuration name. filename if not provided the showing differences between snapshots for all "text" files num_pre first snapshot ID to co...
Returns the changes applied by a `jid` jid The job id to lookup config Configuration name. CLI Example: .. code-block:: bash salt '*' snapper.diff_jid jid=20160607130930720112
def diff_jid(jid, config='root'): ''' Returns the changes applied by a `jid` jid The job id to lookup config Configuration name. CLI Example: .. code-block:: bash salt '*' snapper.diff_jid jid=20160607130930720112 ''' pre_snapshot, post_snapshot = _get_jid_sn...
Creates a snapshot marked as baseline tag Tag name for the baseline config Configuration name. CLI Example: .. code-block:: bash salt '*' snapper.create_baseline salt '*' snapper.create_baseline my_custom_baseline
def create_baseline(tag="baseline", config='root'): ''' Creates a snapshot marked as baseline tag Tag name for the baseline config Configuration name. CLI Example: .. code-block:: bash salt '*' snapper.create_baseline salt '*' snapper.create_baseline my_custo...