INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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 the entries are the... | 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 | 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 | 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 | 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: | 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. | 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 the Args dict if the Settings k... | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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:
... |
( 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... |
r Returns information about a specified policy | 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... |
Get a policy value | 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 | 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. | 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 | 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. | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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. | 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. | 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 | 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. | 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 | 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 | 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 | 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 | 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 | 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... |
Set the salt process environment variables. | def setenv(name,
value,
false_unsets=False,
clear_all=False,
update_minion=False,
permanent=False):
'''
Set the salt process environment variables.
name
The environment key to set. Must be a string.
value
Either a string or dict. W... |
Create a znc compatible hashed password | def _makepass(password, hasher='sha256'):
'''
Create a znc compatible hashed password
'''
# Setup the hasher
if hasher == 'sha256':
h = hashlib.sha256(password)
elif hasher == 'md5':
h = hashlib.md5(password)
else:
return NotImplemented
c = "abcdefghijklmnopqrstu... |
Build module using znc - buildmod | def buildmod(*modules):
'''
Build module using znc-buildmod
CLI Example:
.. code-block:: bash
salt '*' znc.buildmod module.cpp [...]
'''
# Check if module files are missing
missing = [module for module in modules if not os.path.exists(module)]
if missing:
return 'Error... |
Return server version from znc -- version | def version():
'''
Return server version from znc --version
CLI Example:
.. code-block:: bash
salt '*' znc.version
'''
cmd = ['znc', '--version']
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
ret = out[0].split(' - ')
return ret[0] |
Return a MSSQL connection. | def _get_conn(ret=None):
'''
Return a MSSQL connection.
'''
_options = _get_options(ret)
dsn = _options.get('dsn')
user = _options.get('user')
passwd = _options.get('passwd')
return pyodbc.connect('DSN={0};UID={1};PWD={2}'.format(
dsn,
user,
passwd)) |
Return data to an odbc server | def returner(ret):
'''
Return data to an odbc server
'''
conn = _get_conn(ret)
cur = conn.cursor()
sql = '''INSERT INTO salt_returns
(fun, jid, retval, id, success, full_ret)
VALUES (?, ?, ?, ?, ?, ?)'''
cur.execute(
sql, (
ret['fun'],
... |
Return the information returned when the specified job id was executed | def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
conn = _get_conn(ret=None)
cur = conn.cursor()
sql = '''SELECT id, full_ret FROM salt_returns WHERE jid = ?'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
... |
Return a dict of the last function called for all minions | def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
conn = _get_conn(ret=None)
cur = conn.cursor()
sql = '''SELECT s.id,s.jid, s.full_ret
FROM salt_returns s
JOIN ( SELECT MAX(jid) AS jid FROM salt_returns GROUP BY fun, id) max
... |
Return a list of all job ids | def get_jids():
'''
Return a list of all job ids
'''
conn = _get_conn(ret=None)
cur = conn.cursor()
sql = '''SELECT distinct jid, load FROM jids'''
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid, s... |
Loads and parses/ usbkey/ config | def _load_config():
'''
Loads and parses /usbkey/config
'''
config = {}
if os.path.isfile('/usbkey/config'):
with salt.utils.files.fopen('/usbkey/config', 'r') as config_file:
for optval in config_file:
optval = salt.utils.stringutils.to_unicode(optval)
... |
writes/ usbkey/ config | def _write_config(config):
'''
writes /usbkey/config
'''
try:
with salt.utils.atomicfile.atomic_open('/usbkey/config', 'w') as config_file:
config_file.write("#\n# This file was generated by salt\n#\n")
for prop in salt.utils.odict.OrderedDict(sorted(config.items())):
... |
Parse vm_present vm config | def _parse_vmconfig(config, instances):
'''
Parse vm_present vm config
'''
vmconfig = None
if isinstance(config, (salt.utils.odict.OrderedDict)):
vmconfig = salt.utils.odict.OrderedDict()
for prop in config:
if prop not in instances:
vmconfig[prop] = conf... |
get modified properties | def _get_instance_changes(current, state):
'''
get modified properties
'''
# get keys
current_keys = set(current.keys())
state_keys = set(state.keys())
# compare configs
changed = salt.utils.data.compare_dicts(current, state)
for change in salt.utils.data.compare_dicts(current, stat... |
Ensure configuration property is set to value in/ usbkey/ config | def config_present(name, value):
'''
Ensure configuration property is set to value in /usbkey/config
name : string
name of property
value : string
value of property
'''
name = name.lower()
ret = {'name': name,
'changes': {},
'result': None,
... |
Ensure configuration property is absent in/ usbkey/ config | def config_absent(name):
'''
Ensure configuration property is absent in /usbkey/config
name : string
name of property
'''
name = name.lower()
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
# load configuration
config = _load... |
Ensure an image source is present on the computenode | def source_present(name, source_type='imgapi'):
'''
Ensure an image source is present on the computenode
name : string
source url
source_type : string
source type (imgapi or docker)
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment... |
Ensure an image source is absent on the computenode | def source_absent(name):
'''
Ensure an image source is absent on the computenode
name : string
source url
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if name not in __salt__['imgadm.sources']():
# source is absent
... |
Ensure image is present on the computenode | def image_present(name):
'''
Ensure image is present on the computenode
name : string
uuid of image
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if _is_docker_uuid(name) and __salt__['imgadm.docker_to_uuid'](name):
# do... |
Ensure image is absent on the computenode | def image_absent(name):
'''
Ensure image is absent on the computenode
name : string
uuid of image
.. note::
computenode.image_absent will only remove the image if it is not used
by a vm.
'''
ret = {'name': name,
'changes': {},
'result': None,
... |
Delete images not in use or installed via image_present | def image_vacuum(name):
'''
Delete images not in use or installed via image_present
.. warning::
Only image_present states that are included via the
top file will be detected.
'''
name = name.lower()
ret = {'name': name,
'changes': {},
'result': None,
... |
Ensure vm is present on the computenode | def vm_present(name, vmconfig, config=None):
'''
Ensure vm is present on the computenode
name : string
hostname of vm
vmconfig : dict
options to set for the vm
config : dict
fine grain control over vm_present
.. note::
The following configuration properties can... |
Ensure vm is absent on the computenode | def vm_absent(name, archive=False):
'''
Ensure vm is absent on the computenode
name : string
hostname of vm
archive : boolean
toggle archiving of vm on removal
.. note::
State ID is used as hostname. Hostnames must be unique.
'''
name = name.lower()
ret = {'na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.