repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/states/docker_volume.py | absent | def absent(name, driver=None):
'''
Ensure that a volume is absent.
.. versionadded:: 2015.8.4
.. versionchanged:: 2017.7.0
This state was renamed from **docker.volume_absent** to **docker_volume.absent**
name
Name of the volume
Usage Examples:
.. code-block:: yaml
volume_foo:
docker_volume.absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
volume = _find_volume(name)
if not volume:
ret['result'] = True
ret['comment'] = 'Volume \'{0}\' already absent'.format(name)
return ret
try:
ret['changes']['removed'] = __salt__['docker.remove_volume'](name)
ret['result'] = True
except Exception as exc:
ret['comment'] = ('Failed to remove volume \'{0}\': {1}'
.format(name, exc))
return ret | python | def absent(name, driver=None):
'''
Ensure that a volume is absent.
.. versionadded:: 2015.8.4
.. versionchanged:: 2017.7.0
This state was renamed from **docker.volume_absent** to **docker_volume.absent**
name
Name of the volume
Usage Examples:
.. code-block:: yaml
volume_foo:
docker_volume.absent
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
volume = _find_volume(name)
if not volume:
ret['result'] = True
ret['comment'] = 'Volume \'{0}\' already absent'.format(name)
return ret
try:
ret['changes']['removed'] = __salt__['docker.remove_volume'](name)
ret['result'] = True
except Exception as exc:
ret['comment'] = ('Failed to remove volume \'{0}\': {1}'
.format(name, exc))
return ret | [
"def",
"absent",
"(",
"name",
",",
"driver",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"volume",
"=",
"_find_volume",
"(",
"name"... | Ensure that a volume is absent.
.. versionadded:: 2015.8.4
.. versionchanged:: 2017.7.0
This state was renamed from **docker.volume_absent** to **docker_volume.absent**
name
Name of the volume
Usage Examples:
.. code-block:: yaml
volume_foo:
docker_volume.absent | [
"Ensure",
"that",
"a",
"volume",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_volume.py#L195-L231 | train |
saltstack/salt | salt/modules/defaults.py | _load | def _load(formula):
'''
Generates a list of salt://<formula>/defaults.(json|yaml) files
and fetches them from the Salt master.
Returns first defaults file as python dict.
'''
# Compute possibilities
_mk_client()
paths = []
for ext in ('yaml', 'json'):
source_url = salt.utils.url.create(formula + '/defaults.' + ext)
paths.append(source_url)
# Fetch files from master
defaults_files = __context__['cp.fileclient'].cache_files(paths)
for file_ in defaults_files:
if not file_:
# Skip empty string returned by cp.fileclient.cache_files.
continue
suffix = file_.rsplit('.', 1)[-1]
if suffix == 'yaml':
loader = salt.utils.yaml.safe_load
elif suffix == 'json':
loader = salt.utils.json.load
else:
log.debug("Failed to determine loader for %r", file_)
continue
if os.path.exists(file_):
log.debug("Reading defaults from %r", file_)
with salt.utils.files.fopen(file_) as fhr:
defaults = loader(fhr)
log.debug("Read defaults %r", defaults)
return defaults or {} | python | def _load(formula):
'''
Generates a list of salt://<formula>/defaults.(json|yaml) files
and fetches them from the Salt master.
Returns first defaults file as python dict.
'''
# Compute possibilities
_mk_client()
paths = []
for ext in ('yaml', 'json'):
source_url = salt.utils.url.create(formula + '/defaults.' + ext)
paths.append(source_url)
# Fetch files from master
defaults_files = __context__['cp.fileclient'].cache_files(paths)
for file_ in defaults_files:
if not file_:
# Skip empty string returned by cp.fileclient.cache_files.
continue
suffix = file_.rsplit('.', 1)[-1]
if suffix == 'yaml':
loader = salt.utils.yaml.safe_load
elif suffix == 'json':
loader = salt.utils.json.load
else:
log.debug("Failed to determine loader for %r", file_)
continue
if os.path.exists(file_):
log.debug("Reading defaults from %r", file_)
with salt.utils.files.fopen(file_) as fhr:
defaults = loader(fhr)
log.debug("Read defaults %r", defaults)
return defaults or {} | [
"def",
"_load",
"(",
"formula",
")",
":",
"# Compute possibilities",
"_mk_client",
"(",
")",
"paths",
"=",
"[",
"]",
"for",
"ext",
"in",
"(",
"'yaml'",
",",
"'json'",
")",
":",
"source_url",
"=",
"salt",
".",
"utils",
".",
"url",
".",
"create",
"(",
... | Generates a list of salt://<formula>/defaults.(json|yaml) files
and fetches them from the Salt master.
Returns first defaults file as python dict. | [
"Generates",
"a",
"list",
"of",
"salt",
":",
"//",
"<formula",
">",
"/",
"defaults",
".",
"(",
"json|yaml",
")",
"files",
"and",
"fetches",
"them",
"from",
"the",
"Salt",
"master",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/defaults.py#L34-L71 | train |
saltstack/salt | salt/modules/defaults.py | get | def get(key, default=''):
'''
defaults.get is used much like pillar.get except that it will read
a default value for a pillar from defaults.json or defaults.yaml
files that are stored in the root of a salt formula.
CLI Example:
.. code-block:: bash
salt '*' defaults.get core:users:root
The defaults is computed from pillar key. The first entry is considered as
the formula namespace.
For example, querying ``core:users:root`` will try to load
``salt://core/defaults.yaml`` and ``salt://core/defaults.json``.
'''
# Determine formula namespace from query
if ':' in key:
namespace, key = key.split(':', 1)
else:
namespace, key = key, None
# Fetch and load defaults formula files from states.
defaults = _load(namespace)
# Fetch value
if key:
return salt.utils.data.traverse_dict_and_list(defaults, key, default)
else:
return defaults | python | def get(key, default=''):
'''
defaults.get is used much like pillar.get except that it will read
a default value for a pillar from defaults.json or defaults.yaml
files that are stored in the root of a salt formula.
CLI Example:
.. code-block:: bash
salt '*' defaults.get core:users:root
The defaults is computed from pillar key. The first entry is considered as
the formula namespace.
For example, querying ``core:users:root`` will try to load
``salt://core/defaults.yaml`` and ``salt://core/defaults.json``.
'''
# Determine formula namespace from query
if ':' in key:
namespace, key = key.split(':', 1)
else:
namespace, key = key, None
# Fetch and load defaults formula files from states.
defaults = _load(namespace)
# Fetch value
if key:
return salt.utils.data.traverse_dict_and_list(defaults, key, default)
else:
return defaults | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"''",
")",
":",
"# Determine formula namespace from query",
"if",
"':'",
"in",
"key",
":",
"namespace",
",",
"key",
"=",
"key",
".",
"split",
"(",
"':'",
",",
"1",
")",
"else",
":",
"namespace",
",",
"key"... | defaults.get is used much like pillar.get except that it will read
a default value for a pillar from defaults.json or defaults.yaml
files that are stored in the root of a salt formula.
CLI Example:
.. code-block:: bash
salt '*' defaults.get core:users:root
The defaults is computed from pillar key. The first entry is considered as
the formula namespace.
For example, querying ``core:users:root`` will try to load
``salt://core/defaults.yaml`` and ``salt://core/defaults.json``. | [
"defaults",
".",
"get",
"is",
"used",
"much",
"like",
"pillar",
".",
"get",
"except",
"that",
"it",
"will",
"read",
"a",
"default",
"value",
"for",
"a",
"pillar",
"from",
"defaults",
".",
"json",
"or",
"defaults",
".",
"yaml",
"files",
"that",
"are",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/defaults.py#L74-L106 | train |
saltstack/salt | salt/modules/defaults.py | merge | def merge(dest, src, merge_lists=False, in_place=True):
'''
defaults.merge
Allows deep merging of dicts in formulas.
merge_lists : False
If True, it will also merge lists instead of replace their items.
in_place : True
If True, it will merge into dest dict,
if not it will make a new copy from that dict and return it.
CLI Example:
.. code-block:: bash
salt '*' default.merge a=b d=e
It is more typical to use this in a templating language in formulas,
instead of directly on the command-line.
'''
if in_place:
merged = dest
else:
merged = copy.deepcopy(dest)
return dictupdate.update(merged, src, merge_lists=merge_lists) | python | def merge(dest, src, merge_lists=False, in_place=True):
'''
defaults.merge
Allows deep merging of dicts in formulas.
merge_lists : False
If True, it will also merge lists instead of replace their items.
in_place : True
If True, it will merge into dest dict,
if not it will make a new copy from that dict and return it.
CLI Example:
.. code-block:: bash
salt '*' default.merge a=b d=e
It is more typical to use this in a templating language in formulas,
instead of directly on the command-line.
'''
if in_place:
merged = dest
else:
merged = copy.deepcopy(dest)
return dictupdate.update(merged, src, merge_lists=merge_lists) | [
"def",
"merge",
"(",
"dest",
",",
"src",
",",
"merge_lists",
"=",
"False",
",",
"in_place",
"=",
"True",
")",
":",
"if",
"in_place",
":",
"merged",
"=",
"dest",
"else",
":",
"merged",
"=",
"copy",
".",
"deepcopy",
"(",
"dest",
")",
"return",
"dictupd... | defaults.merge
Allows deep merging of dicts in formulas.
merge_lists : False
If True, it will also merge lists instead of replace their items.
in_place : True
If True, it will merge into dest dict,
if not it will make a new copy from that dict and return it.
CLI Example:
.. code-block:: bash
salt '*' default.merge a=b d=e
It is more typical to use this in a templating language in formulas,
instead of directly on the command-line. | [
"defaults",
".",
"merge",
"Allows",
"deep",
"merging",
"of",
"dicts",
"in",
"formulas",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/defaults.py#L109-L133 | train |
saltstack/salt | salt/modules/defaults.py | update | def update(dest, defaults, merge_lists=True, in_place=True):
'''
defaults.update
Allows to set defaults for group of data set e.g. group for nodes.
This function is a combination of defaults.merge
and defaults.deepcopy to avoid redundant in jinja.
Example:
.. code-block:: yaml
group01:
defaults:
enabled: True
extra:
- test
- stage
nodes:
host01:
index: foo
upstream: bar
host02:
index: foo2
upstream: bar2
.. code-block:: jinja
{% do salt['defaults.update'](group01.nodes, group01.defaults) %}
Each node will look like the following:
.. code-block:: yaml
host01:
enabled: True
index: foo
upstream: bar
extra:
- test
- stage
merge_lists : True
If True, it will also merge lists instead of replace their items.
in_place : True
If True, it will merge into dest dict.
if not it will make a new copy from that dict and return it.
It is more typical to use this in a templating language in formulas,
instead of directly on the command-line.
'''
if in_place:
nodes = dest
else:
nodes = deepcopy(dest)
for node_name, node_vars in nodes.items():
defaults_vars = deepcopy(defaults)
node_vars = merge(defaults_vars, node_vars, merge_lists=merge_lists)
nodes[node_name] = node_vars
return nodes | python | def update(dest, defaults, merge_lists=True, in_place=True):
'''
defaults.update
Allows to set defaults for group of data set e.g. group for nodes.
This function is a combination of defaults.merge
and defaults.deepcopy to avoid redundant in jinja.
Example:
.. code-block:: yaml
group01:
defaults:
enabled: True
extra:
- test
- stage
nodes:
host01:
index: foo
upstream: bar
host02:
index: foo2
upstream: bar2
.. code-block:: jinja
{% do salt['defaults.update'](group01.nodes, group01.defaults) %}
Each node will look like the following:
.. code-block:: yaml
host01:
enabled: True
index: foo
upstream: bar
extra:
- test
- stage
merge_lists : True
If True, it will also merge lists instead of replace their items.
in_place : True
If True, it will merge into dest dict.
if not it will make a new copy from that dict and return it.
It is more typical to use this in a templating language in formulas,
instead of directly on the command-line.
'''
if in_place:
nodes = dest
else:
nodes = deepcopy(dest)
for node_name, node_vars in nodes.items():
defaults_vars = deepcopy(defaults)
node_vars = merge(defaults_vars, node_vars, merge_lists=merge_lists)
nodes[node_name] = node_vars
return nodes | [
"def",
"update",
"(",
"dest",
",",
"defaults",
",",
"merge_lists",
"=",
"True",
",",
"in_place",
"=",
"True",
")",
":",
"if",
"in_place",
":",
"nodes",
"=",
"dest",
"else",
":",
"nodes",
"=",
"deepcopy",
"(",
"dest",
")",
"for",
"node_name",
",",
"no... | defaults.update
Allows to set defaults for group of data set e.g. group for nodes.
This function is a combination of defaults.merge
and defaults.deepcopy to avoid redundant in jinja.
Example:
.. code-block:: yaml
group01:
defaults:
enabled: True
extra:
- test
- stage
nodes:
host01:
index: foo
upstream: bar
host02:
index: foo2
upstream: bar2
.. code-block:: jinja
{% do salt['defaults.update'](group01.nodes, group01.defaults) %}
Each node will look like the following:
.. code-block:: yaml
host01:
enabled: True
index: foo
upstream: bar
extra:
- test
- stage
merge_lists : True
If True, it will also merge lists instead of replace their items.
in_place : True
If True, it will merge into dest dict.
if not it will make a new copy from that dict and return it.
It is more typical to use this in a templating language in formulas,
instead of directly on the command-line. | [
"defaults",
".",
"update",
"Allows",
"to",
"set",
"defaults",
"for",
"group",
"of",
"data",
"set",
"e",
".",
"g",
".",
"group",
"for",
"nodes",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/defaults.py#L150-L213 | train |
saltstack/salt | salt/modules/win_task.py | _get_date_time_format | def _get_date_time_format(dt_string):
'''
Copied from win_system.py (_get_date_time_format)
Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
'''
valid_formats = [
'%I:%M:%S %p',
'%I:%M %p',
'%H:%M:%S',
'%H:%M',
'%Y-%m-%d',
'%m-%d-%y',
'%m-%d-%Y',
'%m/%d/%y',
'%m/%d/%Y',
'%Y/%m/%d'
]
for dt_format in valid_formats:
try:
datetime.strptime(dt_string, dt_format)
return dt_format
except ValueError:
continue
return False | python | def _get_date_time_format(dt_string):
'''
Copied from win_system.py (_get_date_time_format)
Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
'''
valid_formats = [
'%I:%M:%S %p',
'%I:%M %p',
'%H:%M:%S',
'%H:%M',
'%Y-%m-%d',
'%m-%d-%y',
'%m-%d-%Y',
'%m/%d/%y',
'%m/%d/%Y',
'%Y/%m/%d'
]
for dt_format in valid_formats:
try:
datetime.strptime(dt_string, dt_format)
return dt_format
except ValueError:
continue
return False | [
"def",
"_get_date_time_format",
"(",
"dt_string",
")",
":",
"valid_formats",
"=",
"[",
"'%I:%M:%S %p'",
",",
"'%I:%M %p'",
",",
"'%H:%M:%S'",
",",
"'%H:%M'",
",",
"'%Y-%m-%d'",
",",
"'%m-%d-%y'",
",",
"'%m-%d-%Y'",
",",
"'%m/%d/%y'",
",",
"'%m/%d/%Y'",
",",
"'%Y... | Copied from win_system.py (_get_date_time_format)
Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str | [
"Copied",
"from",
"win_system",
".",
"py",
"(",
"_get_date_time_format",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L191-L221 | train |
saltstack/salt | salt/modules/win_task.py | _reverse_lookup | def _reverse_lookup(dictionary, value):
'''
Lookup the key in a dictionary by it's value. Will return the first match.
:param dict dictionary: The dictionary to search
:param str value: The value to search for.
:return: Returns the first key to match the value
:rtype: str
'''
value_index = -1
for idx, dict_value in enumerate(dictionary.values()):
if type(dict_value) == list:
if value in dict_value:
value_index = idx
break
elif value == dict_value:
value_index = idx
break
return list(dictionary)[value_index] | python | def _reverse_lookup(dictionary, value):
'''
Lookup the key in a dictionary by it's value. Will return the first match.
:param dict dictionary: The dictionary to search
:param str value: The value to search for.
:return: Returns the first key to match the value
:rtype: str
'''
value_index = -1
for idx, dict_value in enumerate(dictionary.values()):
if type(dict_value) == list:
if value in dict_value:
value_index = idx
break
elif value == dict_value:
value_index = idx
break
return list(dictionary)[value_index] | [
"def",
"_reverse_lookup",
"(",
"dictionary",
",",
"value",
")",
":",
"value_index",
"=",
"-",
"1",
"for",
"idx",
",",
"dict_value",
"in",
"enumerate",
"(",
"dictionary",
".",
"values",
"(",
")",
")",
":",
"if",
"type",
"(",
"dict_value",
")",
"==",
"li... | Lookup the key in a dictionary by it's value. Will return the first match.
:param dict dictionary: The dictionary to search
:param str value: The value to search for.
:return: Returns the first key to match the value
:rtype: str | [
"Lookup",
"the",
"key",
"in",
"a",
"dictionary",
"by",
"it",
"s",
"value",
".",
"Will",
"return",
"the",
"first",
"match",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L241-L262 | train |
saltstack/salt | salt/modules/win_task.py | _lookup_first | def _lookup_first(dictionary, key):
'''
Lookup the first value given a key. Returns the first value if the key
refers to a list or the value itself.
:param dict dictionary: The dictionary to search
:param str key: The key to get
:return: Returns the first value available for the key
:rtype: str
'''
value = dictionary[key]
if type(value) == list:
return value[0]
else:
return value | python | def _lookup_first(dictionary, key):
'''
Lookup the first value given a key. Returns the first value if the key
refers to a list or the value itself.
:param dict dictionary: The dictionary to search
:param str key: The key to get
:return: Returns the first value available for the key
:rtype: str
'''
value = dictionary[key]
if type(value) == list:
return value[0]
else:
return value | [
"def",
"_lookup_first",
"(",
"dictionary",
",",
"key",
")",
":",
"value",
"=",
"dictionary",
"[",
"key",
"]",
"if",
"type",
"(",
"value",
")",
"==",
"list",
":",
"return",
"value",
"[",
"0",
"]",
"else",
":",
"return",
"value"
] | Lookup the first value given a key. Returns the first value if the key
refers to a list or the value itself.
:param dict dictionary: The dictionary to search
:param str key: The key to get
:return: Returns the first value available for the key
:rtype: str | [
"Lookup",
"the",
"first",
"value",
"given",
"a",
"key",
".",
"Returns",
"the",
"first",
"value",
"if",
"the",
"key",
"refers",
"to",
"a",
"list",
"or",
"the",
"value",
"itself",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L265-L281 | train |
saltstack/salt | salt/modules/win_task.py | _save_task_definition | def _save_task_definition(name,
task_folder,
task_definition,
user_name,
password,
logon_type):
'''
Internal function to save the task definition.
:param str name: The name of the task.
:param str task_folder: The object representing the folder in which to save
the task
:param str task_definition: The object representing the task to be saved
:param str user_name: The user_account under which to run the task
:param str password: The password that corresponds to the user account
:param int logon_type: The logon type for the task.
:return: True if successful, False if not
:rtype: bool
'''
try:
task_folder.RegisterTaskDefinition(name,
task_definition,
TASK_CREATE_OR_UPDATE,
user_name,
password,
logon_type)
return True
except pythoncom.com_error as error:
hr, msg, exc, arg = error.args # pylint: disable=W0633
fc = {-2147024773: 'The filename, directory name, or volume label syntax is incorrect',
-2147024894: 'The system cannot find the file specified',
-2147216615: 'Required element or attribute missing',
-2147216616: 'Value incorrectly formatted or out of range',
-2147352571: 'Access denied'}
try:
failure_code = fc[exc[5]]
except KeyError:
failure_code = 'Unknown Failure: {0}'.format(error)
log.debug('Failed to modify task: %s', failure_code)
return 'Failed to modify task: {0}'.format(failure_code) | python | def _save_task_definition(name,
task_folder,
task_definition,
user_name,
password,
logon_type):
'''
Internal function to save the task definition.
:param str name: The name of the task.
:param str task_folder: The object representing the folder in which to save
the task
:param str task_definition: The object representing the task to be saved
:param str user_name: The user_account under which to run the task
:param str password: The password that corresponds to the user account
:param int logon_type: The logon type for the task.
:return: True if successful, False if not
:rtype: bool
'''
try:
task_folder.RegisterTaskDefinition(name,
task_definition,
TASK_CREATE_OR_UPDATE,
user_name,
password,
logon_type)
return True
except pythoncom.com_error as error:
hr, msg, exc, arg = error.args # pylint: disable=W0633
fc = {-2147024773: 'The filename, directory name, or volume label syntax is incorrect',
-2147024894: 'The system cannot find the file specified',
-2147216615: 'Required element or attribute missing',
-2147216616: 'Value incorrectly formatted or out of range',
-2147352571: 'Access denied'}
try:
failure_code = fc[exc[5]]
except KeyError:
failure_code = 'Unknown Failure: {0}'.format(error)
log.debug('Failed to modify task: %s', failure_code)
return 'Failed to modify task: {0}'.format(failure_code) | [
"def",
"_save_task_definition",
"(",
"name",
",",
"task_folder",
",",
"task_definition",
",",
"user_name",
",",
"password",
",",
"logon_type",
")",
":",
"try",
":",
"task_folder",
".",
"RegisterTaskDefinition",
"(",
"name",
",",
"task_definition",
",",
"TASK_CREAT... | Internal function to save the task definition.
:param str name: The name of the task.
:param str task_folder: The object representing the folder in which to save
the task
:param str task_definition: The object representing the task to be saved
:param str user_name: The user_account under which to run the task
:param str password: The password that corresponds to the user account
:param int logon_type: The logon type for the task.
:return: True if successful, False if not
:rtype: bool | [
"Internal",
"function",
"to",
"save",
"the",
"task",
"definition",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L284-L333 | train |
saltstack/salt | salt/modules/win_task.py | list_tasks | def list_tasks(location='\\'):
r'''
List all tasks located in a specific location in the task scheduler.
:param str location: A string value representing the folder from which you
want to list tasks. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:return: Returns a list of tasks.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_tasks
'''
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the folder to list tasks from
task_folder = task_service.GetFolder(location)
tasks = task_folder.GetTasks(0)
ret = []
for task in tasks:
ret.append(task.Name)
return ret | python | def list_tasks(location='\\'):
r'''
List all tasks located in a specific location in the task scheduler.
:param str location: A string value representing the folder from which you
want to list tasks. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:return: Returns a list of tasks.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_tasks
'''
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the folder to list tasks from
task_folder = task_service.GetFolder(location)
tasks = task_folder.GetTasks(0)
ret = []
for task in tasks:
ret.append(task.Name)
return ret | [
"def",
"list_tasks",
"(",
"location",
"=",
"'\\\\'",
")",
":",
"# Create the task service object",
"with",
"salt",
".",
"utils",
".",
"winapi",
".",
"Com",
"(",
")",
":",
"task_service",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
"\"Schedule.Service... | r'''
List all tasks located in a specific location in the task scheduler.
:param str location: A string value representing the folder from which you
want to list tasks. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:return: Returns a list of tasks.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_tasks | [
"r",
"List",
"all",
"tasks",
"located",
"in",
"a",
"specific",
"location",
"in",
"the",
"task",
"scheduler",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L336-L366 | train |
saltstack/salt | salt/modules/win_task.py | list_folders | def list_folders(location='\\'):
r'''
List all folders located in a specific location in the task scheduler.
:param str location: A string value representing the folder from which you
want to list tasks. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:return: Returns a list of folders.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_folders
'''
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the folder to list folders from
task_folder = task_service.GetFolder(location)
folders = task_folder.GetFolders(0)
ret = []
for folder in folders:
ret.append(folder.Name)
return ret | python | def list_folders(location='\\'):
r'''
List all folders located in a specific location in the task scheduler.
:param str location: A string value representing the folder from which you
want to list tasks. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:return: Returns a list of folders.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_folders
'''
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the folder to list folders from
task_folder = task_service.GetFolder(location)
folders = task_folder.GetFolders(0)
ret = []
for folder in folders:
ret.append(folder.Name)
return ret | [
"def",
"list_folders",
"(",
"location",
"=",
"'\\\\'",
")",
":",
"# Create the task service object",
"with",
"salt",
".",
"utils",
".",
"winapi",
".",
"Com",
"(",
")",
":",
"task_service",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
"\"Schedule.Servi... | r'''
List all folders located in a specific location in the task scheduler.
:param str location: A string value representing the folder from which you
want to list tasks. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:return: Returns a list of folders.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_folders | [
"r",
"List",
"all",
"folders",
"located",
"in",
"a",
"specific",
"location",
"in",
"the",
"task",
"scheduler",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L369-L399 | train |
saltstack/salt | salt/modules/win_task.py | list_triggers | def list_triggers(name, location='\\'):
r'''
List all triggers that pertain to a task in the specified location.
:param str name: The name of the task for which list triggers.
:param str location: A string value representing the location of the task
from which to list triggers. Default is '\\' which is the root for the
task scheduler (C:\Windows\System32\tasks).
:return: Returns a list of triggers.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_triggers <task_name>
'''
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the folder to list folders from
task_folder = task_service.GetFolder(location)
task_definition = task_folder.GetTask(name).Definition
triggers = task_definition.Triggers
ret = []
for trigger in triggers:
ret.append(trigger.Id)
return ret | python | def list_triggers(name, location='\\'):
r'''
List all triggers that pertain to a task in the specified location.
:param str name: The name of the task for which list triggers.
:param str location: A string value representing the location of the task
from which to list triggers. Default is '\\' which is the root for the
task scheduler (C:\Windows\System32\tasks).
:return: Returns a list of triggers.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_triggers <task_name>
'''
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the folder to list folders from
task_folder = task_service.GetFolder(location)
task_definition = task_folder.GetTask(name).Definition
triggers = task_definition.Triggers
ret = []
for trigger in triggers:
ret.append(trigger.Id)
return ret | [
"def",
"list_triggers",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Create the task service object",
"with",
"salt",
".",
"utils",
".",
"winapi",
".",
"Com",
"(",
")",
":",
"task_service",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
... | r'''
List all triggers that pertain to a task in the specified location.
:param str name: The name of the task for which list triggers.
:param str location: A string value representing the location of the task
from which to list triggers. Default is '\\' which is the root for the
task scheduler (C:\Windows\System32\tasks).
:return: Returns a list of triggers.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_triggers <task_name> | [
"r",
"List",
"all",
"triggers",
"that",
"pertain",
"to",
"a",
"task",
"in",
"the",
"specified",
"location",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L402-L435 | train |
saltstack/salt | salt/modules/win_task.py | list_actions | def list_actions(name, location='\\'):
r'''
List all actions that pertain to a task in the specified location.
:param str name: The name of the task for which list actions.
:param str location: A string value representing the location of the task
from which to list actions. Default is '\\' which is the root for the
task scheduler (C:\Windows\System32\tasks).
:return: Returns a list of actions.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_actions <task_name>
'''
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the folder to list folders from
task_folder = task_service.GetFolder(location)
task_definition = task_folder.GetTask(name).Definition
actions = task_definition.Actions
ret = []
for action in actions:
ret.append(action.Id)
return ret | python | def list_actions(name, location='\\'):
r'''
List all actions that pertain to a task in the specified location.
:param str name: The name of the task for which list actions.
:param str location: A string value representing the location of the task
from which to list actions. Default is '\\' which is the root for the
task scheduler (C:\Windows\System32\tasks).
:return: Returns a list of actions.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_actions <task_name>
'''
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the folder to list folders from
task_folder = task_service.GetFolder(location)
task_definition = task_folder.GetTask(name).Definition
actions = task_definition.Actions
ret = []
for action in actions:
ret.append(action.Id)
return ret | [
"def",
"list_actions",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Create the task service object",
"with",
"salt",
".",
"utils",
".",
"winapi",
".",
"Com",
"(",
")",
":",
"task_service",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
... | r'''
List all actions that pertain to a task in the specified location.
:param str name: The name of the task for which list actions.
:param str location: A string value representing the location of the task
from which to list actions. Default is '\\' which is the root for the
task scheduler (C:\Windows\System32\tasks).
:return: Returns a list of actions.
:rtype: list
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_actions <task_name> | [
"r",
"List",
"all",
"actions",
"that",
"pertain",
"to",
"a",
"task",
"in",
"the",
"specified",
"location",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L438-L471 | train |
saltstack/salt | salt/modules/win_task.py | create_task | def create_task(name,
location='\\',
user_name='System',
password=None,
force=False,
**kwargs):
r'''
Create a new task in the designated location. This function has many keyword
arguments that are not listed here. For additional arguments see:
- :py:func:`edit_task`
- :py:func:`add_action`
- :py:func:`add_trigger`
:param str name: The name of the task. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the task. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:param str user_name: The user account under which to run the task. To
specify the 'System' account, use 'System'. The password will be
ignored.
:param str password: The password to use for authentication. This should set
the task to run whether the user is logged in or not, but is currently
not working.
:param bool force: If the task exists, overwrite the existing task.
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.create_task <task_name> user_name=System force=True action_type=Execute cmd='del /Q /S C:\\Temp' trigger_type=Once start_date=2016-12-1 start_time=01:00
'''
# Check for existing task
if name in list_tasks(location) and not force:
# Connect to an existing task definition
return '{0} already exists'.format(name)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Create a new task definition
task_definition = task_service.NewTask(0)
# Modify task settings
edit_task(task_definition=task_definition,
user_name=user_name,
password=password,
**kwargs)
# Add Action
add_action(task_definition=task_definition, **kwargs)
# Add Trigger
add_trigger(task_definition=task_definition, **kwargs)
# get the folder to create the task in
task_folder = task_service.GetFolder(location)
# Save the task
_save_task_definition(name=name,
task_folder=task_folder,
task_definition=task_definition,
user_name=task_definition.Principal.UserID,
password=password,
logon_type=task_definition.Principal.LogonType)
# Verify task was created
if name in list_tasks(location):
return True
else:
return False | python | def create_task(name,
location='\\',
user_name='System',
password=None,
force=False,
**kwargs):
r'''
Create a new task in the designated location. This function has many keyword
arguments that are not listed here. For additional arguments see:
- :py:func:`edit_task`
- :py:func:`add_action`
- :py:func:`add_trigger`
:param str name: The name of the task. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the task. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:param str user_name: The user account under which to run the task. To
specify the 'System' account, use 'System'. The password will be
ignored.
:param str password: The password to use for authentication. This should set
the task to run whether the user is logged in or not, but is currently
not working.
:param bool force: If the task exists, overwrite the existing task.
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.create_task <task_name> user_name=System force=True action_type=Execute cmd='del /Q /S C:\\Temp' trigger_type=Once start_date=2016-12-1 start_time=01:00
'''
# Check for existing task
if name in list_tasks(location) and not force:
# Connect to an existing task definition
return '{0} already exists'.format(name)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Create a new task definition
task_definition = task_service.NewTask(0)
# Modify task settings
edit_task(task_definition=task_definition,
user_name=user_name,
password=password,
**kwargs)
# Add Action
add_action(task_definition=task_definition, **kwargs)
# Add Trigger
add_trigger(task_definition=task_definition, **kwargs)
# get the folder to create the task in
task_folder = task_service.GetFolder(location)
# Save the task
_save_task_definition(name=name,
task_folder=task_folder,
task_definition=task_definition,
user_name=task_definition.Principal.UserID,
password=password,
logon_type=task_definition.Principal.LogonType)
# Verify task was created
if name in list_tasks(location):
return True
else:
return False | [
"def",
"create_task",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
",",
"user_name",
"=",
"'System'",
",",
"password",
"=",
"None",
",",
"force",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Check for existing task",
"if",
"name",
"in",
"list_tasks"... | r'''
Create a new task in the designated location. This function has many keyword
arguments that are not listed here. For additional arguments see:
- :py:func:`edit_task`
- :py:func:`add_action`
- :py:func:`add_trigger`
:param str name: The name of the task. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the task. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:param str user_name: The user account under which to run the task. To
specify the 'System' account, use 'System'. The password will be
ignored.
:param str password: The password to use for authentication. This should set
the task to run whether the user is logged in or not, but is currently
not working.
:param bool force: If the task exists, overwrite the existing task.
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.create_task <task_name> user_name=System force=True action_type=Execute cmd='del /Q /S C:\\Temp' trigger_type=Once start_date=2016-12-1 start_time=01:00 | [
"r",
"Create",
"a",
"new",
"task",
"in",
"the",
"designated",
"location",
".",
"This",
"function",
"has",
"many",
"keyword",
"arguments",
"that",
"are",
"not",
"listed",
"here",
".",
"For",
"additional",
"arguments",
"see",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L474-L554 | train |
saltstack/salt | salt/modules/win_task.py | create_task_from_xml | def create_task_from_xml(name,
location='\\',
xml_text=None,
xml_path=None,
user_name='System',
password=None):
r'''
Create a task based on XML. Source can be a file or a string of XML.
:param str name: The name of the task. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the task. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:param str xml_text: A string of xml representing the task to be created.
This will be overridden by `xml_path` if passed.
:param str xml_path: The path to an XML file on the local system containing
the xml that defines the task. This will override `xml_text`
:param str user_name: The user account under which to run the task. To
specify the 'System' account, use 'System'. The password will be
ignored.
:param str password: The password to use for authentication. This should set
the task to run whether the user is logged in or not, but is currently
not working.
:return: True if successful, False if unsuccessful, A string with the error message if there is an error
:rtype: bool
:raises: CommandExecutionError
CLI Example:
.. code-block:: bash
salt 'minion-id' task.create_task_from_xml <task_name> xml_path=C:\task.xml
'''
# Check for existing task
if name in list_tasks(location):
# Connect to an existing task definition
return '{0} already exists'.format(name)
if not xml_text and not xml_path:
raise ArgumentValueError('Must specify either xml_text or xml_path')
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Load xml from file, overrides xml_text
# Need to figure out how to load contents of xml
if xml_path:
xml_text = xml_path
# Get the folder to list folders from
task_folder = task_service.GetFolder(location)
# Determine logon type
if user_name:
if user_name.lower() == 'system':
logon_type = TASK_LOGON_SERVICE_ACCOUNT
user_name = 'SYSTEM'
password = None
else:
if password:
logon_type = TASK_LOGON_PASSWORD
else:
logon_type = TASK_LOGON_INTERACTIVE_TOKEN
else:
password = None
logon_type = TASK_LOGON_NONE
# Save the task
try:
task_folder.RegisterTask(name,
xml_text,
TASK_CREATE,
user_name,
password,
logon_type)
except pythoncom.com_error as error:
hr, msg, exc, arg = error.args # pylint: disable=W0633
error_code = hex(exc[5] + 2**32)
failure_code = error_code
fc = {'0x80041319L': 'Required element or attribute missing',
'0x80041318L': 'Value incorrectly formatted or out of range',
'0x80020005L': 'Access denied',
'0x80041309L': "A task's trigger is not found",
'0x8004130aL': "One or more of the properties required to run this task have not been set",
'0x8004130cL': "The Task Scheduler service is not installed on this computer",
'0x8004130dL': "The task object could not be opened",
'0x8004130eL': "The object is either an invalid task object or is not a task object",
'0x8004130fL': "No account information could be found in the Task Scheduler security database for the task indicated",
'0x80041310L': "Unable to establish existence of the account specified",
'0x80041311L': "Corruption was detected in the Task Scheduler security database; the database has been reset",
'0x80041313L': "The task object version is either unsupported or invalid",
'0x80041314L': "The task has been configured with an unsupported combination of account settings and run time options",
'0x80041315L': "The Task Scheduler Service is not running",
'0x80041316L': "The task XML contains an unexpected node",
'0x80041317L': "The task XML contains an element or attribute from an unexpected namespace",
'0x8004131aL': "The task XML is malformed",
'0x0004131cL': "The task is registered, but may fail to start. Batch logon privilege needs to be enabled for the task principal",
'0x8004131dL': "The task XML contains too many nodes of the same type",
}
try:
failure_code = fc[error_code]
except KeyError:
failure_code = 'Unknown Failure: {0}'.format(error_code)
finally:
log.debug('Failed to create task: %s', failure_code)
raise CommandExecutionError(failure_code)
# Verify creation
return name in list_tasks(location) | python | def create_task_from_xml(name,
location='\\',
xml_text=None,
xml_path=None,
user_name='System',
password=None):
r'''
Create a task based on XML. Source can be a file or a string of XML.
:param str name: The name of the task. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the task. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:param str xml_text: A string of xml representing the task to be created.
This will be overridden by `xml_path` if passed.
:param str xml_path: The path to an XML file on the local system containing
the xml that defines the task. This will override `xml_text`
:param str user_name: The user account under which to run the task. To
specify the 'System' account, use 'System'. The password will be
ignored.
:param str password: The password to use for authentication. This should set
the task to run whether the user is logged in or not, but is currently
not working.
:return: True if successful, False if unsuccessful, A string with the error message if there is an error
:rtype: bool
:raises: CommandExecutionError
CLI Example:
.. code-block:: bash
salt 'minion-id' task.create_task_from_xml <task_name> xml_path=C:\task.xml
'''
# Check for existing task
if name in list_tasks(location):
# Connect to an existing task definition
return '{0} already exists'.format(name)
if not xml_text and not xml_path:
raise ArgumentValueError('Must specify either xml_text or xml_path')
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Load xml from file, overrides xml_text
# Need to figure out how to load contents of xml
if xml_path:
xml_text = xml_path
# Get the folder to list folders from
task_folder = task_service.GetFolder(location)
# Determine logon type
if user_name:
if user_name.lower() == 'system':
logon_type = TASK_LOGON_SERVICE_ACCOUNT
user_name = 'SYSTEM'
password = None
else:
if password:
logon_type = TASK_LOGON_PASSWORD
else:
logon_type = TASK_LOGON_INTERACTIVE_TOKEN
else:
password = None
logon_type = TASK_LOGON_NONE
# Save the task
try:
task_folder.RegisterTask(name,
xml_text,
TASK_CREATE,
user_name,
password,
logon_type)
except pythoncom.com_error as error:
hr, msg, exc, arg = error.args # pylint: disable=W0633
error_code = hex(exc[5] + 2**32)
failure_code = error_code
fc = {'0x80041319L': 'Required element or attribute missing',
'0x80041318L': 'Value incorrectly formatted or out of range',
'0x80020005L': 'Access denied',
'0x80041309L': "A task's trigger is not found",
'0x8004130aL': "One or more of the properties required to run this task have not been set",
'0x8004130cL': "The Task Scheduler service is not installed on this computer",
'0x8004130dL': "The task object could not be opened",
'0x8004130eL': "The object is either an invalid task object or is not a task object",
'0x8004130fL': "No account information could be found in the Task Scheduler security database for the task indicated",
'0x80041310L': "Unable to establish existence of the account specified",
'0x80041311L': "Corruption was detected in the Task Scheduler security database; the database has been reset",
'0x80041313L': "The task object version is either unsupported or invalid",
'0x80041314L': "The task has been configured with an unsupported combination of account settings and run time options",
'0x80041315L': "The Task Scheduler Service is not running",
'0x80041316L': "The task XML contains an unexpected node",
'0x80041317L': "The task XML contains an element or attribute from an unexpected namespace",
'0x8004131aL': "The task XML is malformed",
'0x0004131cL': "The task is registered, but may fail to start. Batch logon privilege needs to be enabled for the task principal",
'0x8004131dL': "The task XML contains too many nodes of the same type",
}
try:
failure_code = fc[error_code]
except KeyError:
failure_code = 'Unknown Failure: {0}'.format(error_code)
finally:
log.debug('Failed to create task: %s', failure_code)
raise CommandExecutionError(failure_code)
# Verify creation
return name in list_tasks(location) | [
"def",
"create_task_from_xml",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
",",
"xml_text",
"=",
"None",
",",
"xml_path",
"=",
"None",
",",
"user_name",
"=",
"'System'",
",",
"password",
"=",
"None",
")",
":",
"# Check for existing task",
"if",
"name",
"in"... | r'''
Create a task based on XML. Source can be a file or a string of XML.
:param str name: The name of the task. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the task. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:param str xml_text: A string of xml representing the task to be created.
This will be overridden by `xml_path` if passed.
:param str xml_path: The path to an XML file on the local system containing
the xml that defines the task. This will override `xml_text`
:param str user_name: The user account under which to run the task. To
specify the 'System' account, use 'System'. The password will be
ignored.
:param str password: The password to use for authentication. This should set
the task to run whether the user is logged in or not, but is currently
not working.
:return: True if successful, False if unsuccessful, A string with the error message if there is an error
:rtype: bool
:raises: CommandExecutionError
CLI Example:
.. code-block:: bash
salt 'minion-id' task.create_task_from_xml <task_name> xml_path=C:\task.xml | [
"r",
"Create",
"a",
"task",
"based",
"on",
"XML",
".",
"Source",
"can",
"be",
"a",
"file",
"or",
"a",
"string",
"of",
"XML",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L557-L675 | train |
saltstack/salt | salt/modules/win_task.py | create_folder | def create_folder(name, location='\\'):
r'''
Create a folder in which to create tasks.
:param str name: The name of the folder. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the folder. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.create_folder <folder_name>
'''
# Check for existing folder
if name in list_folders(location):
# Connect to an existing task definition
return '{0} already exists'.format(name)
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the folder to list folders from
task_folder = task_service.GetFolder(location)
task_folder.CreateFolder(name)
# Verify creation
if name in list_folders(location):
return True
else:
return False | python | def create_folder(name, location='\\'):
r'''
Create a folder in which to create tasks.
:param str name: The name of the folder. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the folder. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.create_folder <folder_name>
'''
# Check for existing folder
if name in list_folders(location):
# Connect to an existing task definition
return '{0} already exists'.format(name)
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the folder to list folders from
task_folder = task_service.GetFolder(location)
task_folder.CreateFolder(name)
# Verify creation
if name in list_folders(location):
return True
else:
return False | [
"def",
"create_folder",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing folder",
"if",
"name",
"in",
"list_folders",
"(",
"location",
")",
":",
"# Connect to an existing task definition",
"return",
"'{0} already exists'",
".",
"format",
"(... | r'''
Create a folder in which to create tasks.
:param str name: The name of the folder. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the folder. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.create_folder <folder_name> | [
"r",
"Create",
"a",
"folder",
"in",
"which",
"to",
"create",
"tasks",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L678-L716 | train |
saltstack/salt | salt/modules/win_task.py | edit_task | def edit_task(name=None,
location='\\',
# General Tab
user_name=None,
password=None,
description=None,
enabled=None,
hidden=None,
# Conditions Tab
run_if_idle=None,
idle_duration=None,
idle_wait_timeout=None,
idle_stop_on_end=None,
idle_restart=None,
ac_only=None,
stop_if_on_batteries=None,
wake_to_run=None,
run_if_network=None,
network_id=None,
network_name=None,
# Settings Tab
allow_demand_start=None,
start_when_available=None,
restart_every=None,
restart_count=3,
execution_time_limit=None,
force_stop=None,
delete_after=None,
multiple_instances=None,
**kwargs):
r'''
Edit the parameters of a task. Triggers and Actions cannot be edited yet.
:param str name: The name of the task. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the task. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:param str user_name: The user account under which to run the task. To
specify the 'System' account, use 'System'. The password will be
ignored.
:param str password: The password to use for authentication. This should set
the task to run whether the user is logged in or not, but is currently
not working.
.. note::
The combination of user_name and password determine how the task runs.
For example, if a username is passed without at password the task will
only run when the user is logged in. If a password is passed as well
the task will run whether the user is logged on or not. If you pass
'System' as the username the task will run as the system account (the
password parameter is ignored.
:param str description: A string representing the text that will be
displayed in the description field in the task scheduler.
:param bool enabled: A boolean value representing whether or not the task is
enabled.
:param bool hidden: A boolean value representing whether or not the task is
hidden.
:param bool run_if_idle: Boolean value that indicates that the Task
Scheduler will run the task only if the computer is in an idle state.
:param str idle_duration: A value that indicates the amount of time that the
computer must be in an idle state before the task is run. Valid values
are:
- 1 minute
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
:param str idle_wait_timeout: A value that indicates the amount of time that
the Task Scheduler will wait for an idle condition to occur. Valid
values are:
- Do not wait
- 1 minute
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
- 2 hours
:param bool idle_stop_on_end: Boolean value that indicates that the Task
Scheduler will terminate the task if the idle condition ends before the
task is completed.
:param bool idle_restart: Boolean value that indicates whether the task is
restarted when the computer cycles into an idle condition more than
once.
:param bool ac_only: Boolean value that indicates that the Task Scheduler
will launch the task only while on AC power.
:param bool stop_if_on_batteries: Boolean value that indicates that the task
will be stopped if the computer begins to run on battery power.
:param bool wake_to_run: Boolean value that indicates that the Task
Scheduler will wake the computer when it is time to run the task.
:param bool run_if_network: Boolean value that indicates that the Task
Scheduler will run the task only when a network is available.
:param guid network_id: GUID value that identifies a network profile.
:param str network_name: Sets the name of a network profile. The name is
used for display purposes.
:param bool allow_demand_start: Boolean value that indicates that the task
can be started by using either the Run command or the Context menu.
:param bool start_when_available: Boolean value that indicates that the Task
Scheduler can start the task at any time after its scheduled time has
passed.
:param restart_every: A value that specifies the interval between task
restart attempts. Valid values are:
- False (to disable)
- 1 minute
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
- 2 hours
:param int restart_count: The number of times the Task Scheduler will
attempt to restart the task. Valid values are integers 1 - 999.
:param execution_time_limit: The amount of time allowed to complete the
task. Valid values are:
- False (to disable)
- 1 hour
- 2 hours
- 4 hours
- 8 hours
- 12 hours
- 1 day
- 3 days
:param bool force_stop: Boolean value that indicates that the task may be
terminated by using TerminateProcess.
:param delete_after: The amount of time that the Task Scheduler will
wait before deleting the task after it expires. Requires a trigger with
an expiration date. Valid values are:
- False (to disable)
- Immediately
- 30 days
- 90 days
- 180 days
- 365 days
:param str multiple_instances: Sets the policy that defines how the Task
Scheduler deals with multiple instances of the task. Valid values are:
- Parallel
- Queue
- No New Instance
- Stop Existing
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.edit_task <task_name> description='This task is awesome'
'''
# TODO: Add more detailed return for items changed
# Check for passed task_definition
# If not passed, open a task definition for an existing task
save_definition = False
if kwargs.get('task_definition', False):
task_definition = kwargs.get('task_definition')
else:
save_definition = True
# Make sure a name was passed
if not name:
return 'Required parameter "name" not passed'
# Make sure task exists to modify
if name in list_tasks(location):
# Connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to create the task in
task_folder = task_service.GetFolder(location)
# Connect to an existing task definition
task_definition = task_folder.GetTask(name).Definition
else:
# Not found and create_new not set, return not found
return '{0} not found'.format(name)
# General Information
if save_definition:
task_definition.RegistrationInfo.Author = 'Salt Minion'
task_definition.RegistrationInfo.Source = "Salt Minion Daemon"
if description is not None:
task_definition.RegistrationInfo.Description = description
# General Information: Security Options
if user_name:
# Determine logon type
if user_name.lower() == 'system':
logon_type = TASK_LOGON_SERVICE_ACCOUNT
user_name = 'SYSTEM'
password = None
else:
task_definition.Principal.Id = user_name
if password:
logon_type = TASK_LOGON_PASSWORD
else:
logon_type = TASK_LOGON_INTERACTIVE_TOKEN
task_definition.Principal.UserID = user_name
task_definition.Principal.DisplayName = user_name
task_definition.Principal.LogonType = logon_type
task_definition.Principal.RunLevel = TASK_RUNLEVEL_HIGHEST
else:
user_name = None
password = None
# Settings
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa383480(v=vs.85).aspx
if enabled is not None:
task_definition.Settings.Enabled = enabled
# Settings: General Tab
if hidden is not None:
task_definition.Settings.Hidden = hidden
# Settings: Conditions Tab (Idle)
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa380669(v=vs.85).aspx
if run_if_idle is not None:
task_definition.Settings.RunOnlyIfIdle = run_if_idle
if task_definition.Settings.RunOnlyIfIdle:
if idle_stop_on_end is not None:
task_definition.Settings.IdleSettings.StopOnIdleEnd = idle_stop_on_end
if idle_restart is not None:
task_definition.Settings.IdleSettings.RestartOnIdle = idle_restart
if idle_duration is not None:
if idle_duration in duration:
task_definition.Settings.IdleSettings.IdleDuration = _lookup_first(duration, idle_duration)
else:
return 'Invalid value for "idle_duration"'
if idle_wait_timeout is not None:
if idle_wait_timeout in duration:
task_definition.Settings.IdleSettings.WaitTimeout = _lookup_first(duration, idle_wait_timeout)
else:
return 'Invalid value for "idle_wait_timeout"'
# Settings: Conditions Tab (Power)
if ac_only is not None:
task_definition.Settings.DisallowStartIfOnBatteries = ac_only
if stop_if_on_batteries is not None:
task_definition.Settings.StopIfGoingOnBatteries = stop_if_on_batteries
if wake_to_run is not None:
task_definition.Settings.WakeToRun = wake_to_run
# Settings: Conditions Tab (Network)
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa382067(v=vs.85).aspx
if run_if_network is not None:
task_definition.Settings.RunOnlyIfNetworkAvailable = run_if_network
if task_definition.Settings.RunOnlyIfNetworkAvailable:
if network_id:
task_definition.Settings.NetworkSettings.Id = network_id
if network_name:
task_definition.Settings.NetworkSettings.Name = network_name
# Settings: Settings Tab
if allow_demand_start is not None:
task_definition.Settings.AllowDemandStart = allow_demand_start
if start_when_available is not None:
task_definition.Settings.StartWhenAvailable = start_when_available
if restart_every is not None:
if restart_every is False:
task_definition.Settings.RestartInterval = ''
else:
if restart_every in duration:
task_definition.Settings.RestartInterval = _lookup_first(duration, restart_every)
else:
return 'Invalid value for "restart_every"'
if task_definition.Settings.RestartInterval:
if restart_count is not None:
if restart_count in range(1, 999):
task_definition.Settings.RestartCount = restart_count
else:
return '"restart_count" must be a value between 1 and 999'
if execution_time_limit is not None:
if execution_time_limit is False:
task_definition.Settings.ExecutionTimeLimit = 'PT0S'
else:
if execution_time_limit in duration:
task_definition.Settings.ExecutionTimeLimit = _lookup_first(duration, execution_time_limit)
else:
return 'Invalid value for "execution_time_limit"'
if force_stop is not None:
task_definition.Settings.AllowHardTerminate = force_stop
if delete_after is not None:
# TODO: Check triggers for end_boundary
if delete_after is False:
task_definition.Settings.DeleteExpiredTaskAfter = ''
if delete_after in duration:
task_definition.Settings.DeleteExpiredTaskAfter = _lookup_first(duration, delete_after)
else:
return 'Invalid value for "delete_after"'
if multiple_instances is not None:
task_definition.Settings.MultipleInstances = instances[multiple_instances]
# Save the task
if save_definition:
# Save the Changes
return _save_task_definition(name=name,
task_folder=task_folder,
task_definition=task_definition,
user_name=user_name,
password=password,
logon_type=task_definition.Principal.LogonType) | python | def edit_task(name=None,
location='\\',
# General Tab
user_name=None,
password=None,
description=None,
enabled=None,
hidden=None,
# Conditions Tab
run_if_idle=None,
idle_duration=None,
idle_wait_timeout=None,
idle_stop_on_end=None,
idle_restart=None,
ac_only=None,
stop_if_on_batteries=None,
wake_to_run=None,
run_if_network=None,
network_id=None,
network_name=None,
# Settings Tab
allow_demand_start=None,
start_when_available=None,
restart_every=None,
restart_count=3,
execution_time_limit=None,
force_stop=None,
delete_after=None,
multiple_instances=None,
**kwargs):
r'''
Edit the parameters of a task. Triggers and Actions cannot be edited yet.
:param str name: The name of the task. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the task. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:param str user_name: The user account under which to run the task. To
specify the 'System' account, use 'System'. The password will be
ignored.
:param str password: The password to use for authentication. This should set
the task to run whether the user is logged in or not, but is currently
not working.
.. note::
The combination of user_name and password determine how the task runs.
For example, if a username is passed without at password the task will
only run when the user is logged in. If a password is passed as well
the task will run whether the user is logged on or not. If you pass
'System' as the username the task will run as the system account (the
password parameter is ignored.
:param str description: A string representing the text that will be
displayed in the description field in the task scheduler.
:param bool enabled: A boolean value representing whether or not the task is
enabled.
:param bool hidden: A boolean value representing whether or not the task is
hidden.
:param bool run_if_idle: Boolean value that indicates that the Task
Scheduler will run the task only if the computer is in an idle state.
:param str idle_duration: A value that indicates the amount of time that the
computer must be in an idle state before the task is run. Valid values
are:
- 1 minute
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
:param str idle_wait_timeout: A value that indicates the amount of time that
the Task Scheduler will wait for an idle condition to occur. Valid
values are:
- Do not wait
- 1 minute
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
- 2 hours
:param bool idle_stop_on_end: Boolean value that indicates that the Task
Scheduler will terminate the task if the idle condition ends before the
task is completed.
:param bool idle_restart: Boolean value that indicates whether the task is
restarted when the computer cycles into an idle condition more than
once.
:param bool ac_only: Boolean value that indicates that the Task Scheduler
will launch the task only while on AC power.
:param bool stop_if_on_batteries: Boolean value that indicates that the task
will be stopped if the computer begins to run on battery power.
:param bool wake_to_run: Boolean value that indicates that the Task
Scheduler will wake the computer when it is time to run the task.
:param bool run_if_network: Boolean value that indicates that the Task
Scheduler will run the task only when a network is available.
:param guid network_id: GUID value that identifies a network profile.
:param str network_name: Sets the name of a network profile. The name is
used for display purposes.
:param bool allow_demand_start: Boolean value that indicates that the task
can be started by using either the Run command or the Context menu.
:param bool start_when_available: Boolean value that indicates that the Task
Scheduler can start the task at any time after its scheduled time has
passed.
:param restart_every: A value that specifies the interval between task
restart attempts. Valid values are:
- False (to disable)
- 1 minute
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
- 2 hours
:param int restart_count: The number of times the Task Scheduler will
attempt to restart the task. Valid values are integers 1 - 999.
:param execution_time_limit: The amount of time allowed to complete the
task. Valid values are:
- False (to disable)
- 1 hour
- 2 hours
- 4 hours
- 8 hours
- 12 hours
- 1 day
- 3 days
:param bool force_stop: Boolean value that indicates that the task may be
terminated by using TerminateProcess.
:param delete_after: The amount of time that the Task Scheduler will
wait before deleting the task after it expires. Requires a trigger with
an expiration date. Valid values are:
- False (to disable)
- Immediately
- 30 days
- 90 days
- 180 days
- 365 days
:param str multiple_instances: Sets the policy that defines how the Task
Scheduler deals with multiple instances of the task. Valid values are:
- Parallel
- Queue
- No New Instance
- Stop Existing
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.edit_task <task_name> description='This task is awesome'
'''
# TODO: Add more detailed return for items changed
# Check for passed task_definition
# If not passed, open a task definition for an existing task
save_definition = False
if kwargs.get('task_definition', False):
task_definition = kwargs.get('task_definition')
else:
save_definition = True
# Make sure a name was passed
if not name:
return 'Required parameter "name" not passed'
# Make sure task exists to modify
if name in list_tasks(location):
# Connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to create the task in
task_folder = task_service.GetFolder(location)
# Connect to an existing task definition
task_definition = task_folder.GetTask(name).Definition
else:
# Not found and create_new not set, return not found
return '{0} not found'.format(name)
# General Information
if save_definition:
task_definition.RegistrationInfo.Author = 'Salt Minion'
task_definition.RegistrationInfo.Source = "Salt Minion Daemon"
if description is not None:
task_definition.RegistrationInfo.Description = description
# General Information: Security Options
if user_name:
# Determine logon type
if user_name.lower() == 'system':
logon_type = TASK_LOGON_SERVICE_ACCOUNT
user_name = 'SYSTEM'
password = None
else:
task_definition.Principal.Id = user_name
if password:
logon_type = TASK_LOGON_PASSWORD
else:
logon_type = TASK_LOGON_INTERACTIVE_TOKEN
task_definition.Principal.UserID = user_name
task_definition.Principal.DisplayName = user_name
task_definition.Principal.LogonType = logon_type
task_definition.Principal.RunLevel = TASK_RUNLEVEL_HIGHEST
else:
user_name = None
password = None
# Settings
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa383480(v=vs.85).aspx
if enabled is not None:
task_definition.Settings.Enabled = enabled
# Settings: General Tab
if hidden is not None:
task_definition.Settings.Hidden = hidden
# Settings: Conditions Tab (Idle)
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa380669(v=vs.85).aspx
if run_if_idle is not None:
task_definition.Settings.RunOnlyIfIdle = run_if_idle
if task_definition.Settings.RunOnlyIfIdle:
if idle_stop_on_end is not None:
task_definition.Settings.IdleSettings.StopOnIdleEnd = idle_stop_on_end
if idle_restart is not None:
task_definition.Settings.IdleSettings.RestartOnIdle = idle_restart
if idle_duration is not None:
if idle_duration in duration:
task_definition.Settings.IdleSettings.IdleDuration = _lookup_first(duration, idle_duration)
else:
return 'Invalid value for "idle_duration"'
if idle_wait_timeout is not None:
if idle_wait_timeout in duration:
task_definition.Settings.IdleSettings.WaitTimeout = _lookup_first(duration, idle_wait_timeout)
else:
return 'Invalid value for "idle_wait_timeout"'
# Settings: Conditions Tab (Power)
if ac_only is not None:
task_definition.Settings.DisallowStartIfOnBatteries = ac_only
if stop_if_on_batteries is not None:
task_definition.Settings.StopIfGoingOnBatteries = stop_if_on_batteries
if wake_to_run is not None:
task_definition.Settings.WakeToRun = wake_to_run
# Settings: Conditions Tab (Network)
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa382067(v=vs.85).aspx
if run_if_network is not None:
task_definition.Settings.RunOnlyIfNetworkAvailable = run_if_network
if task_definition.Settings.RunOnlyIfNetworkAvailable:
if network_id:
task_definition.Settings.NetworkSettings.Id = network_id
if network_name:
task_definition.Settings.NetworkSettings.Name = network_name
# Settings: Settings Tab
if allow_demand_start is not None:
task_definition.Settings.AllowDemandStart = allow_demand_start
if start_when_available is not None:
task_definition.Settings.StartWhenAvailable = start_when_available
if restart_every is not None:
if restart_every is False:
task_definition.Settings.RestartInterval = ''
else:
if restart_every in duration:
task_definition.Settings.RestartInterval = _lookup_first(duration, restart_every)
else:
return 'Invalid value for "restart_every"'
if task_definition.Settings.RestartInterval:
if restart_count is not None:
if restart_count in range(1, 999):
task_definition.Settings.RestartCount = restart_count
else:
return '"restart_count" must be a value between 1 and 999'
if execution_time_limit is not None:
if execution_time_limit is False:
task_definition.Settings.ExecutionTimeLimit = 'PT0S'
else:
if execution_time_limit in duration:
task_definition.Settings.ExecutionTimeLimit = _lookup_first(duration, execution_time_limit)
else:
return 'Invalid value for "execution_time_limit"'
if force_stop is not None:
task_definition.Settings.AllowHardTerminate = force_stop
if delete_after is not None:
# TODO: Check triggers for end_boundary
if delete_after is False:
task_definition.Settings.DeleteExpiredTaskAfter = ''
if delete_after in duration:
task_definition.Settings.DeleteExpiredTaskAfter = _lookup_first(duration, delete_after)
else:
return 'Invalid value for "delete_after"'
if multiple_instances is not None:
task_definition.Settings.MultipleInstances = instances[multiple_instances]
# Save the task
if save_definition:
# Save the Changes
return _save_task_definition(name=name,
task_folder=task_folder,
task_definition=task_definition,
user_name=user_name,
password=password,
logon_type=task_definition.Principal.LogonType) | [
"def",
"edit_task",
"(",
"name",
"=",
"None",
",",
"location",
"=",
"'\\\\'",
",",
"# General Tab",
"user_name",
"=",
"None",
",",
"password",
"=",
"None",
",",
"description",
"=",
"None",
",",
"enabled",
"=",
"None",
",",
"hidden",
"=",
"None",
",",
"... | r'''
Edit the parameters of a task. Triggers and Actions cannot be edited yet.
:param str name: The name of the task. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the task. Default is '\\' which is the root for the task
scheduler (C:\Windows\System32\tasks).
:param str user_name: The user account under which to run the task. To
specify the 'System' account, use 'System'. The password will be
ignored.
:param str password: The password to use for authentication. This should set
the task to run whether the user is logged in or not, but is currently
not working.
.. note::
The combination of user_name and password determine how the task runs.
For example, if a username is passed without at password the task will
only run when the user is logged in. If a password is passed as well
the task will run whether the user is logged on or not. If you pass
'System' as the username the task will run as the system account (the
password parameter is ignored.
:param str description: A string representing the text that will be
displayed in the description field in the task scheduler.
:param bool enabled: A boolean value representing whether or not the task is
enabled.
:param bool hidden: A boolean value representing whether or not the task is
hidden.
:param bool run_if_idle: Boolean value that indicates that the Task
Scheduler will run the task only if the computer is in an idle state.
:param str idle_duration: A value that indicates the amount of time that the
computer must be in an idle state before the task is run. Valid values
are:
- 1 minute
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
:param str idle_wait_timeout: A value that indicates the amount of time that
the Task Scheduler will wait for an idle condition to occur. Valid
values are:
- Do not wait
- 1 minute
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
- 2 hours
:param bool idle_stop_on_end: Boolean value that indicates that the Task
Scheduler will terminate the task if the idle condition ends before the
task is completed.
:param bool idle_restart: Boolean value that indicates whether the task is
restarted when the computer cycles into an idle condition more than
once.
:param bool ac_only: Boolean value that indicates that the Task Scheduler
will launch the task only while on AC power.
:param bool stop_if_on_batteries: Boolean value that indicates that the task
will be stopped if the computer begins to run on battery power.
:param bool wake_to_run: Boolean value that indicates that the Task
Scheduler will wake the computer when it is time to run the task.
:param bool run_if_network: Boolean value that indicates that the Task
Scheduler will run the task only when a network is available.
:param guid network_id: GUID value that identifies a network profile.
:param str network_name: Sets the name of a network profile. The name is
used for display purposes.
:param bool allow_demand_start: Boolean value that indicates that the task
can be started by using either the Run command or the Context menu.
:param bool start_when_available: Boolean value that indicates that the Task
Scheduler can start the task at any time after its scheduled time has
passed.
:param restart_every: A value that specifies the interval between task
restart attempts. Valid values are:
- False (to disable)
- 1 minute
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
- 2 hours
:param int restart_count: The number of times the Task Scheduler will
attempt to restart the task. Valid values are integers 1 - 999.
:param execution_time_limit: The amount of time allowed to complete the
task. Valid values are:
- False (to disable)
- 1 hour
- 2 hours
- 4 hours
- 8 hours
- 12 hours
- 1 day
- 3 days
:param bool force_stop: Boolean value that indicates that the task may be
terminated by using TerminateProcess.
:param delete_after: The amount of time that the Task Scheduler will
wait before deleting the task after it expires. Requires a trigger with
an expiration date. Valid values are:
- False (to disable)
- Immediately
- 30 days
- 90 days
- 180 days
- 365 days
:param str multiple_instances: Sets the policy that defines how the Task
Scheduler deals with multiple instances of the task. Valid values are:
- Parallel
- Queue
- No New Instance
- Stop Existing
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.edit_task <task_name> description='This task is awesome' | [
"r",
"Edit",
"the",
"parameters",
"of",
"a",
"task",
".",
"Triggers",
"and",
"Actions",
"cannot",
"be",
"edited",
"yet",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L719-L1058 | train |
saltstack/salt | salt/modules/win_task.py | delete_task | def delete_task(name, location='\\'):
r'''
Delete a task from the task scheduler.
:param str name: The name of the task to delete.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.delete_task <task_name>
'''
# Check for existing task
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to delete the task from
task_folder = task_service.GetFolder(location)
task_folder.DeleteTask(name, 0)
# Verify deletion
if name not in list_tasks(location):
return True
else:
return False | python | def delete_task(name, location='\\'):
r'''
Delete a task from the task scheduler.
:param str name: The name of the task to delete.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.delete_task <task_name>
'''
# Check for existing task
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to delete the task from
task_folder = task_service.GetFolder(location)
task_folder.DeleteTask(name, 0)
# Verify deletion
if name not in list_tasks(location):
return True
else:
return False | [
"def",
"delete_task",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing task",
"if",
"name",
"not",
"in",
"list_tasks",
"(",
"location",
")",
":",
"return",
"'{0} not found in {1}'",
".",
"format",
"(",
"name",
",",
"location",
")",
... | r'''
Delete a task from the task scheduler.
:param str name: The name of the task to delete.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.delete_task <task_name> | [
"r",
"Delete",
"a",
"task",
"from",
"the",
"task",
"scheduler",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L1061-L1098 | train |
saltstack/salt | salt/modules/win_task.py | run | def run(name, location='\\'):
r'''
Run a scheduled task manually.
:param str name: The name of the task to run.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_run <task_name>
'''
# Check for existing folder
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to delete the folder from
task_folder = task_service.GetFolder(location)
task = task_folder.GetTask(name)
try:
task.Run('')
return True
except pythoncom.com_error as error:
return False | python | def run(name, location='\\'):
r'''
Run a scheduled task manually.
:param str name: The name of the task to run.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_run <task_name>
'''
# Check for existing folder
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to delete the folder from
task_folder = task_service.GetFolder(location)
task = task_folder.GetTask(name)
try:
task.Run('')
return True
except pythoncom.com_error as error:
return False | [
"def",
"run",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing folder",
"if",
"name",
"not",
"in",
"list_tasks",
"(",
"location",
")",
":",
"return",
"'{0} not found in {1}'",
".",
"format",
"(",
"name",
",",
"location",
")",
"# c... | r'''
Run a scheduled task manually.
:param str name: The name of the task to run.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_run <task_name> | [
"r",
"Run",
"a",
"scheduled",
"task",
"manually",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L1142-L1178 | train |
saltstack/salt | salt/modules/win_task.py | run_wait | def run_wait(name, location='\\'):
r'''
Run a scheduled task and return when the task finishes
:param str name: The name of the task to run.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_run_wait <task_name>
'''
# Check for existing folder
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to delete the folder from
task_folder = task_service.GetFolder(location)
task = task_folder.GetTask(name)
# Is the task already running
if task.State == TASK_STATE_RUNNING:
return 'Task already running'
try:
task.Run('')
time.sleep(1)
running = True
except pythoncom.com_error:
return False
while running:
running = False
try:
running_tasks = task_service.GetRunningTasks(0)
if running_tasks.Count:
for item in running_tasks:
if item.Name == name:
running = True
except pythoncom.com_error:
running = False
return True | python | def run_wait(name, location='\\'):
r'''
Run a scheduled task and return when the task finishes
:param str name: The name of the task to run.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_run_wait <task_name>
'''
# Check for existing folder
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to delete the folder from
task_folder = task_service.GetFolder(location)
task = task_folder.GetTask(name)
# Is the task already running
if task.State == TASK_STATE_RUNNING:
return 'Task already running'
try:
task.Run('')
time.sleep(1)
running = True
except pythoncom.com_error:
return False
while running:
running = False
try:
running_tasks = task_service.GetRunningTasks(0)
if running_tasks.Count:
for item in running_tasks:
if item.Name == name:
running = True
except pythoncom.com_error:
running = False
return True | [
"def",
"run_wait",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing folder",
"if",
"name",
"not",
"in",
"list_tasks",
"(",
"location",
")",
":",
"return",
"'{0} not found in {1}'",
".",
"format",
"(",
"name",
",",
"location",
")",
... | r'''
Run a scheduled task and return when the task finishes
:param str name: The name of the task to run.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_run_wait <task_name> | [
"r",
"Run",
"a",
"scheduled",
"task",
"and",
"return",
"when",
"the",
"task",
"finishes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L1181-L1235 | train |
saltstack/salt | salt/modules/win_task.py | status | def status(name, location='\\'):
r'''
Determine the status of a task. Is it Running, Queued, Ready, etc.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: The current status of the task. Will be one of the following:
- Unknown
- Disabled
- Queued
- Ready
- Running
:rtype: string
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_status <task_name>
'''
# Check for existing folder
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder where the task is defined
task_folder = task_service.GetFolder(location)
task = task_folder.GetTask(name)
return states[task.State] | python | def status(name, location='\\'):
r'''
Determine the status of a task. Is it Running, Queued, Ready, etc.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: The current status of the task. Will be one of the following:
- Unknown
- Disabled
- Queued
- Ready
- Running
:rtype: string
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_status <task_name>
'''
# Check for existing folder
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder where the task is defined
task_folder = task_service.GetFolder(location)
task = task_folder.GetTask(name)
return states[task.State] | [
"def",
"status",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing folder",
"if",
"name",
"not",
"in",
"list_tasks",
"(",
"location",
")",
":",
"return",
"'{0} not found in {1}'",
".",
"format",
"(",
"name",
",",
"location",
")",
"... | r'''
Determine the status of a task. Is it Running, Queued, Ready, etc.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: The current status of the task. Will be one of the following:
- Unknown
- Disabled
- Queued
- Ready
- Running
:rtype: string
CLI Example:
.. code-block:: bash
salt 'minion-id' task.list_status <task_name> | [
"r",
"Determine",
"the",
"status",
"of",
"a",
"task",
".",
"Is",
"it",
"Running",
"Queued",
"Ready",
"etc",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L1277-L1316 | train |
saltstack/salt | salt/modules/win_task.py | info | def info(name, location='\\'):
r'''
Get the details about a task in the task scheduler.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return:
:rtype: dict
CLI Example:
.. code-block:: bash
salt 'minion-id' task.info <task_name>
'''
# Check for existing folder
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to delete the folder from
task_folder = task_service.GetFolder(location)
task = task_folder.GetTask(name)
properties = {'enabled': task.Enabled,
'last_run': _get_date_value(task.LastRunTime),
'last_run_result': show_win32api_code(task.LastTaskResult),
'missed_runs': task.NumberOfMissedRuns,
'next_run': _get_date_value(task.NextRunTime),
'status': states[task.State]}
def_set = task.Definition.Settings
settings = {}
settings['allow_demand_start'] = def_set.AllowDemandStart
settings['force_stop'] = def_set.AllowHardTerminate
if def_set.DeleteExpiredTaskAfter == '':
settings['delete_after'] = False
elif def_set.DeleteExpiredTaskAfter == 'PT0S':
settings['delete_after'] = 'Immediately'
else:
settings['delete_after'] = _reverse_lookup(duration, def_set.DeleteExpiredTaskAfter)
if def_set.ExecutionTimeLimit == '':
settings['execution_time_limit'] = False
else:
settings['execution_time_limit'] = _reverse_lookup(duration, def_set.ExecutionTimeLimit)
settings['multiple_instances'] = _reverse_lookup(instances, def_set.MultipleInstances)
if def_set.RestartInterval == '':
settings['restart_interval'] = False
else:
settings['restart_interval'] = _reverse_lookup(duration, def_set.RestartInterval)
if settings['restart_interval']:
settings['restart_count'] = def_set.RestartCount
settings['stop_if_on_batteries'] = def_set.StopIfGoingOnBatteries
settings['wake_to_run'] = def_set.WakeToRun
conditions = {}
conditions['ac_only'] = def_set.DisallowStartIfOnBatteries
conditions['run_if_idle'] = def_set.RunOnlyIfIdle
conditions['run_if_network'] = def_set.RunOnlyIfNetworkAvailable
conditions['start_when_available'] = def_set.StartWhenAvailable
if conditions['run_if_idle']:
idle_set = def_set.IdleSettings
conditions['idle_duration'] = idle_set.IdleDuration
conditions['idle_restart'] = idle_set.RestartOnIdle
conditions['idle_stop_on_end'] = idle_set.StopOnIdleEnd
conditions['idle_wait_timeout'] = idle_set.WaitTimeout
if conditions['run_if_network']:
net_set = def_set.NetworkSettings
conditions['network_id'] = net_set.Id
conditions['network_name'] = net_set.Name
actions = []
for actionObj in task.Definition.Actions:
action = {}
action['action_type'] = _reverse_lookup(action_types, actionObj.Type)
if actionObj.Path:
action['cmd'] = actionObj.Path
if actionObj.Arguments:
action['arguments'] = actionObj.Arguments
if actionObj.WorkingDirectory:
action['working_dir'] = actionObj.WorkingDirectory
actions.append(action)
triggers = []
for triggerObj in task.Definition.Triggers:
trigger = {}
trigger['trigger_type'] = _reverse_lookup(trigger_types, triggerObj.Type)
if triggerObj.ExecutionTimeLimit:
trigger['execution_time_limit'] = _reverse_lookup(duration, triggerObj.ExecutionTimeLimit)
if triggerObj.StartBoundary:
start_date, start_time = triggerObj.StartBoundary.split('T', 1)
trigger['start_date'] = start_date
trigger['start_time'] = start_time
if triggerObj.EndBoundary:
end_date, end_time = triggerObj.EndBoundary.split('T', 1)
trigger['end_date'] = end_date
trigger['end_time'] = end_time
trigger['enabled'] = triggerObj.Enabled
if hasattr(triggerObj, 'RandomDelay'):
if triggerObj.RandomDelay:
trigger['random_delay'] = _reverse_lookup(duration, triggerObj.RandomDelay)
else:
trigger['random_delay'] = False
if hasattr(triggerObj, 'Delay'):
if triggerObj.Delay:
trigger['delay'] = _reverse_lookup(duration, triggerObj.Delay)
else:
trigger['delay'] = False
triggers.append(trigger)
properties['settings'] = settings
properties['conditions'] = conditions
properties['actions'] = actions
properties['triggers'] = triggers
ret = properties
return ret | python | def info(name, location='\\'):
r'''
Get the details about a task in the task scheduler.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return:
:rtype: dict
CLI Example:
.. code-block:: bash
salt 'minion-id' task.info <task_name>
'''
# Check for existing folder
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to delete the folder from
task_folder = task_service.GetFolder(location)
task = task_folder.GetTask(name)
properties = {'enabled': task.Enabled,
'last_run': _get_date_value(task.LastRunTime),
'last_run_result': show_win32api_code(task.LastTaskResult),
'missed_runs': task.NumberOfMissedRuns,
'next_run': _get_date_value(task.NextRunTime),
'status': states[task.State]}
def_set = task.Definition.Settings
settings = {}
settings['allow_demand_start'] = def_set.AllowDemandStart
settings['force_stop'] = def_set.AllowHardTerminate
if def_set.DeleteExpiredTaskAfter == '':
settings['delete_after'] = False
elif def_set.DeleteExpiredTaskAfter == 'PT0S':
settings['delete_after'] = 'Immediately'
else:
settings['delete_after'] = _reverse_lookup(duration, def_set.DeleteExpiredTaskAfter)
if def_set.ExecutionTimeLimit == '':
settings['execution_time_limit'] = False
else:
settings['execution_time_limit'] = _reverse_lookup(duration, def_set.ExecutionTimeLimit)
settings['multiple_instances'] = _reverse_lookup(instances, def_set.MultipleInstances)
if def_set.RestartInterval == '':
settings['restart_interval'] = False
else:
settings['restart_interval'] = _reverse_lookup(duration, def_set.RestartInterval)
if settings['restart_interval']:
settings['restart_count'] = def_set.RestartCount
settings['stop_if_on_batteries'] = def_set.StopIfGoingOnBatteries
settings['wake_to_run'] = def_set.WakeToRun
conditions = {}
conditions['ac_only'] = def_set.DisallowStartIfOnBatteries
conditions['run_if_idle'] = def_set.RunOnlyIfIdle
conditions['run_if_network'] = def_set.RunOnlyIfNetworkAvailable
conditions['start_when_available'] = def_set.StartWhenAvailable
if conditions['run_if_idle']:
idle_set = def_set.IdleSettings
conditions['idle_duration'] = idle_set.IdleDuration
conditions['idle_restart'] = idle_set.RestartOnIdle
conditions['idle_stop_on_end'] = idle_set.StopOnIdleEnd
conditions['idle_wait_timeout'] = idle_set.WaitTimeout
if conditions['run_if_network']:
net_set = def_set.NetworkSettings
conditions['network_id'] = net_set.Id
conditions['network_name'] = net_set.Name
actions = []
for actionObj in task.Definition.Actions:
action = {}
action['action_type'] = _reverse_lookup(action_types, actionObj.Type)
if actionObj.Path:
action['cmd'] = actionObj.Path
if actionObj.Arguments:
action['arguments'] = actionObj.Arguments
if actionObj.WorkingDirectory:
action['working_dir'] = actionObj.WorkingDirectory
actions.append(action)
triggers = []
for triggerObj in task.Definition.Triggers:
trigger = {}
trigger['trigger_type'] = _reverse_lookup(trigger_types, triggerObj.Type)
if triggerObj.ExecutionTimeLimit:
trigger['execution_time_limit'] = _reverse_lookup(duration, triggerObj.ExecutionTimeLimit)
if triggerObj.StartBoundary:
start_date, start_time = triggerObj.StartBoundary.split('T', 1)
trigger['start_date'] = start_date
trigger['start_time'] = start_time
if triggerObj.EndBoundary:
end_date, end_time = triggerObj.EndBoundary.split('T', 1)
trigger['end_date'] = end_date
trigger['end_time'] = end_time
trigger['enabled'] = triggerObj.Enabled
if hasattr(triggerObj, 'RandomDelay'):
if triggerObj.RandomDelay:
trigger['random_delay'] = _reverse_lookup(duration, triggerObj.RandomDelay)
else:
trigger['random_delay'] = False
if hasattr(triggerObj, 'Delay'):
if triggerObj.Delay:
trigger['delay'] = _reverse_lookup(duration, triggerObj.Delay)
else:
trigger['delay'] = False
triggers.append(trigger)
properties['settings'] = settings
properties['conditions'] = conditions
properties['actions'] = actions
properties['triggers'] = triggers
ret = properties
return ret | [
"def",
"info",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing folder",
"if",
"name",
"not",
"in",
"list_tasks",
"(",
"location",
")",
":",
"return",
"'{0} not found in {1}'",
".",
"format",
"(",
"name",
",",
"location",
")",
"# ... | r'''
Get the details about a task in the task scheduler.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return:
:rtype: dict
CLI Example:
.. code-block:: bash
salt 'minion-id' task.info <task_name> | [
"r",
"Get",
"the",
"details",
"about",
"a",
"task",
"in",
"the",
"task",
"scheduler",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L1319-L1451 | train |
saltstack/salt | salt/modules/win_task.py | add_action | def add_action(name=None,
location='\\',
action_type='Execute',
**kwargs):
r'''
Add an action to a task.
:param str name: The name of the task to which to add the action.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:param str action_type: The type of action to add. There are three action
types. Each one requires its own set of Keyword Arguments (kwargs). Valid
values are:
- Execute
- Email
- Message
Required arguments for each action_type:
**Execute** - Execute a command or an executable
:param str cmd: (required) The command / executable to run.
:param str arguments: (optional) Arguments to be passed to the command /
executable. To launch a script the first command will need to be the
interpreter for the script. For example, to run a vbscript you would
pass `cscript.exe` in the `cmd` parameter and pass the script in the
`arguments` parameter as follows:
- ``cmd='cscript.exe' arguments='c:\scripts\myscript.vbs'``
Batch files do not need an interpreter and may be passed to the cmd
parameter directly.
:param str start_in: (optional) The current working directory for the
command.
**Email** - Send and email. Requires ``server``, ``from``, and ``to`` or
``cc``.
:param str from: The sender
:param str reply_to: Who to reply to
:param str to: The recipient
:param str cc: The CC recipient
:param str bcc: The BCC recipient
:param str subject: The subject of the email
:param str body: The Message Body of the email
:param str server: The server used to send the email
:param list attachments: A list of attachments. These will be the paths to
the files to attach. ie: ``attachments="['C:\attachment1.txt',
'C:\attachment2.txt']"``
**Message** - Display a dialog box. The task must be set to "Run only when
user is logged on" in order for the dialog box to display. Both parameters
are required.
:param str title: The dialog box title.
:param str message: The dialog box message body
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.add_action <task_name> cmd='del /Q /S C:\\Temp'
'''
save_definition = False
if kwargs.get('task_definition', False):
task_definition = kwargs.get('task_definition')
else:
save_definition = True
# Make sure a name was passed
if not name:
return 'Required parameter "name" not passed'
# Make sure task exists
if name in list_tasks(location):
# Connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to create the task in
task_folder = task_service.GetFolder(location)
# Connect to an existing task definition
task_definition = task_folder.GetTask(name).Definition
else:
# Not found and create_new not set, return not found
return '{0} not found'.format(name)
# Action Settings
task_action = task_definition.Actions.Create(action_types[action_type])
if action_types[action_type] == TASK_ACTION_EXEC:
task_action.Id = 'Execute_ID1'
if kwargs.get('cmd', False):
task_action.Path = kwargs.get('cmd')
else:
return 'Required parameter "cmd" not found'
task_action.Arguments = kwargs.get('arguments', '')
task_action.WorkingDirectory = kwargs.get('start_in', '')
elif action_types[action_type] == TASK_ACTION_SEND_EMAIL:
task_action.Id = 'Email_ID1'
# Required Parameters
if kwargs.get('server', False):
task_action.Server = kwargs.get('server')
else:
return 'Required parameter "server" not found'
if kwargs.get('from', False):
task_action.From = kwargs.get('from')
else:
return 'Required parameter "from" not found'
if kwargs.get('to', False) or kwargs.get('cc', False):
if kwargs.get('to'):
task_action.To = kwargs.get('to')
if kwargs.get('cc'):
task_action.Cc = kwargs.get('cc')
else:
return 'Required parameter "to" or "cc" not found'
# Optional Parameters
if kwargs.get('reply_to'):
task_action.ReplyTo = kwargs.get('reply_to')
if kwargs.get('bcc'):
task_action.Bcc = kwargs.get('bcc')
if kwargs.get('subject'):
task_action.Subject = kwargs.get('subject')
if kwargs.get('body'):
task_action.Body = kwargs.get('body')
if kwargs.get('attachments'):
task_action.Attachments = kwargs.get('attachments')
elif action_types[action_type] == TASK_ACTION_SHOW_MESSAGE:
task_action.Id = 'Message_ID1'
if kwargs.get('title', False):
task_action.Title = kwargs.get('title')
else:
return 'Required parameter "title" not found'
if kwargs.get('message', False):
task_action.MessageBody = kwargs.get('message')
else:
return 'Required parameter "message" not found'
# Save the task
if save_definition:
# Save the Changes
return _save_task_definition(name=name,
task_folder=task_folder,
task_definition=task_definition,
user_name=task_definition.Principal.UserID,
password=None,
logon_type=task_definition.Principal.LogonType) | python | def add_action(name=None,
location='\\',
action_type='Execute',
**kwargs):
r'''
Add an action to a task.
:param str name: The name of the task to which to add the action.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:param str action_type: The type of action to add. There are three action
types. Each one requires its own set of Keyword Arguments (kwargs). Valid
values are:
- Execute
- Email
- Message
Required arguments for each action_type:
**Execute** - Execute a command or an executable
:param str cmd: (required) The command / executable to run.
:param str arguments: (optional) Arguments to be passed to the command /
executable. To launch a script the first command will need to be the
interpreter for the script. For example, to run a vbscript you would
pass `cscript.exe` in the `cmd` parameter and pass the script in the
`arguments` parameter as follows:
- ``cmd='cscript.exe' arguments='c:\scripts\myscript.vbs'``
Batch files do not need an interpreter and may be passed to the cmd
parameter directly.
:param str start_in: (optional) The current working directory for the
command.
**Email** - Send and email. Requires ``server``, ``from``, and ``to`` or
``cc``.
:param str from: The sender
:param str reply_to: Who to reply to
:param str to: The recipient
:param str cc: The CC recipient
:param str bcc: The BCC recipient
:param str subject: The subject of the email
:param str body: The Message Body of the email
:param str server: The server used to send the email
:param list attachments: A list of attachments. These will be the paths to
the files to attach. ie: ``attachments="['C:\attachment1.txt',
'C:\attachment2.txt']"``
**Message** - Display a dialog box. The task must be set to "Run only when
user is logged on" in order for the dialog box to display. Both parameters
are required.
:param str title: The dialog box title.
:param str message: The dialog box message body
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.add_action <task_name> cmd='del /Q /S C:\\Temp'
'''
save_definition = False
if kwargs.get('task_definition', False):
task_definition = kwargs.get('task_definition')
else:
save_definition = True
# Make sure a name was passed
if not name:
return 'Required parameter "name" not passed'
# Make sure task exists
if name in list_tasks(location):
# Connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to create the task in
task_folder = task_service.GetFolder(location)
# Connect to an existing task definition
task_definition = task_folder.GetTask(name).Definition
else:
# Not found and create_new not set, return not found
return '{0} not found'.format(name)
# Action Settings
task_action = task_definition.Actions.Create(action_types[action_type])
if action_types[action_type] == TASK_ACTION_EXEC:
task_action.Id = 'Execute_ID1'
if kwargs.get('cmd', False):
task_action.Path = kwargs.get('cmd')
else:
return 'Required parameter "cmd" not found'
task_action.Arguments = kwargs.get('arguments', '')
task_action.WorkingDirectory = kwargs.get('start_in', '')
elif action_types[action_type] == TASK_ACTION_SEND_EMAIL:
task_action.Id = 'Email_ID1'
# Required Parameters
if kwargs.get('server', False):
task_action.Server = kwargs.get('server')
else:
return 'Required parameter "server" not found'
if kwargs.get('from', False):
task_action.From = kwargs.get('from')
else:
return 'Required parameter "from" not found'
if kwargs.get('to', False) or kwargs.get('cc', False):
if kwargs.get('to'):
task_action.To = kwargs.get('to')
if kwargs.get('cc'):
task_action.Cc = kwargs.get('cc')
else:
return 'Required parameter "to" or "cc" not found'
# Optional Parameters
if kwargs.get('reply_to'):
task_action.ReplyTo = kwargs.get('reply_to')
if kwargs.get('bcc'):
task_action.Bcc = kwargs.get('bcc')
if kwargs.get('subject'):
task_action.Subject = kwargs.get('subject')
if kwargs.get('body'):
task_action.Body = kwargs.get('body')
if kwargs.get('attachments'):
task_action.Attachments = kwargs.get('attachments')
elif action_types[action_type] == TASK_ACTION_SHOW_MESSAGE:
task_action.Id = 'Message_ID1'
if kwargs.get('title', False):
task_action.Title = kwargs.get('title')
else:
return 'Required parameter "title" not found'
if kwargs.get('message', False):
task_action.MessageBody = kwargs.get('message')
else:
return 'Required parameter "message" not found'
# Save the task
if save_definition:
# Save the Changes
return _save_task_definition(name=name,
task_folder=task_folder,
task_definition=task_definition,
user_name=task_definition.Principal.UserID,
password=None,
logon_type=task_definition.Principal.LogonType) | [
"def",
"add_action",
"(",
"name",
"=",
"None",
",",
"location",
"=",
"'\\\\'",
",",
"action_type",
"=",
"'Execute'",
",",
"*",
"*",
"kwargs",
")",
":",
"save_definition",
"=",
"False",
"if",
"kwargs",
".",
"get",
"(",
"'task_definition'",
",",
"False",
"... | r'''
Add an action to a task.
:param str name: The name of the task to which to add the action.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:param str action_type: The type of action to add. There are three action
types. Each one requires its own set of Keyword Arguments (kwargs). Valid
values are:
- Execute
- Email
- Message
Required arguments for each action_type:
**Execute** - Execute a command or an executable
:param str cmd: (required) The command / executable to run.
:param str arguments: (optional) Arguments to be passed to the command /
executable. To launch a script the first command will need to be the
interpreter for the script. For example, to run a vbscript you would
pass `cscript.exe` in the `cmd` parameter and pass the script in the
`arguments` parameter as follows:
- ``cmd='cscript.exe' arguments='c:\scripts\myscript.vbs'``
Batch files do not need an interpreter and may be passed to the cmd
parameter directly.
:param str start_in: (optional) The current working directory for the
command.
**Email** - Send and email. Requires ``server``, ``from``, and ``to`` or
``cc``.
:param str from: The sender
:param str reply_to: Who to reply to
:param str to: The recipient
:param str cc: The CC recipient
:param str bcc: The BCC recipient
:param str subject: The subject of the email
:param str body: The Message Body of the email
:param str server: The server used to send the email
:param list attachments: A list of attachments. These will be the paths to
the files to attach. ie: ``attachments="['C:\attachment1.txt',
'C:\attachment2.txt']"``
**Message** - Display a dialog box. The task must be set to "Run only when
user is logged on" in order for the dialog box to display. Both parameters
are required.
:param str title: The dialog box title.
:param str message: The dialog box message body
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.add_action <task_name> cmd='del /Q /S C:\\Temp' | [
"r",
"Add",
"an",
"action",
"to",
"a",
"task",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L1454-L1619 | train |
saltstack/salt | salt/modules/win_task.py | add_trigger | def add_trigger(name=None,
location='\\',
trigger_type=None,
trigger_enabled=True,
start_date=None,
start_time=None,
end_date=None,
end_time=None,
random_delay=None,
repeat_interval=None,
repeat_duration=None,
repeat_stop_at_duration_end=False,
execution_time_limit=None,
delay=None,
**kwargs):
r'''
:param str name: The name of the task to which to add the trigger.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:param str trigger_type: The type of trigger to create. This is defined
when the trigger is created and cannot be changed later. Options are as
follows:
- Event
- Once
- Daily
- Weekly
- Monthly
- MonthlyDay
- OnIdle
- OnTaskCreation
- OnBoot
- OnLogon
- OnSessionChange
:param bool trigger_enabled: Boolean value that indicates whether the
trigger is enabled.
:param str start_date: The date when the trigger is activated. If no value
is passed, the current date will be used. Can be one of the following
formats:
- %Y-%m-%d
- %m-%d-%y
- %m-%d-%Y
- %m/%d/%y
- %m/%d/%Y
- %Y/%m/%d
:param str start_time: The time when the trigger is activated. If no value
is passed, midnight will be used. Can be one of the following formats:
- %I:%M:%S %p
- %I:%M %p
- %H:%M:%S
- %H:%M
:param str end_date: The date when the trigger is deactivated. The trigger
cannot start the task after it is deactivated. Can be one of the
following formats:
- %Y-%m-%d
- %m-%d-%y
- %m-%d-%Y
- %m/%d/%y
- %m/%d/%Y
- %Y/%m/%d
:param str end_time: The time when the trigger is deactivated. If the this
is not passed with ``end_date`` it will be set to midnight. Can be one
of the following formats:
- %I:%M:%S %p
- %I:%M %p
- %H:%M:%S
- %H:%M
:param str random_delay: The delay time that is randomly added to the start
time of the trigger. Valid values are:
- 30 seconds
- 1 minute
- 30 minutes
- 1 hour
- 8 hours
- 1 day
:param str repeat_interval: The amount of time between each restart of the
task. Valid values are:
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
:param str repeat_duration: How long the pattern is repeated. Valid values
are:
- Indefinitely
- 15 minutes
- 30 minutes
- 1 hour
- 12 hours
- 1 day
:param bool repeat_stop_at_duration_end: Boolean value that indicates if a
running instance of the task is stopped at the end of the repetition
pattern duration.
:param str execution_time_limit: The maximum amount of time that the task
launched by the trigger is allowed to run. Valid values are:
- 30 minutes
- 1 hour
- 2 hours
- 4 hours
- 8 hours
- 12 hours
- 1 day
- 3 days (default)
:param str delay: The time the trigger waits after its activation to start the task.
Valid values are:
- 15 seconds
- 30 seconds
- 1 minute
- 30 minutes
- 1 hour
- 8 hours
- 1 day
**kwargs**
There are optional keyword arguments determined by the type of trigger
being defined. They are as follows:
*Event*
:param str subscription: An event definition in xml format that fires the
trigger. The easiest way to get this would is to create an event in
windows task scheduler and then copy the xml text.
*Once*
No special parameters required.
*Daily*
:param int days_interval: The interval between days in the schedule. An
interval of 1 produces a daily schedule. An interval of 2 produces an
every-other day schedule. If no interval is specified, 1 is used. Valid
entries are 1 - 999.
*Weekly*
:param int weeks_interval: The interval between weeks in the schedule.
An interval of 1 produces a weekly schedule. An interval of 2 produces
an every-other week schedule. If no interval is specified, 1 is used.
Valid entries are 1 - 52.
param list days_of_week: Sets the days of the week on which the task
runs. Should be a list. ie: ['Monday','Wednesday','Friday']. Valid
entries are the names of the days of the week.
*Monthly*
:param list months_of_year: Sets the months of the year during which the
task runs. Should be a list. ie: ['January','July']. Valid entries are
the full names of all the months.
:param list days_of_month: Sets the days of the month during which the
task runs. Should be a list. ie: [1, 15, 'Last']. Options are all days
of the month 1 - 31 and the word 'Last' to indicate the last day of the
month.
:param bool last_day_of_month: Boolean value that indicates that the
task runs on the last day of the month regardless of the actual date of
that day.
You can set the task to run on the last day of the month by either
including the word 'Last' in the list of days, or setting the parameter
'last_day_of_month` equal to True.
*MonthlyDay*
:param list months_of_year: Sets the months of the year during which the
task runs. Should be a list. ie: ['January','July']. Valid entries are
the full names of all the months.
:param list weeks_of_month: Sets the weeks of the month during which the
task runs. Should be a list. ie: ['First','Third']. Valid options are:
- First
- Second
- Third
- Fourth
:param bool last_week_of_month: Boolean value that indicates that the task
runs on the last week of the month.
:param list days_of_week: Sets the days of the week during which the task
runs. Should be a list. ie: ['Monday','Wednesday','Friday']. Valid
entries are the names of the days of the week.
*OnIdle*
No special parameters required.
*OnTaskCreation*
No special parameters required.
*OnBoot*
No special parameters required.
*OnLogon*
No special parameters required.
*OnSessionChange*
:param str session_user_name: Sets the user for the Terminal Server
session. When a session state change is detected for this user, a task
is started. To detect session status change for any user, do not pass
this parameter.
:param str state_change: Sets the kind of Terminal Server session change
that would trigger a task launch. Valid options are:
- ConsoleConnect: When you connect to a user session (switch users)
- ConsoleDisconnect: When you disconnect a user session (switch users)
- RemoteConnect: When a user connects via Remote Desktop
- RemoteDisconnect: When a user disconnects via Remote Desktop
- SessionLock: When the workstation is locked
- SessionUnlock: When the workstation is unlocked
.. note::
Arguments are parsed by the YAML loader and are subject to yaml's
idiosyncrasies. Therefore, time values in some formats (``%H:%M:%S`` and
``%H:%M``) should to be quoted. See `YAML IDIOSYNCRASIES`_ for more details.
.. _`YAML IDIOSYNCRASIES`: https://docs.saltstack.com/en/latest/topics/troubleshooting/yaml_idiosyncrasies.html#time-expressions
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.add_trigger <task_name> trigger_type=Once trigger_enabled=True start_date=2016/12/1 start_time='"12:01"'
'''
if not trigger_type:
return 'Required parameter "trigger_type" not specified'
# Define lookup dictionaries
state_changes = {'ConsoleConnect': 1,
'ConsoleDisconnect': 2,
'RemoteConnect': 3,
'RemoteDisconnect': 4,
'SessionLock': 7,
'SessionUnlock': 8}
days = {1: 0x1,
2: 0x2,
3: 0x4,
4: 0x8,
5: 0x10,
6: 0x20,
7: 0x40,
8: 0x80,
9: 0x100,
10: 0x200,
11: 0x400,
12: 0x800,
13: 0x1000,
14: 0x2000,
15: 0x4000,
16: 0x8000,
17: 0x10000,
18: 0x20000,
19: 0x40000,
20: 0x80000,
21: 0x100000,
22: 0x200000,
23: 0x400000,
24: 0x800000,
25: 0x1000000,
26: 0x2000000,
27: 0x4000000,
28: 0x8000000,
29: 0x10000000,
30: 0x20000000,
31: 0x40000000,
'Last': 0x80000000}
weekdays = {'Sunday': 0x1,
'Monday': 0x2,
'Tuesday': 0x4,
'Wednesday': 0x8,
'Thursday': 0x10,
'Friday': 0x20,
'Saturday': 0x40}
weeks = {'First': 0x1,
'Second': 0x2,
'Third': 0x4,
'Fourth': 0x8}
months = {'January': 0x1,
'February': 0x2,
'March': 0x4,
'April': 0x8,
'May': 0x10,
'June': 0x20,
'July': 0x40,
'August': 0x80,
'September': 0x100,
'October': 0x200,
'November': 0x400,
'December': 0x800}
# Format Date Parameters
if start_date:
date_format = _get_date_time_format(start_date)
if date_format:
dt_obj = datetime.strptime(start_date, date_format)
else:
return 'Invalid start_date'
else:
dt_obj = datetime.now()
if start_time:
time_format = _get_date_time_format(start_time)
if time_format:
tm_obj = datetime.strptime(start_time, time_format)
else:
return 'Invalid start_time'
else:
tm_obj = datetime.strptime('00:00:00', '%H:%M:%S')
start_boundary = '{0}T{1}'.format(dt_obj.strftime('%Y-%m-%d'),
tm_obj.strftime('%H:%M:%S'))
dt_obj = None
tm_obj = None
if end_date:
date_format = _get_date_time_format(end_date)
if date_format:
dt_obj = datetime.strptime(end_date, date_format)
else:
return 'Invalid end_date'
if end_time:
time_format = _get_date_time_format(end_time)
if time_format:
tm_obj = datetime.strptime(end_time, time_format)
else:
return 'Invalid end_time'
else:
tm_obj = datetime.strptime('00:00:00', '%H:%M:%S')
end_boundary = None
if dt_obj and tm_obj:
end_boundary = '{0}T{1}'.format(dt_obj.strftime('%Y-%m-%d'),
tm_obj.strftime('%H:%M:%S'))
save_definition = False
if kwargs.get('task_definition', False):
task_definition = kwargs.get('task_definition')
else:
save_definition = True
# Make sure a name was passed
if not name:
return 'Required parameter "name" not passed'
# Make sure task exists
if name in list_tasks(location):
# Connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to create the task in
task_folder = task_service.GetFolder(location)
# Connect to an existing task definition
task_definition = task_folder.GetTask(name).Definition
else:
# Not found and create_new not set, return not found
return '{0} not found'.format(name)
# Create a New Trigger
trigger = task_definition.Triggers.Create(trigger_types[trigger_type])
# Shared Trigger Parameters
# Settings
trigger.StartBoundary = start_boundary
# Advanced Settings
if delay:
trigger.Delay = _lookup_first(duration, delay)
if random_delay:
trigger.RandomDelay = _lookup_first(duration, random_delay)
if repeat_interval:
trigger.Repetition.Interval = _lookup_first(duration, repeat_interval)
if repeat_duration:
trigger.Repetition.Duration = _lookup_first(duration, repeat_duration)
trigger.Repetition.StopAtDurationEnd = repeat_stop_at_duration_end
if execution_time_limit:
trigger.ExecutionTimeLimit = _lookup_first(duration, execution_time_limit)
if end_boundary:
trigger.EndBoundary = end_boundary
trigger.Enabled = trigger_enabled
# Trigger Specific Parameters
# Event Trigger Parameters
if trigger_types[trigger_type] == TASK_TRIGGER_EVENT:
# Check for required kwargs
if kwargs.get('subscription', False):
trigger.Id = 'Event_ID1'
trigger.Subscription = kwargs.get('subscription')
else:
return 'Required parameter "subscription" not passed'
elif trigger_types[trigger_type] == TASK_TRIGGER_TIME:
trigger.Id = 'Once_ID1'
# Daily Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_DAILY:
trigger.Id = 'Daily_ID1'
trigger.DaysInterval = kwargs.get('days_interval', 1)
# Weekly Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_WEEKLY:
trigger.Id = 'Weekly_ID1'
trigger.WeeksInterval = kwargs.get('weeks_interval', 1)
if kwargs.get('days_of_week', False):
bits_days = 0
for weekday in kwargs.get('days_of_week'):
bits_days |= weekdays[weekday]
trigger.DaysOfWeek = bits_days
else:
return 'Required parameter "days_of_week" not passed'
# Monthly Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_MONTHLY:
trigger.Id = 'Monthly_ID1'
if kwargs.get('months_of_year', False):
bits_months = 0
for month in kwargs.get('months_of_year'):
bits_months |= months[month]
trigger.MonthsOfYear = bits_months
else:
return 'Required parameter "months_of_year" not passed'
if kwargs.get('days_of_month', False) or \
kwargs.get('last_day_of_month', False):
if kwargs.get('days_of_month', False):
bits_days = 0
for day in kwargs.get('days_of_month'):
bits_days |= days[day]
trigger.DaysOfMonth = bits_days
trigger.RunOnLastDayOfMonth = kwargs.get('last_day_of_month', False)
else:
return 'Monthly trigger requires "days_of_month" or "last_day_of_month" parameters'
# Monthly Day Of Week Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_MONTHLYDOW:
trigger.Id = 'Monthy_DOW_ID1'
if kwargs.get('months_of_year', False):
bits_months = 0
for month in kwargs.get('months_of_year'):
bits_months |= months[month]
trigger.MonthsOfYear = bits_months
else:
return 'Required parameter "months_of_year" not passed'
if kwargs.get('weeks_of_month', False) or \
kwargs.get('last_week_of_month', False):
if kwargs.get('weeks_of_month', False):
bits_weeks = 0
for week in kwargs.get('weeks_of_month'):
bits_weeks |= weeks[week]
trigger.WeeksOfMonth = bits_weeks
trigger.RunOnLastWeekOfMonth = kwargs.get('last_week_of_month', False)
else:
return 'Monthly DOW trigger requires "weeks_of_month" or "last_week_of_month" parameters'
if kwargs.get('days_of_week', False):
bits_days = 0
for weekday in kwargs.get('days_of_week'):
bits_days |= weekdays[weekday]
trigger.DaysOfWeek = bits_days
else:
return 'Required parameter "days_of_week" not passed'
# On Idle Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_IDLE:
trigger.Id = 'OnIdle_ID1'
# On Task Creation Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_REGISTRATION:
trigger.Id = 'OnTaskCreation_ID1'
# On Boot Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_BOOT:
trigger.Id = 'OnBoot_ID1'
# On Logon Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_LOGON:
trigger.Id = 'OnLogon_ID1'
# On Session State Change Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_SESSION_STATE_CHANGE:
trigger.Id = 'OnSessionStateChange_ID1'
if kwargs.get('session_user_name', False):
trigger.UserId = kwargs.get('session_user_name')
if kwargs.get('state_change', False):
trigger.StateChange = state_changes[kwargs.get('state_change')]
else:
return 'Required parameter "state_change" not passed'
# Save the task
if save_definition:
# Save the Changes
return _save_task_definition(name=name,
task_folder=task_folder,
task_definition=task_definition,
user_name=task_definition.Principal.UserID,
password=None,
logon_type=task_definition.Principal.LogonType) | python | def add_trigger(name=None,
location='\\',
trigger_type=None,
trigger_enabled=True,
start_date=None,
start_time=None,
end_date=None,
end_time=None,
random_delay=None,
repeat_interval=None,
repeat_duration=None,
repeat_stop_at_duration_end=False,
execution_time_limit=None,
delay=None,
**kwargs):
r'''
:param str name: The name of the task to which to add the trigger.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:param str trigger_type: The type of trigger to create. This is defined
when the trigger is created and cannot be changed later. Options are as
follows:
- Event
- Once
- Daily
- Weekly
- Monthly
- MonthlyDay
- OnIdle
- OnTaskCreation
- OnBoot
- OnLogon
- OnSessionChange
:param bool trigger_enabled: Boolean value that indicates whether the
trigger is enabled.
:param str start_date: The date when the trigger is activated. If no value
is passed, the current date will be used. Can be one of the following
formats:
- %Y-%m-%d
- %m-%d-%y
- %m-%d-%Y
- %m/%d/%y
- %m/%d/%Y
- %Y/%m/%d
:param str start_time: The time when the trigger is activated. If no value
is passed, midnight will be used. Can be one of the following formats:
- %I:%M:%S %p
- %I:%M %p
- %H:%M:%S
- %H:%M
:param str end_date: The date when the trigger is deactivated. The trigger
cannot start the task after it is deactivated. Can be one of the
following formats:
- %Y-%m-%d
- %m-%d-%y
- %m-%d-%Y
- %m/%d/%y
- %m/%d/%Y
- %Y/%m/%d
:param str end_time: The time when the trigger is deactivated. If the this
is not passed with ``end_date`` it will be set to midnight. Can be one
of the following formats:
- %I:%M:%S %p
- %I:%M %p
- %H:%M:%S
- %H:%M
:param str random_delay: The delay time that is randomly added to the start
time of the trigger. Valid values are:
- 30 seconds
- 1 minute
- 30 minutes
- 1 hour
- 8 hours
- 1 day
:param str repeat_interval: The amount of time between each restart of the
task. Valid values are:
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
:param str repeat_duration: How long the pattern is repeated. Valid values
are:
- Indefinitely
- 15 minutes
- 30 minutes
- 1 hour
- 12 hours
- 1 day
:param bool repeat_stop_at_duration_end: Boolean value that indicates if a
running instance of the task is stopped at the end of the repetition
pattern duration.
:param str execution_time_limit: The maximum amount of time that the task
launched by the trigger is allowed to run. Valid values are:
- 30 minutes
- 1 hour
- 2 hours
- 4 hours
- 8 hours
- 12 hours
- 1 day
- 3 days (default)
:param str delay: The time the trigger waits after its activation to start the task.
Valid values are:
- 15 seconds
- 30 seconds
- 1 minute
- 30 minutes
- 1 hour
- 8 hours
- 1 day
**kwargs**
There are optional keyword arguments determined by the type of trigger
being defined. They are as follows:
*Event*
:param str subscription: An event definition in xml format that fires the
trigger. The easiest way to get this would is to create an event in
windows task scheduler and then copy the xml text.
*Once*
No special parameters required.
*Daily*
:param int days_interval: The interval between days in the schedule. An
interval of 1 produces a daily schedule. An interval of 2 produces an
every-other day schedule. If no interval is specified, 1 is used. Valid
entries are 1 - 999.
*Weekly*
:param int weeks_interval: The interval between weeks in the schedule.
An interval of 1 produces a weekly schedule. An interval of 2 produces
an every-other week schedule. If no interval is specified, 1 is used.
Valid entries are 1 - 52.
param list days_of_week: Sets the days of the week on which the task
runs. Should be a list. ie: ['Monday','Wednesday','Friday']. Valid
entries are the names of the days of the week.
*Monthly*
:param list months_of_year: Sets the months of the year during which the
task runs. Should be a list. ie: ['January','July']. Valid entries are
the full names of all the months.
:param list days_of_month: Sets the days of the month during which the
task runs. Should be a list. ie: [1, 15, 'Last']. Options are all days
of the month 1 - 31 and the word 'Last' to indicate the last day of the
month.
:param bool last_day_of_month: Boolean value that indicates that the
task runs on the last day of the month regardless of the actual date of
that day.
You can set the task to run on the last day of the month by either
including the word 'Last' in the list of days, or setting the parameter
'last_day_of_month` equal to True.
*MonthlyDay*
:param list months_of_year: Sets the months of the year during which the
task runs. Should be a list. ie: ['January','July']. Valid entries are
the full names of all the months.
:param list weeks_of_month: Sets the weeks of the month during which the
task runs. Should be a list. ie: ['First','Third']. Valid options are:
- First
- Second
- Third
- Fourth
:param bool last_week_of_month: Boolean value that indicates that the task
runs on the last week of the month.
:param list days_of_week: Sets the days of the week during which the task
runs. Should be a list. ie: ['Monday','Wednesday','Friday']. Valid
entries are the names of the days of the week.
*OnIdle*
No special parameters required.
*OnTaskCreation*
No special parameters required.
*OnBoot*
No special parameters required.
*OnLogon*
No special parameters required.
*OnSessionChange*
:param str session_user_name: Sets the user for the Terminal Server
session. When a session state change is detected for this user, a task
is started. To detect session status change for any user, do not pass
this parameter.
:param str state_change: Sets the kind of Terminal Server session change
that would trigger a task launch. Valid options are:
- ConsoleConnect: When you connect to a user session (switch users)
- ConsoleDisconnect: When you disconnect a user session (switch users)
- RemoteConnect: When a user connects via Remote Desktop
- RemoteDisconnect: When a user disconnects via Remote Desktop
- SessionLock: When the workstation is locked
- SessionUnlock: When the workstation is unlocked
.. note::
Arguments are parsed by the YAML loader and are subject to yaml's
idiosyncrasies. Therefore, time values in some formats (``%H:%M:%S`` and
``%H:%M``) should to be quoted. See `YAML IDIOSYNCRASIES`_ for more details.
.. _`YAML IDIOSYNCRASIES`: https://docs.saltstack.com/en/latest/topics/troubleshooting/yaml_idiosyncrasies.html#time-expressions
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.add_trigger <task_name> trigger_type=Once trigger_enabled=True start_date=2016/12/1 start_time='"12:01"'
'''
if not trigger_type:
return 'Required parameter "trigger_type" not specified'
# Define lookup dictionaries
state_changes = {'ConsoleConnect': 1,
'ConsoleDisconnect': 2,
'RemoteConnect': 3,
'RemoteDisconnect': 4,
'SessionLock': 7,
'SessionUnlock': 8}
days = {1: 0x1,
2: 0x2,
3: 0x4,
4: 0x8,
5: 0x10,
6: 0x20,
7: 0x40,
8: 0x80,
9: 0x100,
10: 0x200,
11: 0x400,
12: 0x800,
13: 0x1000,
14: 0x2000,
15: 0x4000,
16: 0x8000,
17: 0x10000,
18: 0x20000,
19: 0x40000,
20: 0x80000,
21: 0x100000,
22: 0x200000,
23: 0x400000,
24: 0x800000,
25: 0x1000000,
26: 0x2000000,
27: 0x4000000,
28: 0x8000000,
29: 0x10000000,
30: 0x20000000,
31: 0x40000000,
'Last': 0x80000000}
weekdays = {'Sunday': 0x1,
'Monday': 0x2,
'Tuesday': 0x4,
'Wednesday': 0x8,
'Thursday': 0x10,
'Friday': 0x20,
'Saturday': 0x40}
weeks = {'First': 0x1,
'Second': 0x2,
'Third': 0x4,
'Fourth': 0x8}
months = {'January': 0x1,
'February': 0x2,
'March': 0x4,
'April': 0x8,
'May': 0x10,
'June': 0x20,
'July': 0x40,
'August': 0x80,
'September': 0x100,
'October': 0x200,
'November': 0x400,
'December': 0x800}
# Format Date Parameters
if start_date:
date_format = _get_date_time_format(start_date)
if date_format:
dt_obj = datetime.strptime(start_date, date_format)
else:
return 'Invalid start_date'
else:
dt_obj = datetime.now()
if start_time:
time_format = _get_date_time_format(start_time)
if time_format:
tm_obj = datetime.strptime(start_time, time_format)
else:
return 'Invalid start_time'
else:
tm_obj = datetime.strptime('00:00:00', '%H:%M:%S')
start_boundary = '{0}T{1}'.format(dt_obj.strftime('%Y-%m-%d'),
tm_obj.strftime('%H:%M:%S'))
dt_obj = None
tm_obj = None
if end_date:
date_format = _get_date_time_format(end_date)
if date_format:
dt_obj = datetime.strptime(end_date, date_format)
else:
return 'Invalid end_date'
if end_time:
time_format = _get_date_time_format(end_time)
if time_format:
tm_obj = datetime.strptime(end_time, time_format)
else:
return 'Invalid end_time'
else:
tm_obj = datetime.strptime('00:00:00', '%H:%M:%S')
end_boundary = None
if dt_obj and tm_obj:
end_boundary = '{0}T{1}'.format(dt_obj.strftime('%Y-%m-%d'),
tm_obj.strftime('%H:%M:%S'))
save_definition = False
if kwargs.get('task_definition', False):
task_definition = kwargs.get('task_definition')
else:
save_definition = True
# Make sure a name was passed
if not name:
return 'Required parameter "name" not passed'
# Make sure task exists
if name in list_tasks(location):
# Connect to the task scheduler
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# get the folder to create the task in
task_folder = task_service.GetFolder(location)
# Connect to an existing task definition
task_definition = task_folder.GetTask(name).Definition
else:
# Not found and create_new not set, return not found
return '{0} not found'.format(name)
# Create a New Trigger
trigger = task_definition.Triggers.Create(trigger_types[trigger_type])
# Shared Trigger Parameters
# Settings
trigger.StartBoundary = start_boundary
# Advanced Settings
if delay:
trigger.Delay = _lookup_first(duration, delay)
if random_delay:
trigger.RandomDelay = _lookup_first(duration, random_delay)
if repeat_interval:
trigger.Repetition.Interval = _lookup_first(duration, repeat_interval)
if repeat_duration:
trigger.Repetition.Duration = _lookup_first(duration, repeat_duration)
trigger.Repetition.StopAtDurationEnd = repeat_stop_at_duration_end
if execution_time_limit:
trigger.ExecutionTimeLimit = _lookup_first(duration, execution_time_limit)
if end_boundary:
trigger.EndBoundary = end_boundary
trigger.Enabled = trigger_enabled
# Trigger Specific Parameters
# Event Trigger Parameters
if trigger_types[trigger_type] == TASK_TRIGGER_EVENT:
# Check for required kwargs
if kwargs.get('subscription', False):
trigger.Id = 'Event_ID1'
trigger.Subscription = kwargs.get('subscription')
else:
return 'Required parameter "subscription" not passed'
elif trigger_types[trigger_type] == TASK_TRIGGER_TIME:
trigger.Id = 'Once_ID1'
# Daily Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_DAILY:
trigger.Id = 'Daily_ID1'
trigger.DaysInterval = kwargs.get('days_interval', 1)
# Weekly Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_WEEKLY:
trigger.Id = 'Weekly_ID1'
trigger.WeeksInterval = kwargs.get('weeks_interval', 1)
if kwargs.get('days_of_week', False):
bits_days = 0
for weekday in kwargs.get('days_of_week'):
bits_days |= weekdays[weekday]
trigger.DaysOfWeek = bits_days
else:
return 'Required parameter "days_of_week" not passed'
# Monthly Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_MONTHLY:
trigger.Id = 'Monthly_ID1'
if kwargs.get('months_of_year', False):
bits_months = 0
for month in kwargs.get('months_of_year'):
bits_months |= months[month]
trigger.MonthsOfYear = bits_months
else:
return 'Required parameter "months_of_year" not passed'
if kwargs.get('days_of_month', False) or \
kwargs.get('last_day_of_month', False):
if kwargs.get('days_of_month', False):
bits_days = 0
for day in kwargs.get('days_of_month'):
bits_days |= days[day]
trigger.DaysOfMonth = bits_days
trigger.RunOnLastDayOfMonth = kwargs.get('last_day_of_month', False)
else:
return 'Monthly trigger requires "days_of_month" or "last_day_of_month" parameters'
# Monthly Day Of Week Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_MONTHLYDOW:
trigger.Id = 'Monthy_DOW_ID1'
if kwargs.get('months_of_year', False):
bits_months = 0
for month in kwargs.get('months_of_year'):
bits_months |= months[month]
trigger.MonthsOfYear = bits_months
else:
return 'Required parameter "months_of_year" not passed'
if kwargs.get('weeks_of_month', False) or \
kwargs.get('last_week_of_month', False):
if kwargs.get('weeks_of_month', False):
bits_weeks = 0
for week in kwargs.get('weeks_of_month'):
bits_weeks |= weeks[week]
trigger.WeeksOfMonth = bits_weeks
trigger.RunOnLastWeekOfMonth = kwargs.get('last_week_of_month', False)
else:
return 'Monthly DOW trigger requires "weeks_of_month" or "last_week_of_month" parameters'
if kwargs.get('days_of_week', False):
bits_days = 0
for weekday in kwargs.get('days_of_week'):
bits_days |= weekdays[weekday]
trigger.DaysOfWeek = bits_days
else:
return 'Required parameter "days_of_week" not passed'
# On Idle Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_IDLE:
trigger.Id = 'OnIdle_ID1'
# On Task Creation Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_REGISTRATION:
trigger.Id = 'OnTaskCreation_ID1'
# On Boot Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_BOOT:
trigger.Id = 'OnBoot_ID1'
# On Logon Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_LOGON:
trigger.Id = 'OnLogon_ID1'
# On Session State Change Trigger Parameters
elif trigger_types[trigger_type] == TASK_TRIGGER_SESSION_STATE_CHANGE:
trigger.Id = 'OnSessionStateChange_ID1'
if kwargs.get('session_user_name', False):
trigger.UserId = kwargs.get('session_user_name')
if kwargs.get('state_change', False):
trigger.StateChange = state_changes[kwargs.get('state_change')]
else:
return 'Required parameter "state_change" not passed'
# Save the task
if save_definition:
# Save the Changes
return _save_task_definition(name=name,
task_folder=task_folder,
task_definition=task_definition,
user_name=task_definition.Principal.UserID,
password=None,
logon_type=task_definition.Principal.LogonType) | [
"def",
"add_trigger",
"(",
"name",
"=",
"None",
",",
"location",
"=",
"'\\\\'",
",",
"trigger_type",
"=",
"None",
",",
"trigger_enabled",
"=",
"True",
",",
"start_date",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"end... | r'''
:param str name: The name of the task to which to add the trigger.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:param str trigger_type: The type of trigger to create. This is defined
when the trigger is created and cannot be changed later. Options are as
follows:
- Event
- Once
- Daily
- Weekly
- Monthly
- MonthlyDay
- OnIdle
- OnTaskCreation
- OnBoot
- OnLogon
- OnSessionChange
:param bool trigger_enabled: Boolean value that indicates whether the
trigger is enabled.
:param str start_date: The date when the trigger is activated. If no value
is passed, the current date will be used. Can be one of the following
formats:
- %Y-%m-%d
- %m-%d-%y
- %m-%d-%Y
- %m/%d/%y
- %m/%d/%Y
- %Y/%m/%d
:param str start_time: The time when the trigger is activated. If no value
is passed, midnight will be used. Can be one of the following formats:
- %I:%M:%S %p
- %I:%M %p
- %H:%M:%S
- %H:%M
:param str end_date: The date when the trigger is deactivated. The trigger
cannot start the task after it is deactivated. Can be one of the
following formats:
- %Y-%m-%d
- %m-%d-%y
- %m-%d-%Y
- %m/%d/%y
- %m/%d/%Y
- %Y/%m/%d
:param str end_time: The time when the trigger is deactivated. If the this
is not passed with ``end_date`` it will be set to midnight. Can be one
of the following formats:
- %I:%M:%S %p
- %I:%M %p
- %H:%M:%S
- %H:%M
:param str random_delay: The delay time that is randomly added to the start
time of the trigger. Valid values are:
- 30 seconds
- 1 minute
- 30 minutes
- 1 hour
- 8 hours
- 1 day
:param str repeat_interval: The amount of time between each restart of the
task. Valid values are:
- 5 minutes
- 10 minutes
- 15 minutes
- 30 minutes
- 1 hour
:param str repeat_duration: How long the pattern is repeated. Valid values
are:
- Indefinitely
- 15 minutes
- 30 minutes
- 1 hour
- 12 hours
- 1 day
:param bool repeat_stop_at_duration_end: Boolean value that indicates if a
running instance of the task is stopped at the end of the repetition
pattern duration.
:param str execution_time_limit: The maximum amount of time that the task
launched by the trigger is allowed to run. Valid values are:
- 30 minutes
- 1 hour
- 2 hours
- 4 hours
- 8 hours
- 12 hours
- 1 day
- 3 days (default)
:param str delay: The time the trigger waits after its activation to start the task.
Valid values are:
- 15 seconds
- 30 seconds
- 1 minute
- 30 minutes
- 1 hour
- 8 hours
- 1 day
**kwargs**
There are optional keyword arguments determined by the type of trigger
being defined. They are as follows:
*Event*
:param str subscription: An event definition in xml format that fires the
trigger. The easiest way to get this would is to create an event in
windows task scheduler and then copy the xml text.
*Once*
No special parameters required.
*Daily*
:param int days_interval: The interval between days in the schedule. An
interval of 1 produces a daily schedule. An interval of 2 produces an
every-other day schedule. If no interval is specified, 1 is used. Valid
entries are 1 - 999.
*Weekly*
:param int weeks_interval: The interval between weeks in the schedule.
An interval of 1 produces a weekly schedule. An interval of 2 produces
an every-other week schedule. If no interval is specified, 1 is used.
Valid entries are 1 - 52.
param list days_of_week: Sets the days of the week on which the task
runs. Should be a list. ie: ['Monday','Wednesday','Friday']. Valid
entries are the names of the days of the week.
*Monthly*
:param list months_of_year: Sets the months of the year during which the
task runs. Should be a list. ie: ['January','July']. Valid entries are
the full names of all the months.
:param list days_of_month: Sets the days of the month during which the
task runs. Should be a list. ie: [1, 15, 'Last']. Options are all days
of the month 1 - 31 and the word 'Last' to indicate the last day of the
month.
:param bool last_day_of_month: Boolean value that indicates that the
task runs on the last day of the month regardless of the actual date of
that day.
You can set the task to run on the last day of the month by either
including the word 'Last' in the list of days, or setting the parameter
'last_day_of_month` equal to True.
*MonthlyDay*
:param list months_of_year: Sets the months of the year during which the
task runs. Should be a list. ie: ['January','July']. Valid entries are
the full names of all the months.
:param list weeks_of_month: Sets the weeks of the month during which the
task runs. Should be a list. ie: ['First','Third']. Valid options are:
- First
- Second
- Third
- Fourth
:param bool last_week_of_month: Boolean value that indicates that the task
runs on the last week of the month.
:param list days_of_week: Sets the days of the week during which the task
runs. Should be a list. ie: ['Monday','Wednesday','Friday']. Valid
entries are the names of the days of the week.
*OnIdle*
No special parameters required.
*OnTaskCreation*
No special parameters required.
*OnBoot*
No special parameters required.
*OnLogon*
No special parameters required.
*OnSessionChange*
:param str session_user_name: Sets the user for the Terminal Server
session. When a session state change is detected for this user, a task
is started. To detect session status change for any user, do not pass
this parameter.
:param str state_change: Sets the kind of Terminal Server session change
that would trigger a task launch. Valid options are:
- ConsoleConnect: When you connect to a user session (switch users)
- ConsoleDisconnect: When you disconnect a user session (switch users)
- RemoteConnect: When a user connects via Remote Desktop
- RemoteDisconnect: When a user disconnects via Remote Desktop
- SessionLock: When the workstation is locked
- SessionUnlock: When the workstation is unlocked
.. note::
Arguments are parsed by the YAML loader and are subject to yaml's
idiosyncrasies. Therefore, time values in some formats (``%H:%M:%S`` and
``%H:%M``) should to be quoted. See `YAML IDIOSYNCRASIES`_ for more details.
.. _`YAML IDIOSYNCRASIES`: https://docs.saltstack.com/en/latest/topics/troubleshooting/yaml_idiosyncrasies.html#time-expressions
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.add_trigger <task_name> trigger_type=Once trigger_enabled=True start_date=2016/12/1 start_time='"12:01"' | [
"r",
":",
"param",
"str",
"name",
":",
"The",
"name",
"of",
"the",
"task",
"to",
"which",
"to",
"add",
"the",
"trigger",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L1666-L2202 | train |
saltstack/salt | salt/modules/win_task.py | clear_triggers | def clear_triggers(name, location='\\'):
r'''
Remove all triggers from the task.
:param str name: The name of the task from which to clear all triggers.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.clear_trigger <task_name>
'''
# Check for existing task
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the triggers from the task
task_folder = task_service.GetFolder(location)
task_definition = task_folder.GetTask(name).Definition
triggers = task_definition.Triggers
triggers.Clear()
# Save the Changes
return _save_task_definition(name=name,
task_folder=task_folder,
task_definition=task_definition,
user_name=task_definition.Principal.UserID,
password=None,
logon_type=task_definition.Principal.LogonType) | python | def clear_triggers(name, location='\\'):
r'''
Remove all triggers from the task.
:param str name: The name of the task from which to clear all triggers.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.clear_trigger <task_name>
'''
# Check for existing task
if name not in list_tasks(location):
return '{0} not found in {1}'.format(name, location)
# Create the task service object
with salt.utils.winapi.Com():
task_service = win32com.client.Dispatch("Schedule.Service")
task_service.Connect()
# Get the triggers from the task
task_folder = task_service.GetFolder(location)
task_definition = task_folder.GetTask(name).Definition
triggers = task_definition.Triggers
triggers.Clear()
# Save the Changes
return _save_task_definition(name=name,
task_folder=task_folder,
task_definition=task_definition,
user_name=task_definition.Principal.UserID,
password=None,
logon_type=task_definition.Principal.LogonType) | [
"def",
"clear_triggers",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing task",
"if",
"name",
"not",
"in",
"list_tasks",
"(",
"location",
")",
":",
"return",
"'{0} not found in {1}'",
".",
"format",
"(",
"name",
",",
"location",
")... | r'''
Remove all triggers from the task.
:param str name: The name of the task from which to clear all triggers.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if successful, False if unsuccessful
:rtype: bool
CLI Example:
.. code-block:: bash
salt 'minion-id' task.clear_trigger <task_name> | [
"r",
"Remove",
"all",
"triggers",
"from",
"the",
"task",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L2205-L2246 | train |
saltstack/salt | salt/sdb/couchdb.py | _get_conn | def _get_conn(profile):
'''
Get a connection to CouchDB
'''
DEFAULT_BASE_URL = _construct_uri(profile) or 'http://localhost:5984'
server = couchdb.Server()
if profile['database'] not in server:
server.create(profile['database'])
return server | python | def _get_conn(profile):
'''
Get a connection to CouchDB
'''
DEFAULT_BASE_URL = _construct_uri(profile) or 'http://localhost:5984'
server = couchdb.Server()
if profile['database'] not in server:
server.create(profile['database'])
return server | [
"def",
"_get_conn",
"(",
"profile",
")",
":",
"DEFAULT_BASE_URL",
"=",
"_construct_uri",
"(",
"profile",
")",
"or",
"'http://localhost:5984'",
"server",
"=",
"couchdb",
".",
"Server",
"(",
")",
"if",
"profile",
"[",
"'database'",
"]",
"not",
"in",
"server",
... | Get a connection to CouchDB | [
"Get",
"a",
"connection",
"to",
"CouchDB"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/couchdb.py#L79-L88 | train |
saltstack/salt | salt/sdb/couchdb.py | set_ | def set_(key, value, profile=None):
'''
Set a key/value pair in couchdb
'''
db = _get_db(profile)
return db.save({'_id': uuid4().hex, key: value}) | python | def set_(key, value, profile=None):
'''
Set a key/value pair in couchdb
'''
db = _get_db(profile)
return db.save({'_id': uuid4().hex, key: value}) | [
"def",
"set_",
"(",
"key",
",",
"value",
",",
"profile",
"=",
"None",
")",
":",
"db",
"=",
"_get_db",
"(",
"profile",
")",
"return",
"db",
".",
"save",
"(",
"{",
"'_id'",
":",
"uuid4",
"(",
")",
".",
"hex",
",",
"key",
":",
"value",
"}",
")"
] | Set a key/value pair in couchdb | [
"Set",
"a",
"key",
"/",
"value",
"pair",
"in",
"couchdb"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/couchdb.py#L91-L96 | train |
saltstack/salt | salt/client/ssh/shell.py | gen_key | def gen_key(path):
'''
Generate a key for use with salt-ssh
'''
cmd = 'ssh-keygen -P "" -f {0} -t rsa -q'.format(path)
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
subprocess.call(cmd, shell=True) | python | def gen_key(path):
'''
Generate a key for use with salt-ssh
'''
cmd = 'ssh-keygen -P "" -f {0} -t rsa -q'.format(path)
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
subprocess.call(cmd, shell=True) | [
"def",
"gen_key",
"(",
"path",
")",
":",
"cmd",
"=",
"'ssh-keygen -P \"\" -f {0} -t rsa -q'",
".",
"format",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
":",
"os",
"."... | Generate a key for use with salt-ssh | [
"Generate",
"a",
"key",
"for",
"use",
"with",
"salt",
"-",
"ssh"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L42-L49 | train |
saltstack/salt | salt/client/ssh/shell.py | gen_shell | def gen_shell(opts, **kwargs):
'''
Return the correct shell interface for the target system
'''
if kwargs['winrm']:
try:
import saltwinshell
shell = saltwinshell.Shell(opts, **kwargs)
except ImportError:
log.error('The saltwinshell library is not available')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
shell = Shell(opts, **kwargs)
return shell | python | def gen_shell(opts, **kwargs):
'''
Return the correct shell interface for the target system
'''
if kwargs['winrm']:
try:
import saltwinshell
shell = saltwinshell.Shell(opts, **kwargs)
except ImportError:
log.error('The saltwinshell library is not available')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
shell = Shell(opts, **kwargs)
return shell | [
"def",
"gen_shell",
"(",
"opts",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
"[",
"'winrm'",
"]",
":",
"try",
":",
"import",
"saltwinshell",
"shell",
"=",
"saltwinshell",
".",
"Shell",
"(",
"opts",
",",
"*",
"*",
"kwargs",
")",
"except",
"Impo... | Return the correct shell interface for the target system | [
"Return",
"the",
"correct",
"shell",
"interface",
"for",
"the",
"target",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L52-L65 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell.get_error | def get_error(self, errstr):
'''
Parse out an error and return a targeted error string
'''
for line in errstr.split('\n'):
if line.startswith('ssh:'):
return line
if line.startswith('Pseudo-terminal'):
continue
if 'to the list of known hosts.' in line:
continue
return line
return errstr | python | def get_error(self, errstr):
'''
Parse out an error and return a targeted error string
'''
for line in errstr.split('\n'):
if line.startswith('ssh:'):
return line
if line.startswith('Pseudo-terminal'):
continue
if 'to the list of known hosts.' in line:
continue
return line
return errstr | [
"def",
"get_error",
"(",
"self",
",",
"errstr",
")",
":",
"for",
"line",
"in",
"errstr",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'ssh:'",
")",
":",
"return",
"line",
"if",
"line",
".",
"startswith",
"(",
"'Pseudo-... | Parse out an error and return a targeted error string | [
"Parse",
"out",
"an",
"error",
"and",
"return",
"a",
"targeted",
"error",
"string"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L106-L118 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell._key_opts | def _key_opts(self):
'''
Return options for the ssh command base for Salt to call
'''
options = [
'KbdInteractiveAuthentication=no',
]
if self.passwd:
options.append('PasswordAuthentication=yes')
else:
options.append('PasswordAuthentication=no')
if self.opts.get('_ssh_version', (0,)) > (4, 9):
options.append('GSSAPIAuthentication=no')
options.append('ConnectTimeout={0}'.format(self.timeout))
if self.opts.get('ignore_host_keys'):
options.append('StrictHostKeyChecking=no')
if self.opts.get('no_host_keys'):
options.extend(['StrictHostKeyChecking=no',
'UserKnownHostsFile=/dev/null'])
known_hosts = self.opts.get('known_hosts_file')
if known_hosts and os.path.isfile(known_hosts):
options.append('UserKnownHostsFile={0}'.format(known_hosts))
if self.port:
options.append('Port={0}'.format(self.port))
if self.priv and self.priv != 'agent-forwarding':
options.append('IdentityFile={0}'.format(self.priv))
if self.user:
options.append('User={0}'.format(self.user))
if self.identities_only:
options.append('IdentitiesOnly=yes')
ret = []
for option in options:
ret.append('-o {0} '.format(option))
return ''.join(ret) | python | def _key_opts(self):
'''
Return options for the ssh command base for Salt to call
'''
options = [
'KbdInteractiveAuthentication=no',
]
if self.passwd:
options.append('PasswordAuthentication=yes')
else:
options.append('PasswordAuthentication=no')
if self.opts.get('_ssh_version', (0,)) > (4, 9):
options.append('GSSAPIAuthentication=no')
options.append('ConnectTimeout={0}'.format(self.timeout))
if self.opts.get('ignore_host_keys'):
options.append('StrictHostKeyChecking=no')
if self.opts.get('no_host_keys'):
options.extend(['StrictHostKeyChecking=no',
'UserKnownHostsFile=/dev/null'])
known_hosts = self.opts.get('known_hosts_file')
if known_hosts and os.path.isfile(known_hosts):
options.append('UserKnownHostsFile={0}'.format(known_hosts))
if self.port:
options.append('Port={0}'.format(self.port))
if self.priv and self.priv != 'agent-forwarding':
options.append('IdentityFile={0}'.format(self.priv))
if self.user:
options.append('User={0}'.format(self.user))
if self.identities_only:
options.append('IdentitiesOnly=yes')
ret = []
for option in options:
ret.append('-o {0} '.format(option))
return ''.join(ret) | [
"def",
"_key_opts",
"(",
"self",
")",
":",
"options",
"=",
"[",
"'KbdInteractiveAuthentication=no'",
",",
"]",
"if",
"self",
".",
"passwd",
":",
"options",
".",
"append",
"(",
"'PasswordAuthentication=yes'",
")",
"else",
":",
"options",
".",
"append",
"(",
"... | Return options for the ssh command base for Salt to call | [
"Return",
"options",
"for",
"the",
"ssh",
"command",
"base",
"for",
"Salt",
"to",
"call"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L120-L154 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell._passwd_opts | def _passwd_opts(self):
'''
Return options to pass to ssh
'''
# TODO ControlMaster does not work without ControlPath
# user could take advantage of it if they set ControlPath in their
# ssh config. Also, ControlPersist not widely available.
options = ['ControlMaster=auto',
'StrictHostKeyChecking=no',
]
if self.opts['_ssh_version'] > (4, 9):
options.append('GSSAPIAuthentication=no')
options.append('ConnectTimeout={0}'.format(self.timeout))
if self.opts.get('ignore_host_keys'):
options.append('StrictHostKeyChecking=no')
if self.opts.get('no_host_keys'):
options.extend(['StrictHostKeyChecking=no',
'UserKnownHostsFile=/dev/null'])
if self.passwd:
options.extend(['PasswordAuthentication=yes',
'PubkeyAuthentication=yes'])
else:
options.extend(['PasswordAuthentication=no',
'PubkeyAuthentication=yes',
'KbdInteractiveAuthentication=no',
'ChallengeResponseAuthentication=no',
'BatchMode=yes'])
if self.port:
options.append('Port={0}'.format(self.port))
if self.user:
options.append('User={0}'.format(self.user))
if self.identities_only:
options.append('IdentitiesOnly=yes')
ret = []
for option in options:
ret.append('-o {0} '.format(option))
return ''.join(ret) | python | def _passwd_opts(self):
'''
Return options to pass to ssh
'''
# TODO ControlMaster does not work without ControlPath
# user could take advantage of it if they set ControlPath in their
# ssh config. Also, ControlPersist not widely available.
options = ['ControlMaster=auto',
'StrictHostKeyChecking=no',
]
if self.opts['_ssh_version'] > (4, 9):
options.append('GSSAPIAuthentication=no')
options.append('ConnectTimeout={0}'.format(self.timeout))
if self.opts.get('ignore_host_keys'):
options.append('StrictHostKeyChecking=no')
if self.opts.get('no_host_keys'):
options.extend(['StrictHostKeyChecking=no',
'UserKnownHostsFile=/dev/null'])
if self.passwd:
options.extend(['PasswordAuthentication=yes',
'PubkeyAuthentication=yes'])
else:
options.extend(['PasswordAuthentication=no',
'PubkeyAuthentication=yes',
'KbdInteractiveAuthentication=no',
'ChallengeResponseAuthentication=no',
'BatchMode=yes'])
if self.port:
options.append('Port={0}'.format(self.port))
if self.user:
options.append('User={0}'.format(self.user))
if self.identities_only:
options.append('IdentitiesOnly=yes')
ret = []
for option in options:
ret.append('-o {0} '.format(option))
return ''.join(ret) | [
"def",
"_passwd_opts",
"(",
"self",
")",
":",
"# TODO ControlMaster does not work without ControlPath",
"# user could take advantage of it if they set ControlPath in their",
"# ssh config. Also, ControlPersist not widely available.",
"options",
"=",
"[",
"'ControlMaster=auto'",
",",
"'S... | Return options to pass to ssh | [
"Return",
"options",
"to",
"pass",
"to",
"ssh"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L156-L194 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell._copy_id_str_old | def _copy_id_str_old(self):
'''
Return the string to execute ssh-copy-id
'''
if self.passwd:
# Using single quotes prevents shell expansion and
# passwords containing '$'
return "{0} {1} '{2} -p {3} {4} {5}@{6}'".format(
'ssh-copy-id',
'-i {0}.pub'.format(self.priv),
self._passwd_opts(),
self.port,
self._ssh_opts(),
self.user,
self.host)
return None | python | def _copy_id_str_old(self):
'''
Return the string to execute ssh-copy-id
'''
if self.passwd:
# Using single quotes prevents shell expansion and
# passwords containing '$'
return "{0} {1} '{2} -p {3} {4} {5}@{6}'".format(
'ssh-copy-id',
'-i {0}.pub'.format(self.priv),
self._passwd_opts(),
self.port,
self._ssh_opts(),
self.user,
self.host)
return None | [
"def",
"_copy_id_str_old",
"(",
"self",
")",
":",
"if",
"self",
".",
"passwd",
":",
"# Using single quotes prevents shell expansion and",
"# passwords containing '$'",
"return",
"\"{0} {1} '{2} -p {3} {4} {5}@{6}'\"",
".",
"format",
"(",
"'ssh-copy-id'",
",",
"'-i {0}.pub'",
... | Return the string to execute ssh-copy-id | [
"Return",
"the",
"string",
"to",
"execute",
"ssh",
"-",
"copy",
"-",
"id"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L200-L215 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell.copy_id | def copy_id(self):
'''
Execute ssh-copy-id to plant the id file on the target
'''
stdout, stderr, retcode = self._run_cmd(self._copy_id_str_old())
if salt.defaults.exitcodes.EX_OK != retcode and 'Usage' in stderr:
stdout, stderr, retcode = self._run_cmd(self._copy_id_str_new())
return stdout, stderr, retcode | python | def copy_id(self):
'''
Execute ssh-copy-id to plant the id file on the target
'''
stdout, stderr, retcode = self._run_cmd(self._copy_id_str_old())
if salt.defaults.exitcodes.EX_OK != retcode and 'Usage' in stderr:
stdout, stderr, retcode = self._run_cmd(self._copy_id_str_new())
return stdout, stderr, retcode | [
"def",
"copy_id",
"(",
"self",
")",
":",
"stdout",
",",
"stderr",
",",
"retcode",
"=",
"self",
".",
"_run_cmd",
"(",
"self",
".",
"_copy_id_str_old",
"(",
")",
")",
"if",
"salt",
".",
"defaults",
".",
"exitcodes",
".",
"EX_OK",
"!=",
"retcode",
"and",
... | Execute ssh-copy-id to plant the id file on the target | [
"Execute",
"ssh",
"-",
"copy",
"-",
"id",
"to",
"plant",
"the",
"id",
"file",
"on",
"the",
"target"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L235-L242 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell._cmd_str | def _cmd_str(self, cmd, ssh='ssh'):
'''
Return the cmd string to execute
'''
# TODO: if tty, then our SSH_SHIM cannot be supplied from STDIN Will
# need to deliver the SHIM to the remote host and execute it there
command = [ssh]
if ssh != 'scp':
command.append(self.host)
if self.tty and ssh == 'ssh':
command.append('-t -t')
if self.passwd or self.priv:
command.append(self.priv and self._key_opts() or self._passwd_opts())
if ssh != 'scp' and self.remote_port_forwards:
command.append(' '.join(['-R {0}'.format(item)
for item in self.remote_port_forwards.split(',')]))
if self.ssh_options:
command.append(self._ssh_opts())
command.append(cmd)
return ' '.join(command) | python | def _cmd_str(self, cmd, ssh='ssh'):
'''
Return the cmd string to execute
'''
# TODO: if tty, then our SSH_SHIM cannot be supplied from STDIN Will
# need to deliver the SHIM to the remote host and execute it there
command = [ssh]
if ssh != 'scp':
command.append(self.host)
if self.tty and ssh == 'ssh':
command.append('-t -t')
if self.passwd or self.priv:
command.append(self.priv and self._key_opts() or self._passwd_opts())
if ssh != 'scp' and self.remote_port_forwards:
command.append(' '.join(['-R {0}'.format(item)
for item in self.remote_port_forwards.split(',')]))
if self.ssh_options:
command.append(self._ssh_opts())
command.append(cmd)
return ' '.join(command) | [
"def",
"_cmd_str",
"(",
"self",
",",
"cmd",
",",
"ssh",
"=",
"'ssh'",
")",
":",
"# TODO: if tty, then our SSH_SHIM cannot be supplied from STDIN Will",
"# need to deliver the SHIM to the remote host and execute it there",
"command",
"=",
"[",
"ssh",
"]",
"if",
"ssh",
"!=",
... | Return the cmd string to execute | [
"Return",
"the",
"cmd",
"string",
"to",
"execute"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L244-L267 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell._old_run_cmd | def _old_run_cmd(self, cmd):
'''
Cleanly execute the command string
'''
try:
proc = subprocess.Popen(
cmd,
shell=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
data = proc.communicate()
return data[0], data[1], proc.returncode
except Exception:
return ('local', 'Unknown Error', None) | python | def _old_run_cmd(self, cmd):
'''
Cleanly execute the command string
'''
try:
proc = subprocess.Popen(
cmd,
shell=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
data = proc.communicate()
return data[0], data[1], proc.returncode
except Exception:
return ('local', 'Unknown Error', None) | [
"def",
"_old_run_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"try",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
... | Cleanly execute the command string | [
"Cleanly",
"execute",
"the",
"command",
"string"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L269-L284 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell._run_nb_cmd | def _run_nb_cmd(self, cmd):
'''
cmd iterator
'''
try:
proc = salt.utils.nb_popen.NonBlockingPopen(
cmd,
shell=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
while True:
time.sleep(0.1)
out = proc.recv()
err = proc.recv_err()
rcode = proc.returncode
if out is None and err is None:
break
if err:
err = self.get_error(err)
yield out, err, rcode
except Exception:
yield ('', 'Unknown Error', None) | python | def _run_nb_cmd(self, cmd):
'''
cmd iterator
'''
try:
proc = salt.utils.nb_popen.NonBlockingPopen(
cmd,
shell=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
while True:
time.sleep(0.1)
out = proc.recv()
err = proc.recv_err()
rcode = proc.returncode
if out is None and err is None:
break
if err:
err = self.get_error(err)
yield out, err, rcode
except Exception:
yield ('', 'Unknown Error', None) | [
"def",
"_run_nb_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"try",
":",
"proc",
"=",
"salt",
".",
"utils",
".",
"nb_popen",
".",
"NonBlockingPopen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"="... | cmd iterator | [
"cmd",
"iterator"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L286-L308 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell.exec_nb_cmd | def exec_nb_cmd(self, cmd):
'''
Yield None until cmd finished
'''
r_out = []
r_err = []
rcode = None
cmd = self._cmd_str(cmd)
logmsg = 'Executing non-blocking command: {0}'.format(cmd)
if self.passwd:
logmsg = logmsg.replace(self.passwd, ('*' * 6))
log.debug(logmsg)
for out, err, rcode in self._run_nb_cmd(cmd):
if out is not None:
r_out.append(out)
if err is not None:
r_err.append(err)
yield None, None, None
yield ''.join(r_out), ''.join(r_err), rcode | python | def exec_nb_cmd(self, cmd):
'''
Yield None until cmd finished
'''
r_out = []
r_err = []
rcode = None
cmd = self._cmd_str(cmd)
logmsg = 'Executing non-blocking command: {0}'.format(cmd)
if self.passwd:
logmsg = logmsg.replace(self.passwd, ('*' * 6))
log.debug(logmsg)
for out, err, rcode in self._run_nb_cmd(cmd):
if out is not None:
r_out.append(out)
if err is not None:
r_err.append(err)
yield None, None, None
yield ''.join(r_out), ''.join(r_err), rcode | [
"def",
"exec_nb_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"r_out",
"=",
"[",
"]",
"r_err",
"=",
"[",
"]",
"rcode",
"=",
"None",
"cmd",
"=",
"self",
".",
"_cmd_str",
"(",
"cmd",
")",
"logmsg",
"=",
"'Executing non-blocking command: {0}'",
".",
"format",
... | Yield None until cmd finished | [
"Yield",
"None",
"until",
"cmd",
"finished"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L310-L330 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell.exec_cmd | def exec_cmd(self, cmd):
'''
Execute a remote command
'''
cmd = self._cmd_str(cmd)
logmsg = 'Executing command: {0}'.format(cmd)
if self.passwd:
logmsg = logmsg.replace(self.passwd, ('*' * 6))
if 'decode("base64")' in logmsg or 'base64.b64decode(' in logmsg:
log.debug('Executed SHIM command. Command logged to TRACE')
log.trace(logmsg)
else:
log.debug(logmsg)
ret = self._run_cmd(cmd)
return ret | python | def exec_cmd(self, cmd):
'''
Execute a remote command
'''
cmd = self._cmd_str(cmd)
logmsg = 'Executing command: {0}'.format(cmd)
if self.passwd:
logmsg = logmsg.replace(self.passwd, ('*' * 6))
if 'decode("base64")' in logmsg or 'base64.b64decode(' in logmsg:
log.debug('Executed SHIM command. Command logged to TRACE')
log.trace(logmsg)
else:
log.debug(logmsg)
ret = self._run_cmd(cmd)
return ret | [
"def",
"exec_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"cmd",
"=",
"self",
".",
"_cmd_str",
"(",
"cmd",
")",
"logmsg",
"=",
"'Executing command: {0}'",
".",
"format",
"(",
"cmd",
")",
"if",
"self",
".",
"passwd",
":",
"logmsg",
"=",
"logmsg",
".",
"re... | Execute a remote command | [
"Execute",
"a",
"remote",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L332-L348 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell.send | def send(self, local, remote, makedirs=False):
'''
scp a file or files to a remote system
'''
if makedirs:
self.exec_cmd('mkdir -p {0}'.format(os.path.dirname(remote)))
# scp needs [<ipv6}
host = self.host
if ':' in host:
host = '[{0}]'.format(host)
cmd = '{0} {1}:{2}'.format(local, host, remote)
cmd = self._cmd_str(cmd, ssh='scp')
logmsg = 'Executing command: {0}'.format(cmd)
if self.passwd:
logmsg = logmsg.replace(self.passwd, ('*' * 6))
log.debug(logmsg)
return self._run_cmd(cmd) | python | def send(self, local, remote, makedirs=False):
'''
scp a file or files to a remote system
'''
if makedirs:
self.exec_cmd('mkdir -p {0}'.format(os.path.dirname(remote)))
# scp needs [<ipv6}
host = self.host
if ':' in host:
host = '[{0}]'.format(host)
cmd = '{0} {1}:{2}'.format(local, host, remote)
cmd = self._cmd_str(cmd, ssh='scp')
logmsg = 'Executing command: {0}'.format(cmd)
if self.passwd:
logmsg = logmsg.replace(self.passwd, ('*' * 6))
log.debug(logmsg)
return self._run_cmd(cmd) | [
"def",
"send",
"(",
"self",
",",
"local",
",",
"remote",
",",
"makedirs",
"=",
"False",
")",
":",
"if",
"makedirs",
":",
"self",
".",
"exec_cmd",
"(",
"'mkdir -p {0}'",
".",
"format",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"remote",
")",
")",
... | scp a file or files to a remote system | [
"scp",
"a",
"file",
"or",
"files",
"to",
"a",
"remote",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L350-L370 | train |
saltstack/salt | salt/client/ssh/shell.py | Shell._run_cmd | def _run_cmd(self, cmd, key_accept=False, passwd_retries=3):
'''
Execute a shell command via VT. This is blocking and assumes that ssh
is being run
'''
if not cmd:
return '', 'No command or passphrase', 245
term = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stdout_level='trace',
log_stderr=True,
log_stderr_level='trace',
stream_stdout=False,
stream_stderr=False)
sent_passwd = 0
send_password = True
ret_stdout = ''
ret_stderr = ''
old_stdout = ''
try:
while term.has_unread_data:
stdout, stderr = term.recv()
if stdout:
ret_stdout += stdout
buff = old_stdout + stdout
else:
buff = stdout
if stderr:
ret_stderr += stderr
if buff and RSTR_RE.search(buff):
# We're getting results back, don't try to send passwords
send_password = False
if buff and SSH_PRIVATE_KEY_PASSWORD_PROMPT_RE.search(buff):
if not self.priv_passwd:
return '', 'Private key file need passphrase', 254
term.sendline(self.priv_passwd)
continue
if buff and SSH_PASSWORD_PROMPT_RE.search(buff) and send_password:
if not self.passwd:
return '', 'Permission denied, no authentication information', 254
if sent_passwd < passwd_retries:
term.sendline(self.passwd)
sent_passwd += 1
continue
else:
# asking for a password, and we can't seem to send it
return '', 'Password authentication failed', 254
elif buff and KEY_VALID_RE.search(buff):
if key_accept:
term.sendline('yes')
continue
else:
term.sendline('no')
ret_stdout = ('The host key needs to be accepted, to '
'auto accept run salt-ssh with the -i '
'flag:\n{0}').format(stdout)
return ret_stdout, '', 254
elif buff and buff.endswith('_||ext_mods||_'):
mods_raw = salt.utils.json.dumps(self.mods, separators=(',', ':')) + '|_E|0|'
term.sendline(mods_raw)
if stdout:
old_stdout = stdout
time.sleep(0.01)
return ret_stdout, ret_stderr, term.exitstatus
finally:
term.close(terminate=True, kill=True) | python | def _run_cmd(self, cmd, key_accept=False, passwd_retries=3):
'''
Execute a shell command via VT. This is blocking and assumes that ssh
is being run
'''
if not cmd:
return '', 'No command or passphrase', 245
term = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stdout_level='trace',
log_stderr=True,
log_stderr_level='trace',
stream_stdout=False,
stream_stderr=False)
sent_passwd = 0
send_password = True
ret_stdout = ''
ret_stderr = ''
old_stdout = ''
try:
while term.has_unread_data:
stdout, stderr = term.recv()
if stdout:
ret_stdout += stdout
buff = old_stdout + stdout
else:
buff = stdout
if stderr:
ret_stderr += stderr
if buff and RSTR_RE.search(buff):
# We're getting results back, don't try to send passwords
send_password = False
if buff and SSH_PRIVATE_KEY_PASSWORD_PROMPT_RE.search(buff):
if not self.priv_passwd:
return '', 'Private key file need passphrase', 254
term.sendline(self.priv_passwd)
continue
if buff and SSH_PASSWORD_PROMPT_RE.search(buff) and send_password:
if not self.passwd:
return '', 'Permission denied, no authentication information', 254
if sent_passwd < passwd_retries:
term.sendline(self.passwd)
sent_passwd += 1
continue
else:
# asking for a password, and we can't seem to send it
return '', 'Password authentication failed', 254
elif buff and KEY_VALID_RE.search(buff):
if key_accept:
term.sendline('yes')
continue
else:
term.sendline('no')
ret_stdout = ('The host key needs to be accepted, to '
'auto accept run salt-ssh with the -i '
'flag:\n{0}').format(stdout)
return ret_stdout, '', 254
elif buff and buff.endswith('_||ext_mods||_'):
mods_raw = salt.utils.json.dumps(self.mods, separators=(',', ':')) + '|_E|0|'
term.sendline(mods_raw)
if stdout:
old_stdout = stdout
time.sleep(0.01)
return ret_stdout, ret_stderr, term.exitstatus
finally:
term.close(terminate=True, kill=True) | [
"def",
"_run_cmd",
"(",
"self",
",",
"cmd",
",",
"key_accept",
"=",
"False",
",",
"passwd_retries",
"=",
"3",
")",
":",
"if",
"not",
"cmd",
":",
"return",
"''",
",",
"'No command or passphrase'",
",",
"245",
"term",
"=",
"salt",
".",
"utils",
".",
"vt"... | Execute a shell command via VT. This is blocking and assumes that ssh
is being run | [
"Execute",
"a",
"shell",
"command",
"via",
"VT",
".",
"This",
"is",
"blocking",
"and",
"assumes",
"that",
"ssh",
"is",
"being",
"run"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/shell.py#L372-L441 | train |
saltstack/salt | salt/log/handlers/sentry_mod.py | setup_handlers | def setup_handlers():
'''
sets up the sentry handler
'''
__grains__ = salt.loader.grains(__opts__)
__salt__ = salt.loader.minion_mods(__opts__)
if 'sentry_handler' not in __opts__:
log.debug('No \'sentry_handler\' key was found in the configuration')
return False
options = {}
dsn = get_config_value('dsn')
if dsn is not None:
try:
# support raven ver 5.5.0
from raven.transport import TransportRegistry, default_transports
from raven.utils.urlparse import urlparse
transport_registry = TransportRegistry(default_transports)
url = urlparse(dsn)
if not transport_registry.supported_scheme(url.scheme):
raise ValueError('Unsupported Sentry DSN scheme: {0}'.format(url.scheme))
except ValueError as exc:
log.info(
'Raven failed to parse the configuration provided DSN: %s', exc
)
if not dsn:
for key in ('project', 'servers', 'public_key', 'secret_key'):
config_value = get_config_value(key)
if config_value is None and key not in options:
log.debug(
'The required \'sentry_handler\' configuration key, '
'\'%s\', is not properly configured. Not configuring '
'the sentry logging handler.', key
)
return
elif config_value is None:
continue
options[key] = config_value
# site: An optional, arbitrary string to identify this client installation.
options.update({
# site: An optional, arbitrary string to identify this client
# installation
'site': get_config_value('site'),
# name: This will override the server_name value for this installation.
# Defaults to socket.gethostname()
'name': get_config_value('name'),
# exclude_paths: Extending this allow you to ignore module prefixes
# when sentry attempts to discover which function an error comes from
'exclude_paths': get_config_value('exclude_paths', ()),
# include_paths: For example, in Django this defaults to your list of
# INSTALLED_APPS, and is used for drilling down where an exception is
# located
'include_paths': get_config_value('include_paths', ()),
# list_max_length: The maximum number of items a list-like container
# should store.
'list_max_length': get_config_value('list_max_length'),
# string_max_length: The maximum characters of a string that should be
# stored.
'string_max_length': get_config_value('string_max_length'),
# auto_log_stacks: Should Raven automatically log frame stacks
# (including locals) all calls as it would for exceptions.
'auto_log_stacks': get_config_value('auto_log_stacks'),
# timeout: If supported, the timeout value for sending messages to
# remote.
'timeout': get_config_value('timeout', 1),
# processors: A list of processors to apply to events before sending
# them to the Sentry server. Useful for sending additional global state
# data or sanitizing data that you want to keep off of the server.
'processors': get_config_value('processors'),
# dsn: Ensure the DSN is passed into the client
'dsn': dsn
})
client = raven.Client(**options)
context = get_config_value('context')
context_dict = {}
if context is not None:
for tag in context:
try:
tag_value = __grains__[tag]
except KeyError:
log.debug('Sentry tag \'%s\' not found in grains.', tag)
continue
if tag_value:
context_dict[tag] = tag_value
if context_dict:
client.context.merge({'tags': context_dict})
try:
handler = SentryHandler(client)
exclude_patterns = get_config_value('exclude_patterns', None)
if exclude_patterns:
filter_regexes = [re.compile(pattern) for pattern in exclude_patterns]
class FilterExcludedMessages(object):
@staticmethod
def filter(record):
m = record.getMessage()
return not any(regex.search(m) for regex in filter_regexes)
handler.addFilter(FilterExcludedMessages())
handler.setLevel(LOG_LEVELS[get_config_value('log_level', 'error')])
return handler
except ValueError as exc:
log.debug('Failed to setup the sentry logging handler', exc_info=True) | python | def setup_handlers():
'''
sets up the sentry handler
'''
__grains__ = salt.loader.grains(__opts__)
__salt__ = salt.loader.minion_mods(__opts__)
if 'sentry_handler' not in __opts__:
log.debug('No \'sentry_handler\' key was found in the configuration')
return False
options = {}
dsn = get_config_value('dsn')
if dsn is not None:
try:
# support raven ver 5.5.0
from raven.transport import TransportRegistry, default_transports
from raven.utils.urlparse import urlparse
transport_registry = TransportRegistry(default_transports)
url = urlparse(dsn)
if not transport_registry.supported_scheme(url.scheme):
raise ValueError('Unsupported Sentry DSN scheme: {0}'.format(url.scheme))
except ValueError as exc:
log.info(
'Raven failed to parse the configuration provided DSN: %s', exc
)
if not dsn:
for key in ('project', 'servers', 'public_key', 'secret_key'):
config_value = get_config_value(key)
if config_value is None and key not in options:
log.debug(
'The required \'sentry_handler\' configuration key, '
'\'%s\', is not properly configured. Not configuring '
'the sentry logging handler.', key
)
return
elif config_value is None:
continue
options[key] = config_value
# site: An optional, arbitrary string to identify this client installation.
options.update({
# site: An optional, arbitrary string to identify this client
# installation
'site': get_config_value('site'),
# name: This will override the server_name value for this installation.
# Defaults to socket.gethostname()
'name': get_config_value('name'),
# exclude_paths: Extending this allow you to ignore module prefixes
# when sentry attempts to discover which function an error comes from
'exclude_paths': get_config_value('exclude_paths', ()),
# include_paths: For example, in Django this defaults to your list of
# INSTALLED_APPS, and is used for drilling down where an exception is
# located
'include_paths': get_config_value('include_paths', ()),
# list_max_length: The maximum number of items a list-like container
# should store.
'list_max_length': get_config_value('list_max_length'),
# string_max_length: The maximum characters of a string that should be
# stored.
'string_max_length': get_config_value('string_max_length'),
# auto_log_stacks: Should Raven automatically log frame stacks
# (including locals) all calls as it would for exceptions.
'auto_log_stacks': get_config_value('auto_log_stacks'),
# timeout: If supported, the timeout value for sending messages to
# remote.
'timeout': get_config_value('timeout', 1),
# processors: A list of processors to apply to events before sending
# them to the Sentry server. Useful for sending additional global state
# data or sanitizing data that you want to keep off of the server.
'processors': get_config_value('processors'),
# dsn: Ensure the DSN is passed into the client
'dsn': dsn
})
client = raven.Client(**options)
context = get_config_value('context')
context_dict = {}
if context is not None:
for tag in context:
try:
tag_value = __grains__[tag]
except KeyError:
log.debug('Sentry tag \'%s\' not found in grains.', tag)
continue
if tag_value:
context_dict[tag] = tag_value
if context_dict:
client.context.merge({'tags': context_dict})
try:
handler = SentryHandler(client)
exclude_patterns = get_config_value('exclude_patterns', None)
if exclude_patterns:
filter_regexes = [re.compile(pattern) for pattern in exclude_patterns]
class FilterExcludedMessages(object):
@staticmethod
def filter(record):
m = record.getMessage()
return not any(regex.search(m) for regex in filter_regexes)
handler.addFilter(FilterExcludedMessages())
handler.setLevel(LOG_LEVELS[get_config_value('log_level', 'error')])
return handler
except ValueError as exc:
log.debug('Failed to setup the sentry logging handler', exc_info=True) | [
"def",
"setup_handlers",
"(",
")",
":",
"__grains__",
"=",
"salt",
".",
"loader",
".",
"grains",
"(",
"__opts__",
")",
"__salt__",
"=",
"salt",
".",
"loader",
".",
"minion_mods",
"(",
"__opts__",
")",
"if",
"'sentry_handler'",
"not",
"in",
"__opts__",
":",... | sets up the sentry handler | [
"sets",
"up",
"the",
"sentry",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/handlers/sentry_mod.py#L120-L235 | train |
saltstack/salt | salt/auth/ldap.py | _config | def _config(key, mandatory=True, opts=None):
'''
Return a value for 'name' from master config file options or defaults.
'''
try:
if opts:
value = opts['auth.ldap.{0}'.format(key)]
else:
value = __opts__['auth.ldap.{0}'.format(key)]
except KeyError:
try:
value = __defopts__['auth.ldap.{0}'.format(key)]
except KeyError:
if mandatory:
msg = 'missing auth.ldap.{0} in master config'.format(key)
raise SaltInvocationError(msg)
return False
return value | python | def _config(key, mandatory=True, opts=None):
'''
Return a value for 'name' from master config file options or defaults.
'''
try:
if opts:
value = opts['auth.ldap.{0}'.format(key)]
else:
value = __opts__['auth.ldap.{0}'.format(key)]
except KeyError:
try:
value = __defopts__['auth.ldap.{0}'.format(key)]
except KeyError:
if mandatory:
msg = 'missing auth.ldap.{0} in master config'.format(key)
raise SaltInvocationError(msg)
return False
return value | [
"def",
"_config",
"(",
"key",
",",
"mandatory",
"=",
"True",
",",
"opts",
"=",
"None",
")",
":",
"try",
":",
"if",
"opts",
":",
"value",
"=",
"opts",
"[",
"'auth.ldap.{0}'",
".",
"format",
"(",
"key",
")",
"]",
"else",
":",
"value",
"=",
"__opts__"... | Return a value for 'name' from master config file options or defaults. | [
"Return",
"a",
"value",
"for",
"name",
"from",
"master",
"config",
"file",
"options",
"or",
"defaults",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/ldap.py#L51-L68 | train |
saltstack/salt | salt/auth/ldap.py | _render_template | def _render_template(param, username):
'''
Render config template, substituting username where found.
'''
env = Environment()
template = env.from_string(param)
variables = {'username': username}
return template.render(variables) | python | def _render_template(param, username):
'''
Render config template, substituting username where found.
'''
env = Environment()
template = env.from_string(param)
variables = {'username': username}
return template.render(variables) | [
"def",
"_render_template",
"(",
"param",
",",
"username",
")",
":",
"env",
"=",
"Environment",
"(",
")",
"template",
"=",
"env",
".",
"from_string",
"(",
"param",
")",
"variables",
"=",
"{",
"'username'",
":",
"username",
"}",
"return",
"template",
".",
... | Render config template, substituting username where found. | [
"Render",
"config",
"template",
"substituting",
"username",
"where",
"found",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/ldap.py#L71-L78 | train |
saltstack/salt | salt/auth/ldap.py | _bind_for_search | def _bind_for_search(anonymous=False, opts=None):
'''
Bind with binddn and bindpw only for searching LDAP
:param anonymous: Try binding anonymously
:param opts: Pass in when __opts__ is not available
:return: LDAPConnection object
'''
# Get config params; create connection dictionary
connargs = {}
# config params (auth.ldap.*)
params = {
'mandatory': ['uri', 'server', 'port', 'starttls', 'tls',
'no_verify', 'anonymous',
'accountattributename', 'activedirectory'],
'additional': ['binddn', 'bindpw', 'filter', 'groupclass',
'auth_by_group_membership_only'],
}
paramvalues = {}
for param in params['mandatory']:
paramvalues[param] = _config(param, opts=opts)
for param in params['additional']:
paramvalues[param] = _config(param, mandatory=False, opts=opts)
paramvalues['anonymous'] = anonymous
# Only add binddn/bindpw to the connargs when they're set, as they're not
# mandatory for initializing the LDAP object, but if they're provided
# initially, a bind attempt will be done during the initialization to
# validate them
if paramvalues['binddn']:
connargs['binddn'] = paramvalues['binddn']
if paramvalues['bindpw']:
params['mandatory'].append('bindpw')
for name in params['mandatory']:
connargs[name] = paramvalues[name]
if not paramvalues['anonymous']:
if paramvalues['binddn'] and paramvalues['bindpw']:
# search for the user's DN to be used for the actual authentication
return _LDAPConnection(**connargs).ldap | python | def _bind_for_search(anonymous=False, opts=None):
'''
Bind with binddn and bindpw only for searching LDAP
:param anonymous: Try binding anonymously
:param opts: Pass in when __opts__ is not available
:return: LDAPConnection object
'''
# Get config params; create connection dictionary
connargs = {}
# config params (auth.ldap.*)
params = {
'mandatory': ['uri', 'server', 'port', 'starttls', 'tls',
'no_verify', 'anonymous',
'accountattributename', 'activedirectory'],
'additional': ['binddn', 'bindpw', 'filter', 'groupclass',
'auth_by_group_membership_only'],
}
paramvalues = {}
for param in params['mandatory']:
paramvalues[param] = _config(param, opts=opts)
for param in params['additional']:
paramvalues[param] = _config(param, mandatory=False, opts=opts)
paramvalues['anonymous'] = anonymous
# Only add binddn/bindpw to the connargs when they're set, as they're not
# mandatory for initializing the LDAP object, but if they're provided
# initially, a bind attempt will be done during the initialization to
# validate them
if paramvalues['binddn']:
connargs['binddn'] = paramvalues['binddn']
if paramvalues['bindpw']:
params['mandatory'].append('bindpw')
for name in params['mandatory']:
connargs[name] = paramvalues[name]
if not paramvalues['anonymous']:
if paramvalues['binddn'] and paramvalues['bindpw']:
# search for the user's DN to be used for the actual authentication
return _LDAPConnection(**connargs).ldap | [
"def",
"_bind_for_search",
"(",
"anonymous",
"=",
"False",
",",
"opts",
"=",
"None",
")",
":",
"# Get config params; create connection dictionary",
"connargs",
"=",
"{",
"}",
"# config params (auth.ldap.*)",
"params",
"=",
"{",
"'mandatory'",
":",
"[",
"'uri'",
",",... | Bind with binddn and bindpw only for searching LDAP
:param anonymous: Try binding anonymously
:param opts: Pass in when __opts__ is not available
:return: LDAPConnection object | [
"Bind",
"with",
"binddn",
"and",
"bindpw",
"only",
"for",
"searching",
"LDAP",
":",
"param",
"anonymous",
":",
"Try",
"binding",
"anonymously",
":",
"param",
"opts",
":",
"Pass",
"in",
"when",
"__opts__",
"is",
"not",
"available",
":",
"return",
":",
"LDAP... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/ldap.py#L140-L183 | train |
saltstack/salt | salt/auth/ldap.py | _bind | def _bind(username, password, anonymous=False, opts=None):
'''
Authenticate via an LDAP bind
'''
# Get config params; create connection dictionary
basedn = _config('basedn', opts=opts)
scope = _config('scope', opts=opts)
connargs = {}
# config params (auth.ldap.*)
params = {
'mandatory': ['uri', 'server', 'port', 'starttls', 'tls',
'no_verify', 'anonymous',
'accountattributename', 'activedirectory'],
'additional': ['binddn', 'bindpw', 'filter', 'groupclass',
'auth_by_group_membership_only'],
}
paramvalues = {}
for param in params['mandatory']:
paramvalues[param] = _config(param, opts=opts)
for param in params['additional']:
paramvalues[param] = _config(param, mandatory=False, opts=opts)
paramvalues['anonymous'] = anonymous
if paramvalues['binddn']:
# the binddn can also be composited, e.g.
# - {{ username }}@domain.com
# - cn={{ username }},ou=users,dc=company,dc=tld
# so make sure to render it first before using it
paramvalues['binddn'] = _render_template(paramvalues['binddn'], username)
paramvalues['binddn'] = ldap.filter.escape_filter_chars(paramvalues['binddn'])
if paramvalues['filter']:
escaped_username = ldap.filter.escape_filter_chars(username)
paramvalues['filter'] = _render_template(paramvalues['filter'], escaped_username)
# Only add binddn/bindpw to the connargs when they're set, as they're not
# mandatory for initializing the LDAP object, but if they're provided
# initially, a bind attempt will be done during the initialization to
# validate them
if paramvalues['binddn']:
connargs['binddn'] = paramvalues['binddn']
if paramvalues['bindpw']:
params['mandatory'].append('bindpw')
for name in params['mandatory']:
connargs[name] = paramvalues[name]
if not paramvalues['anonymous']:
if paramvalues['binddn'] and paramvalues['bindpw']:
# search for the user's DN to be used for the actual authentication
_ldap = _LDAPConnection(**connargs).ldap
log.debug(
'Running LDAP user dn search with filter:%s, dn:%s, '
'scope:%s', paramvalues['filter'], basedn, scope
)
result = _ldap.search_s(basedn, int(scope), paramvalues['filter'])
if not result:
log.warning('Unable to find user %s', username)
return False
elif len(result) > 1:
# Active Directory returns something odd. Though we do not
# chase referrals (ldap.set_option(ldap.OPT_REFERRALS, 0) above)
# it still appears to return several entries for other potential
# sources for a match. All these sources have None for the
# CN (ldap array return items are tuples: (cn, ldap entry))
# But the actual CNs are at the front of the list.
# So with some list comprehension magic, extract the first tuple
# entry from all the results, create a list from those,
# and count the ones that are not None. If that total is more than one
# we need to error out because the ldap filter isn't narrow enough.
cns = [tup[0] for tup in result]
total_not_none = sum(1 for c in cns if c is not None)
if total_not_none > 1:
log.error('LDAP lookup found multiple results for user %s', username)
return False
elif total_not_none == 0:
log.error('LDAP lookup--unable to find CN matching user %s', username)
return False
connargs['binddn'] = result[0][0]
if paramvalues['binddn'] and not paramvalues['bindpw']:
connargs['binddn'] = paramvalues['binddn']
elif paramvalues['binddn'] and not paramvalues['bindpw']:
connargs['binddn'] = paramvalues['binddn']
# Update connection dictionary with the user's password
connargs['bindpw'] = password
# Attempt bind with user dn and password
if paramvalues['anonymous']:
log.debug('Attempting anonymous LDAP bind')
else:
log.debug('Attempting LDAP bind with user dn: %s', connargs['binddn'])
try:
ldap_conn = _LDAPConnection(**connargs).ldap
except Exception:
connargs.pop('bindpw', None) # Don't log the password
log.error('Failed to authenticate user dn via LDAP: %s', connargs)
log.debug('Error authenticating user dn via LDAP:', exc_info=True)
return False
log.debug('Successfully authenticated user dn via LDAP: %s', connargs['binddn'])
return ldap_conn | python | def _bind(username, password, anonymous=False, opts=None):
'''
Authenticate via an LDAP bind
'''
# Get config params; create connection dictionary
basedn = _config('basedn', opts=opts)
scope = _config('scope', opts=opts)
connargs = {}
# config params (auth.ldap.*)
params = {
'mandatory': ['uri', 'server', 'port', 'starttls', 'tls',
'no_verify', 'anonymous',
'accountattributename', 'activedirectory'],
'additional': ['binddn', 'bindpw', 'filter', 'groupclass',
'auth_by_group_membership_only'],
}
paramvalues = {}
for param in params['mandatory']:
paramvalues[param] = _config(param, opts=opts)
for param in params['additional']:
paramvalues[param] = _config(param, mandatory=False, opts=opts)
paramvalues['anonymous'] = anonymous
if paramvalues['binddn']:
# the binddn can also be composited, e.g.
# - {{ username }}@domain.com
# - cn={{ username }},ou=users,dc=company,dc=tld
# so make sure to render it first before using it
paramvalues['binddn'] = _render_template(paramvalues['binddn'], username)
paramvalues['binddn'] = ldap.filter.escape_filter_chars(paramvalues['binddn'])
if paramvalues['filter']:
escaped_username = ldap.filter.escape_filter_chars(username)
paramvalues['filter'] = _render_template(paramvalues['filter'], escaped_username)
# Only add binddn/bindpw to the connargs when they're set, as they're not
# mandatory for initializing the LDAP object, but if they're provided
# initially, a bind attempt will be done during the initialization to
# validate them
if paramvalues['binddn']:
connargs['binddn'] = paramvalues['binddn']
if paramvalues['bindpw']:
params['mandatory'].append('bindpw')
for name in params['mandatory']:
connargs[name] = paramvalues[name]
if not paramvalues['anonymous']:
if paramvalues['binddn'] and paramvalues['bindpw']:
# search for the user's DN to be used for the actual authentication
_ldap = _LDAPConnection(**connargs).ldap
log.debug(
'Running LDAP user dn search with filter:%s, dn:%s, '
'scope:%s', paramvalues['filter'], basedn, scope
)
result = _ldap.search_s(basedn, int(scope), paramvalues['filter'])
if not result:
log.warning('Unable to find user %s', username)
return False
elif len(result) > 1:
# Active Directory returns something odd. Though we do not
# chase referrals (ldap.set_option(ldap.OPT_REFERRALS, 0) above)
# it still appears to return several entries for other potential
# sources for a match. All these sources have None for the
# CN (ldap array return items are tuples: (cn, ldap entry))
# But the actual CNs are at the front of the list.
# So with some list comprehension magic, extract the first tuple
# entry from all the results, create a list from those,
# and count the ones that are not None. If that total is more than one
# we need to error out because the ldap filter isn't narrow enough.
cns = [tup[0] for tup in result]
total_not_none = sum(1 for c in cns if c is not None)
if total_not_none > 1:
log.error('LDAP lookup found multiple results for user %s', username)
return False
elif total_not_none == 0:
log.error('LDAP lookup--unable to find CN matching user %s', username)
return False
connargs['binddn'] = result[0][0]
if paramvalues['binddn'] and not paramvalues['bindpw']:
connargs['binddn'] = paramvalues['binddn']
elif paramvalues['binddn'] and not paramvalues['bindpw']:
connargs['binddn'] = paramvalues['binddn']
# Update connection dictionary with the user's password
connargs['bindpw'] = password
# Attempt bind with user dn and password
if paramvalues['anonymous']:
log.debug('Attempting anonymous LDAP bind')
else:
log.debug('Attempting LDAP bind with user dn: %s', connargs['binddn'])
try:
ldap_conn = _LDAPConnection(**connargs).ldap
except Exception:
connargs.pop('bindpw', None) # Don't log the password
log.error('Failed to authenticate user dn via LDAP: %s', connargs)
log.debug('Error authenticating user dn via LDAP:', exc_info=True)
return False
log.debug('Successfully authenticated user dn via LDAP: %s', connargs['binddn'])
return ldap_conn | [
"def",
"_bind",
"(",
"username",
",",
"password",
",",
"anonymous",
"=",
"False",
",",
"opts",
"=",
"None",
")",
":",
"# Get config params; create connection dictionary",
"basedn",
"=",
"_config",
"(",
"'basedn'",
",",
"opts",
"=",
"opts",
")",
"scope",
"=",
... | Authenticate via an LDAP bind | [
"Authenticate",
"via",
"an",
"LDAP",
"bind"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/ldap.py#L186-L290 | train |
saltstack/salt | salt/auth/ldap.py | auth | def auth(username, password):
'''
Simple LDAP auth
'''
if not HAS_LDAP:
log.error('LDAP authentication requires python-ldap module')
return False
bind = None
# If bind credentials are configured, verify that we receive a valid bind
if _config('binddn', mandatory=False) and _config('bindpw', mandatory=False):
search_bind = _bind_for_search(anonymous=_config('anonymous', mandatory=False))
# If username & password are not None, attempt to verify they are valid
if search_bind and username and password:
bind = _bind(username, password,
anonymous=_config('auth_by_group_membership_only', mandatory=False)
and _config('anonymous', mandatory=False))
else:
bind = _bind(username, password,
anonymous=_config('auth_by_group_membership_only', mandatory=False)
and _config('anonymous', mandatory=False))
if bind:
log.debug('LDAP authentication successful')
return bind
log.error('LDAP _bind authentication FAILED')
return False | python | def auth(username, password):
'''
Simple LDAP auth
'''
if not HAS_LDAP:
log.error('LDAP authentication requires python-ldap module')
return False
bind = None
# If bind credentials are configured, verify that we receive a valid bind
if _config('binddn', mandatory=False) and _config('bindpw', mandatory=False):
search_bind = _bind_for_search(anonymous=_config('anonymous', mandatory=False))
# If username & password are not None, attempt to verify they are valid
if search_bind and username and password:
bind = _bind(username, password,
anonymous=_config('auth_by_group_membership_only', mandatory=False)
and _config('anonymous', mandatory=False))
else:
bind = _bind(username, password,
anonymous=_config('auth_by_group_membership_only', mandatory=False)
and _config('anonymous', mandatory=False))
if bind:
log.debug('LDAP authentication successful')
return bind
log.error('LDAP _bind authentication FAILED')
return False | [
"def",
"auth",
"(",
"username",
",",
"password",
")",
":",
"if",
"not",
"HAS_LDAP",
":",
"log",
".",
"error",
"(",
"'LDAP authentication requires python-ldap module'",
")",
"return",
"False",
"bind",
"=",
"None",
"# If bind credentials are configured, verify that we rec... | Simple LDAP auth | [
"Simple",
"LDAP",
"auth"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/ldap.py#L293-L322 | train |
saltstack/salt | salt/auth/ldap.py | groups | def groups(username, **kwargs):
'''
Authenticate against an LDAP group
Behavior is highly dependent on if Active Directory is in use.
AD handles group membership very differently than OpenLDAP.
See the :ref:`External Authentication <acl-eauth>` documentation for a thorough
discussion of available parameters for customizing the search.
OpenLDAP allows you to search for all groups in the directory
and returns members of those groups. Then we check against
the username entered.
'''
group_list = []
# If bind credentials are configured, use them instead of user's
if _config('binddn', mandatory=False) and _config('bindpw', mandatory=False):
bind = _bind_for_search(anonymous=_config('anonymous', mandatory=False))
else:
bind = _bind(username, kwargs.get('password', ''),
anonymous=_config('auth_by_group_membership_only', mandatory=False)
and _config('anonymous', mandatory=False))
if bind:
log.debug('ldap bind to determine group membership succeeded!')
if _config('activedirectory'):
try:
get_user_dn_search = '(&({0}={1})(objectClass={2}))'.format(_config('accountattributename'),
username,
_config('persontype'))
user_dn_results = bind.search_s(_config('basedn'),
ldap.SCOPE_SUBTREE,
get_user_dn_search, [str('distinguishedName')]) # future lint: disable=blacklisted-function
except Exception as e:
log.error('Exception thrown while looking up user DN in AD: %s', e)
return group_list
if not user_dn_results:
log.error('Could not get distinguished name for user %s', username)
return group_list
# LDAP results are always tuples. First entry in the tuple is the DN
dn = ldap.filter.escape_filter_chars(user_dn_results[0][0])
ldap_search_string = '(&(member={0})(objectClass={1}))'.format(dn, _config('groupclass'))
log.debug('Running LDAP group membership search: %s', ldap_search_string)
try:
search_results = bind.search_s(_config('basedn'),
ldap.SCOPE_SUBTREE,
ldap_search_string,
[salt.utils.stringutils.to_str(_config('accountattributename')), str('cn')]) # future lint: disable=blacklisted-function
except Exception as e:
log.error('Exception thrown while retrieving group membership in AD: %s', e)
return group_list
for _, entry in search_results:
if 'cn' in entry:
group_list.append(salt.utils.stringutils.to_unicode(entry['cn'][0]))
log.debug('User %s is a member of groups: %s', username, group_list)
elif _config('freeipa'):
escaped_username = ldap.filter.escape_filter_chars(username)
search_base = _config('group_basedn')
search_string = _render_template(_config('group_filter'), escaped_username)
search_results = bind.search_s(search_base,
ldap.SCOPE_SUBTREE,
search_string,
[salt.utils.stringutils.to_str(_config('accountattributename')), salt.utils.stringutils.to_str(_config('groupattribute')), str('cn')]) # future lint: disable=blacklisted-function
for entry, result in search_results:
for user in itertools.chain(result.get(_config('accountattributename'), []),
result.get(_config('groupattribute'), [])):
if username == salt.utils.stringutils.to_unicode(user).split(',')[0].split('=')[-1]:
group_list.append(entry.split(',')[0].split('=')[-1])
log.debug('User %s is a member of groups: %s', username, group_list)
if not auth(username, kwargs['password']):
log.error('LDAP username and password do not match')
return []
else:
if _config('groupou'):
search_base = 'ou={0},{1}'.format(_config('groupou'), _config('basedn'))
else:
search_base = '{0}'.format(_config('basedn'))
search_string = '(&({0}={1})(objectClass={2}))'.format(_config('accountattributename'),
username, _config('groupclass'))
search_results = bind.search_s(search_base,
ldap.SCOPE_SUBTREE,
search_string,
[salt.utils.stringutils.to_str(_config('accountattributename')),
str('cn'), # future lint: disable=blacklisted-function
salt.utils.stringutils.to_str(_config('groupattribute'))])
for _, entry in search_results:
if username in salt.utils.data.decode(entry[_config('accountattributename')]):
group_list.append(salt.utils.stringutils.to_unicode(entry['cn'][0]))
for user, entry in search_results:
if username == salt.utils.stringutils.to_unicode(user).split(',')[0].split('=')[-1]:
for group in salt.utils.data.decode(entry[_config('groupattribute')]):
group_list.append(salt.utils.stringutils.to_unicode(group).split(',')[0].split('=')[-1])
log.debug('User %s is a member of groups: %s', username, group_list)
# Only test user auth on first call for job.
# 'show_jid' only exists on first payload so we can use that for the conditional.
if 'show_jid' in kwargs and not _bind(username, kwargs.get('password'),
anonymous=_config('auth_by_group_membership_only', mandatory=False) and
_config('anonymous', mandatory=False)):
log.error('LDAP username and password do not match')
return []
else:
log.error('ldap bind to determine group membership FAILED!')
return group_list | python | def groups(username, **kwargs):
'''
Authenticate against an LDAP group
Behavior is highly dependent on if Active Directory is in use.
AD handles group membership very differently than OpenLDAP.
See the :ref:`External Authentication <acl-eauth>` documentation for a thorough
discussion of available parameters for customizing the search.
OpenLDAP allows you to search for all groups in the directory
and returns members of those groups. Then we check against
the username entered.
'''
group_list = []
# If bind credentials are configured, use them instead of user's
if _config('binddn', mandatory=False) and _config('bindpw', mandatory=False):
bind = _bind_for_search(anonymous=_config('anonymous', mandatory=False))
else:
bind = _bind(username, kwargs.get('password', ''),
anonymous=_config('auth_by_group_membership_only', mandatory=False)
and _config('anonymous', mandatory=False))
if bind:
log.debug('ldap bind to determine group membership succeeded!')
if _config('activedirectory'):
try:
get_user_dn_search = '(&({0}={1})(objectClass={2}))'.format(_config('accountattributename'),
username,
_config('persontype'))
user_dn_results = bind.search_s(_config('basedn'),
ldap.SCOPE_SUBTREE,
get_user_dn_search, [str('distinguishedName')]) # future lint: disable=blacklisted-function
except Exception as e:
log.error('Exception thrown while looking up user DN in AD: %s', e)
return group_list
if not user_dn_results:
log.error('Could not get distinguished name for user %s', username)
return group_list
# LDAP results are always tuples. First entry in the tuple is the DN
dn = ldap.filter.escape_filter_chars(user_dn_results[0][0])
ldap_search_string = '(&(member={0})(objectClass={1}))'.format(dn, _config('groupclass'))
log.debug('Running LDAP group membership search: %s', ldap_search_string)
try:
search_results = bind.search_s(_config('basedn'),
ldap.SCOPE_SUBTREE,
ldap_search_string,
[salt.utils.stringutils.to_str(_config('accountattributename')), str('cn')]) # future lint: disable=blacklisted-function
except Exception as e:
log.error('Exception thrown while retrieving group membership in AD: %s', e)
return group_list
for _, entry in search_results:
if 'cn' in entry:
group_list.append(salt.utils.stringutils.to_unicode(entry['cn'][0]))
log.debug('User %s is a member of groups: %s', username, group_list)
elif _config('freeipa'):
escaped_username = ldap.filter.escape_filter_chars(username)
search_base = _config('group_basedn')
search_string = _render_template(_config('group_filter'), escaped_username)
search_results = bind.search_s(search_base,
ldap.SCOPE_SUBTREE,
search_string,
[salt.utils.stringutils.to_str(_config('accountattributename')), salt.utils.stringutils.to_str(_config('groupattribute')), str('cn')]) # future lint: disable=blacklisted-function
for entry, result in search_results:
for user in itertools.chain(result.get(_config('accountattributename'), []),
result.get(_config('groupattribute'), [])):
if username == salt.utils.stringutils.to_unicode(user).split(',')[0].split('=')[-1]:
group_list.append(entry.split(',')[0].split('=')[-1])
log.debug('User %s is a member of groups: %s', username, group_list)
if not auth(username, kwargs['password']):
log.error('LDAP username and password do not match')
return []
else:
if _config('groupou'):
search_base = 'ou={0},{1}'.format(_config('groupou'), _config('basedn'))
else:
search_base = '{0}'.format(_config('basedn'))
search_string = '(&({0}={1})(objectClass={2}))'.format(_config('accountattributename'),
username, _config('groupclass'))
search_results = bind.search_s(search_base,
ldap.SCOPE_SUBTREE,
search_string,
[salt.utils.stringutils.to_str(_config('accountattributename')),
str('cn'), # future lint: disable=blacklisted-function
salt.utils.stringutils.to_str(_config('groupattribute'))])
for _, entry in search_results:
if username in salt.utils.data.decode(entry[_config('accountattributename')]):
group_list.append(salt.utils.stringutils.to_unicode(entry['cn'][0]))
for user, entry in search_results:
if username == salt.utils.stringutils.to_unicode(user).split(',')[0].split('=')[-1]:
for group in salt.utils.data.decode(entry[_config('groupattribute')]):
group_list.append(salt.utils.stringutils.to_unicode(group).split(',')[0].split('=')[-1])
log.debug('User %s is a member of groups: %s', username, group_list)
# Only test user auth on first call for job.
# 'show_jid' only exists on first payload so we can use that for the conditional.
if 'show_jid' in kwargs and not _bind(username, kwargs.get('password'),
anonymous=_config('auth_by_group_membership_only', mandatory=False) and
_config('anonymous', mandatory=False)):
log.error('LDAP username and password do not match')
return []
else:
log.error('ldap bind to determine group membership FAILED!')
return group_list | [
"def",
"groups",
"(",
"username",
",",
"*",
"*",
"kwargs",
")",
":",
"group_list",
"=",
"[",
"]",
"# If bind credentials are configured, use them instead of user's",
"if",
"_config",
"(",
"'binddn'",
",",
"mandatory",
"=",
"False",
")",
"and",
"_config",
"(",
"'... | Authenticate against an LDAP group
Behavior is highly dependent on if Active Directory is in use.
AD handles group membership very differently than OpenLDAP.
See the :ref:`External Authentication <acl-eauth>` documentation for a thorough
discussion of available parameters for customizing the search.
OpenLDAP allows you to search for all groups in the directory
and returns members of those groups. Then we check against
the username entered. | [
"Authenticate",
"against",
"an",
"LDAP",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/ldap.py#L325-L436 | train |
saltstack/salt | salt/auth/ldap.py | process_acl | def process_acl(auth_list, opts=None):
'''
Query LDAP, retrieve list of minion_ids from an OU or other search.
For each minion_id returned from the LDAP search, copy the perms
matchers into the auth dictionary
:param auth_list:
:param opts: __opts__ for when __opts__ is not injected
:return: Modified auth list.
'''
ou_names = []
for item in auth_list:
if isinstance(item, six.string_types):
continue
ou_names.extend([potential_ou for potential_ou in item.keys() if potential_ou.startswith('ldap(')])
if ou_names:
auth_list = __expand_ldap_entries(auth_list, opts)
return auth_list | python | def process_acl(auth_list, opts=None):
'''
Query LDAP, retrieve list of minion_ids from an OU or other search.
For each minion_id returned from the LDAP search, copy the perms
matchers into the auth dictionary
:param auth_list:
:param opts: __opts__ for when __opts__ is not injected
:return: Modified auth list.
'''
ou_names = []
for item in auth_list:
if isinstance(item, six.string_types):
continue
ou_names.extend([potential_ou for potential_ou in item.keys() if potential_ou.startswith('ldap(')])
if ou_names:
auth_list = __expand_ldap_entries(auth_list, opts)
return auth_list | [
"def",
"process_acl",
"(",
"auth_list",
",",
"opts",
"=",
"None",
")",
":",
"ou_names",
"=",
"[",
"]",
"for",
"item",
"in",
"auth_list",
":",
"if",
"isinstance",
"(",
"item",
",",
"six",
".",
"string_types",
")",
":",
"continue",
"ou_names",
".",
"exte... | Query LDAP, retrieve list of minion_ids from an OU or other search.
For each minion_id returned from the LDAP search, copy the perms
matchers into the auth dictionary
:param auth_list:
:param opts: __opts__ for when __opts__ is not injected
:return: Modified auth list. | [
"Query",
"LDAP",
"retrieve",
"list",
"of",
"minion_ids",
"from",
"an",
"OU",
"or",
"other",
"search",
".",
"For",
"each",
"minion_id",
"returned",
"from",
"the",
"LDAP",
"search",
"copy",
"the",
"perms",
"matchers",
"into",
"the",
"auth",
"dictionary",
":",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/ldap.py#L509-L525 | train |
saltstack/salt | salt/modules/napalm_mod.py | _get_netmiko_args | def _get_netmiko_args(optional_args):
'''
Check for Netmiko arguments that were passed in as NAPALM optional arguments.
Return a dictionary of these optional args that will be passed into the
Netmiko ConnectHandler call.
.. note::
This is a port of the NAPALM helper for backwards compatibility with
older versions of NAPALM, and stability across Salt features.
If the netmiko helpers module is available however, it will prefer that
implementation nevertheless.
'''
if HAS_NETMIKO_HELPERS:
return napalm.base.netmiko_helpers.netmiko_args(optional_args)
# Older version don't have the netmiko_helpers module, the following code is
# simply a port from the NAPALM code base, for backwards compatibility:
# https://github.com/napalm-automation/napalm/blob/develop/napalm/base/netmiko_helpers.py
netmiko_args, _, _, netmiko_defaults = inspect.getargspec(BaseConnection.__init__)
check_self = netmiko_args.pop(0)
if check_self != 'self':
raise ValueError('Error processing Netmiko arguments')
netmiko_argument_map = dict(six.moves.zip(netmiko_args, netmiko_defaults))
# Netmiko arguments that are integrated into NAPALM already
netmiko_filter = ['ip', 'host', 'username', 'password', 'device_type', 'timeout']
# Filter out all of the arguments that are integrated into NAPALM
for k in netmiko_filter:
netmiko_argument_map.pop(k)
# Check if any of these arguments were passed in as NAPALM optional_args
netmiko_optional_args = {}
for k, v in six.iteritems(netmiko_argument_map):
try:
netmiko_optional_args[k] = optional_args[k]
except KeyError:
pass
# Return these arguments for use with establishing Netmiko SSH connection
return netmiko_optional_args | python | def _get_netmiko_args(optional_args):
'''
Check for Netmiko arguments that were passed in as NAPALM optional arguments.
Return a dictionary of these optional args that will be passed into the
Netmiko ConnectHandler call.
.. note::
This is a port of the NAPALM helper for backwards compatibility with
older versions of NAPALM, and stability across Salt features.
If the netmiko helpers module is available however, it will prefer that
implementation nevertheless.
'''
if HAS_NETMIKO_HELPERS:
return napalm.base.netmiko_helpers.netmiko_args(optional_args)
# Older version don't have the netmiko_helpers module, the following code is
# simply a port from the NAPALM code base, for backwards compatibility:
# https://github.com/napalm-automation/napalm/blob/develop/napalm/base/netmiko_helpers.py
netmiko_args, _, _, netmiko_defaults = inspect.getargspec(BaseConnection.__init__)
check_self = netmiko_args.pop(0)
if check_self != 'self':
raise ValueError('Error processing Netmiko arguments')
netmiko_argument_map = dict(six.moves.zip(netmiko_args, netmiko_defaults))
# Netmiko arguments that are integrated into NAPALM already
netmiko_filter = ['ip', 'host', 'username', 'password', 'device_type', 'timeout']
# Filter out all of the arguments that are integrated into NAPALM
for k in netmiko_filter:
netmiko_argument_map.pop(k)
# Check if any of these arguments were passed in as NAPALM optional_args
netmiko_optional_args = {}
for k, v in six.iteritems(netmiko_argument_map):
try:
netmiko_optional_args[k] = optional_args[k]
except KeyError:
pass
# Return these arguments for use with establishing Netmiko SSH connection
return netmiko_optional_args | [
"def",
"_get_netmiko_args",
"(",
"optional_args",
")",
":",
"if",
"HAS_NETMIKO_HELPERS",
":",
"return",
"napalm",
".",
"base",
".",
"netmiko_helpers",
".",
"netmiko_args",
"(",
"optional_args",
")",
"# Older version don't have the netmiko_helpers module, the following code is... | Check for Netmiko arguments that were passed in as NAPALM optional arguments.
Return a dictionary of these optional args that will be passed into the
Netmiko ConnectHandler call.
.. note::
This is a port of the NAPALM helper for backwards compatibility with
older versions of NAPALM, and stability across Salt features.
If the netmiko helpers module is available however, it will prefer that
implementation nevertheless. | [
"Check",
"for",
"Netmiko",
"arguments",
"that",
"were",
"passed",
"in",
"as",
"NAPALM",
"optional",
"arguments",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L81-L118 | train |
saltstack/salt | salt/modules/napalm_mod.py | reconnect | def reconnect(force=False, **kwargs): # pylint: disable=unused-argument
'''
Reconnect the NAPALM proxy when the connection
is dropped by the network device.
The connection can be forced to be restarted
using the ``force`` argument.
.. note::
This function can be used only when running proxy minions.
CLI Example:
.. code-block:: bash
salt '*' napalm.reconnect
salt '*' napalm.reconnect force=True
'''
default_ret = {
'out': None,
'result': True,
'comment': 'Already alive.'
}
if not salt.utils.napalm.is_proxy(__opts__):
# regular minion is always alive
# otherwise, the user would not be able to execute this command
return default_ret
is_alive = alive()
log.debug('Is alive fetch:')
log.debug(is_alive)
if not is_alive.get('result', False) or\
not is_alive.get('out', False) or\
not is_alive.get('out', {}).get('is_alive', False) or\
force: # even if alive, but the user wants to force a restart
proxyid = __opts__.get('proxyid') or __opts__.get('id')
# close the connection
log.info('Closing the NAPALM proxy connection with %s', proxyid)
salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'close',
**{}
)
# and re-open
log.info('Re-opening the NAPALM proxy connection with %s', proxyid)
salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'open',
**{}
)
default_ret.update({
'comment': 'Connection restarted!'
})
return default_ret
# otherwise, I have nothing to do here:
return default_ret | python | def reconnect(force=False, **kwargs): # pylint: disable=unused-argument
'''
Reconnect the NAPALM proxy when the connection
is dropped by the network device.
The connection can be forced to be restarted
using the ``force`` argument.
.. note::
This function can be used only when running proxy minions.
CLI Example:
.. code-block:: bash
salt '*' napalm.reconnect
salt '*' napalm.reconnect force=True
'''
default_ret = {
'out': None,
'result': True,
'comment': 'Already alive.'
}
if not salt.utils.napalm.is_proxy(__opts__):
# regular minion is always alive
# otherwise, the user would not be able to execute this command
return default_ret
is_alive = alive()
log.debug('Is alive fetch:')
log.debug(is_alive)
if not is_alive.get('result', False) or\
not is_alive.get('out', False) or\
not is_alive.get('out', {}).get('is_alive', False) or\
force: # even if alive, but the user wants to force a restart
proxyid = __opts__.get('proxyid') or __opts__.get('id')
# close the connection
log.info('Closing the NAPALM proxy connection with %s', proxyid)
salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'close',
**{}
)
# and re-open
log.info('Re-opening the NAPALM proxy connection with %s', proxyid)
salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'open',
**{}
)
default_ret.update({
'comment': 'Connection restarted!'
})
return default_ret
# otherwise, I have nothing to do here:
return default_ret | [
"def",
"reconnect",
"(",
"force",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"default_ret",
"=",
"{",
"'out'",
":",
"None",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"'Already alive.'",
"}",
"if",
"not",
... | Reconnect the NAPALM proxy when the connection
is dropped by the network device.
The connection can be forced to be restarted
using the ``force`` argument.
.. note::
This function can be used only when running proxy minions.
CLI Example:
.. code-block:: bash
salt '*' napalm.reconnect
salt '*' napalm.reconnect force=True | [
"Reconnect",
"the",
"NAPALM",
"proxy",
"when",
"the",
"connection",
"is",
"dropped",
"by",
"the",
"network",
"device",
".",
"The",
"connection",
"can",
"be",
"forced",
"to",
"be",
"restarted",
"using",
"the",
"force",
"argument",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L195-L249 | train |
saltstack/salt | salt/modules/napalm_mod.py | call | def call(method, *args, **kwargs):
'''
Execute arbitrary methods from the NAPALM library.
To see the expected output, please consult the NAPALM documentation.
.. note::
This feature is not recommended to be used in production.
It should be used for testing only!
CLI Example:
.. code-block:: bash
salt '*' napalm.call get_lldp_neighbors
salt '*' napalm.call get_firewall_policies
salt '*' napalm.call get_bgp_config group='my-group'
'''
clean_kwargs = {}
for karg, warg in six.iteritems(kwargs):
# remove the __pub args
if not karg.startswith('__pub_'):
clean_kwargs[karg] = warg
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
method,
*args,
**clean_kwargs
) | python | def call(method, *args, **kwargs):
'''
Execute arbitrary methods from the NAPALM library.
To see the expected output, please consult the NAPALM documentation.
.. note::
This feature is not recommended to be used in production.
It should be used for testing only!
CLI Example:
.. code-block:: bash
salt '*' napalm.call get_lldp_neighbors
salt '*' napalm.call get_firewall_policies
salt '*' napalm.call get_bgp_config group='my-group'
'''
clean_kwargs = {}
for karg, warg in six.iteritems(kwargs):
# remove the __pub args
if not karg.startswith('__pub_'):
clean_kwargs[karg] = warg
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
method,
*args,
**clean_kwargs
) | [
"def",
"call",
"(",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"clean_kwargs",
"=",
"{",
"}",
"for",
"karg",
",",
"warg",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
":",
"# remove the __pub args",
"if",
"not",
"karg",
".",... | Execute arbitrary methods from the NAPALM library.
To see the expected output, please consult the NAPALM documentation.
.. note::
This feature is not recommended to be used in production.
It should be used for testing only!
CLI Example:
.. code-block:: bash
salt '*' napalm.call get_lldp_neighbors
salt '*' napalm.call get_firewall_policies
salt '*' napalm.call get_bgp_config group='my-group' | [
"Execute",
"arbitrary",
"methods",
"from",
"the",
"NAPALM",
"library",
".",
"To",
"see",
"the",
"expected",
"output",
"please",
"consult",
"the",
"NAPALM",
"documentation",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L253-L281 | train |
saltstack/salt | salt/modules/napalm_mod.py | compliance_report | def compliance_report(filepath=None,
string=None,
renderer='jinja|yaml',
**kwargs):
'''
Return the compliance report.
filepath
The absolute path to the validation file.
.. versionchanged:: 2019.2.0
Beginning with release codename ``2019.2.0``, this function has been
enhanced, to be able to leverage the multi-engine template rendering
of Salt, besides the possibility to retrieve the file source from
remote systems, the URL schemes supported being:
- ``salt://``
- ``http://`` and ``https://``
- ``ftp://``
- ``s3://``
- ``swift:/``
Or on the local file system (on the Minion).
.. note::
The rendering result does not necessarily need to be YAML, instead
it can be any format interpreted by Salt's rendering pipeline
(including pure Python).
string
.. versionadded:: 2019.2.0
The compliance report send as inline string, to be used as the file to
send through the renderer system. Note, not all renderer modules can
work with strings; the 'py' renderer requires a file, for example.
renderer: ``jinja|yaml``
.. versionadded:: 2019.2.0
The renderer pipe to send the file through; this is overridden by a
"she-bang" at the top of the file.
kwargs
.. versionchanged:: 2019.2.0
Keyword args to pass to Salt's compile_template() function.
CLI Example:
.. code-block:: bash
salt '*' napalm.compliance_report ~/validate.yml
salt '*' napalm.compliance_report salt://path/to/validator.sls
Validation File Example (pure YAML):
.. code-block:: yaml
- get_facts:
os_version: 4.17
- get_interfaces_ip:
Management1:
ipv4:
10.0.2.14:
prefix_length: 24
_mode: strict
Validation File Example (as Jinja + YAML):
.. code-block:: yaml
- get_facts:
os_version: {{ grains.version }}
- get_interfaces_ip:
Loopback0:
ipv4:
{{ grains.lo0.ipv4 }}:
prefix_length: 24
_mode: strict
- get_bgp_neighbors: {{ pillar.bgp.neighbors }}
Output Example:
.. code-block:: yaml
device1:
----------
comment:
out:
----------
complies:
False
get_facts:
----------
complies:
False
extra:
missing:
present:
----------
os_version:
----------
actual_value:
15.1F6-S1.4
complies:
False
nested:
False
get_interfaces_ip:
----------
complies:
False
extra:
missing:
- Management1
present:
----------
skipped:
result:
True
'''
validation_string = __salt__['slsutil.renderer'](path=filepath,
string=string,
default_renderer=renderer,
**kwargs)
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compliance_report',
validation_source=validation_string
) | python | def compliance_report(filepath=None,
string=None,
renderer='jinja|yaml',
**kwargs):
'''
Return the compliance report.
filepath
The absolute path to the validation file.
.. versionchanged:: 2019.2.0
Beginning with release codename ``2019.2.0``, this function has been
enhanced, to be able to leverage the multi-engine template rendering
of Salt, besides the possibility to retrieve the file source from
remote systems, the URL schemes supported being:
- ``salt://``
- ``http://`` and ``https://``
- ``ftp://``
- ``s3://``
- ``swift:/``
Or on the local file system (on the Minion).
.. note::
The rendering result does not necessarily need to be YAML, instead
it can be any format interpreted by Salt's rendering pipeline
(including pure Python).
string
.. versionadded:: 2019.2.0
The compliance report send as inline string, to be used as the file to
send through the renderer system. Note, not all renderer modules can
work with strings; the 'py' renderer requires a file, for example.
renderer: ``jinja|yaml``
.. versionadded:: 2019.2.0
The renderer pipe to send the file through; this is overridden by a
"she-bang" at the top of the file.
kwargs
.. versionchanged:: 2019.2.0
Keyword args to pass to Salt's compile_template() function.
CLI Example:
.. code-block:: bash
salt '*' napalm.compliance_report ~/validate.yml
salt '*' napalm.compliance_report salt://path/to/validator.sls
Validation File Example (pure YAML):
.. code-block:: yaml
- get_facts:
os_version: 4.17
- get_interfaces_ip:
Management1:
ipv4:
10.0.2.14:
prefix_length: 24
_mode: strict
Validation File Example (as Jinja + YAML):
.. code-block:: yaml
- get_facts:
os_version: {{ grains.version }}
- get_interfaces_ip:
Loopback0:
ipv4:
{{ grains.lo0.ipv4 }}:
prefix_length: 24
_mode: strict
- get_bgp_neighbors: {{ pillar.bgp.neighbors }}
Output Example:
.. code-block:: yaml
device1:
----------
comment:
out:
----------
complies:
False
get_facts:
----------
complies:
False
extra:
missing:
present:
----------
os_version:
----------
actual_value:
15.1F6-S1.4
complies:
False
nested:
False
get_interfaces_ip:
----------
complies:
False
extra:
missing:
- Management1
present:
----------
skipped:
result:
True
'''
validation_string = __salt__['slsutil.renderer'](path=filepath,
string=string,
default_renderer=renderer,
**kwargs)
return salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'compliance_report',
validation_source=validation_string
) | [
"def",
"compliance_report",
"(",
"filepath",
"=",
"None",
",",
"string",
"=",
"None",
",",
"renderer",
"=",
"'jinja|yaml'",
",",
"*",
"*",
"kwargs",
")",
":",
"validation_string",
"=",
"__salt__",
"[",
"'slsutil.renderer'",
"]",
"(",
"path",
"=",
"filepath",... | Return the compliance report.
filepath
The absolute path to the validation file.
.. versionchanged:: 2019.2.0
Beginning with release codename ``2019.2.0``, this function has been
enhanced, to be able to leverage the multi-engine template rendering
of Salt, besides the possibility to retrieve the file source from
remote systems, the URL schemes supported being:
- ``salt://``
- ``http://`` and ``https://``
- ``ftp://``
- ``s3://``
- ``swift:/``
Or on the local file system (on the Minion).
.. note::
The rendering result does not necessarily need to be YAML, instead
it can be any format interpreted by Salt's rendering pipeline
(including pure Python).
string
.. versionadded:: 2019.2.0
The compliance report send as inline string, to be used as the file to
send through the renderer system. Note, not all renderer modules can
work with strings; the 'py' renderer requires a file, for example.
renderer: ``jinja|yaml``
.. versionadded:: 2019.2.0
The renderer pipe to send the file through; this is overridden by a
"she-bang" at the top of the file.
kwargs
.. versionchanged:: 2019.2.0
Keyword args to pass to Salt's compile_template() function.
CLI Example:
.. code-block:: bash
salt '*' napalm.compliance_report ~/validate.yml
salt '*' napalm.compliance_report salt://path/to/validator.sls
Validation File Example (pure YAML):
.. code-block:: yaml
- get_facts:
os_version: 4.17
- get_interfaces_ip:
Management1:
ipv4:
10.0.2.14:
prefix_length: 24
_mode: strict
Validation File Example (as Jinja + YAML):
.. code-block:: yaml
- get_facts:
os_version: {{ grains.version }}
- get_interfaces_ip:
Loopback0:
ipv4:
{{ grains.lo0.ipv4 }}:
prefix_length: 24
_mode: strict
- get_bgp_neighbors: {{ pillar.bgp.neighbors }}
Output Example:
.. code-block:: yaml
device1:
----------
comment:
out:
----------
complies:
False
get_facts:
----------
complies:
False
extra:
missing:
present:
----------
os_version:
----------
actual_value:
15.1F6-S1.4
complies:
False
nested:
False
get_interfaces_ip:
----------
complies:
False
extra:
missing:
- Management1
present:
----------
skipped:
result:
True | [
"Return",
"the",
"compliance",
"report",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L285-L417 | train |
saltstack/salt | salt/modules/napalm_mod.py | netmiko_args | def netmiko_args(**kwargs):
'''
.. versionadded:: 2019.2.0
Return the key-value arguments used for the authentication arguments for
the netmiko module.
When running in a non-native NAPALM driver (e.g., ``panos``, `f5``, ``mos`` -
either from https://github.com/napalm-automation-community or defined in
user's own environment, one can specify the Netmiko device type (the
``device_type`` argument) via the ``netmiko_device_type_map`` configuration
option / Pillar key, e.g.,
.. code-block:: yaml
netmiko_device_type_map:
f5: f5_ltm
dellos10: dell_os10
The configuration above defines the mapping between the NAPALM ``os`` Grain
and the Netmiko ``device_type``, e.g., when the NAPALM Grain is ``f5``, it
would use the ``f5_ltm`` SSH Netmiko driver to execute commands over SSH on
the remote network device.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_args
'''
if not HAS_NETMIKO:
raise CommandExecutionError('Please install netmiko to be able to use this feature.')
kwargs = {}
napalm_opts = salt.utils.napalm.get_device_opts(__opts__, salt_obj=__salt__)
optional_args = napalm_opts['OPTIONAL_ARGS']
netmiko_args = _get_netmiko_args(optional_args)
kwargs['host'] = napalm_opts['HOSTNAME']
kwargs['username'] = napalm_opts['USERNAME']
kwargs['password'] = napalm_opts['PASSWORD']
kwargs['timeout'] = napalm_opts['TIMEOUT']
kwargs.update(netmiko_args)
netmiko_device_type_map = {
'junos': 'juniper_junos',
'ios': 'cisco_ios',
'iosxr': 'cisco_xr',
'eos': 'arista_eos',
'nxos_ssh': 'cisco_nxos',
'asa': 'cisco_asa',
'fortios': 'fortinet',
'panos': 'paloalto_panos',
'aos': 'alcatel_aos',
'vyos': 'vyos',
'f5': 'f5_ltm',
'ce': 'huawei',
's350': 'cisco_s300'
}
# If you have a device type that is not listed here, please submit a PR
# to add it, and/or add the map into your opts/Pillar: netmiko_device_type_map
# Example:
#
# netmiko_device_type_map:
# junos: juniper_junos
# ios: cisco_ios
#
#etc.
netmiko_device_type_map.update(__salt__['config.get']('netmiko_device_type_map', {}))
kwargs['device_type'] = netmiko_device_type_map[__grains__['os']]
return kwargs | python | def netmiko_args(**kwargs):
'''
.. versionadded:: 2019.2.0
Return the key-value arguments used for the authentication arguments for
the netmiko module.
When running in a non-native NAPALM driver (e.g., ``panos``, `f5``, ``mos`` -
either from https://github.com/napalm-automation-community or defined in
user's own environment, one can specify the Netmiko device type (the
``device_type`` argument) via the ``netmiko_device_type_map`` configuration
option / Pillar key, e.g.,
.. code-block:: yaml
netmiko_device_type_map:
f5: f5_ltm
dellos10: dell_os10
The configuration above defines the mapping between the NAPALM ``os`` Grain
and the Netmiko ``device_type``, e.g., when the NAPALM Grain is ``f5``, it
would use the ``f5_ltm`` SSH Netmiko driver to execute commands over SSH on
the remote network device.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_args
'''
if not HAS_NETMIKO:
raise CommandExecutionError('Please install netmiko to be able to use this feature.')
kwargs = {}
napalm_opts = salt.utils.napalm.get_device_opts(__opts__, salt_obj=__salt__)
optional_args = napalm_opts['OPTIONAL_ARGS']
netmiko_args = _get_netmiko_args(optional_args)
kwargs['host'] = napalm_opts['HOSTNAME']
kwargs['username'] = napalm_opts['USERNAME']
kwargs['password'] = napalm_opts['PASSWORD']
kwargs['timeout'] = napalm_opts['TIMEOUT']
kwargs.update(netmiko_args)
netmiko_device_type_map = {
'junos': 'juniper_junos',
'ios': 'cisco_ios',
'iosxr': 'cisco_xr',
'eos': 'arista_eos',
'nxos_ssh': 'cisco_nxos',
'asa': 'cisco_asa',
'fortios': 'fortinet',
'panos': 'paloalto_panos',
'aos': 'alcatel_aos',
'vyos': 'vyos',
'f5': 'f5_ltm',
'ce': 'huawei',
's350': 'cisco_s300'
}
# If you have a device type that is not listed here, please submit a PR
# to add it, and/or add the map into your opts/Pillar: netmiko_device_type_map
# Example:
#
# netmiko_device_type_map:
# junos: juniper_junos
# ios: cisco_ios
#
#etc.
netmiko_device_type_map.update(__salt__['config.get']('netmiko_device_type_map', {}))
kwargs['device_type'] = netmiko_device_type_map[__grains__['os']]
return kwargs | [
"def",
"netmiko_args",
"(",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"HAS_NETMIKO",
":",
"raise",
"CommandExecutionError",
"(",
"'Please install netmiko to be able to use this feature.'",
")",
"kwargs",
"=",
"{",
"}",
"napalm_opts",
"=",
"salt",
".",
"utils",
".... | .. versionadded:: 2019.2.0
Return the key-value arguments used for the authentication arguments for
the netmiko module.
When running in a non-native NAPALM driver (e.g., ``panos``, `f5``, ``mos`` -
either from https://github.com/napalm-automation-community or defined in
user's own environment, one can specify the Netmiko device type (the
``device_type`` argument) via the ``netmiko_device_type_map`` configuration
option / Pillar key, e.g.,
.. code-block:: yaml
netmiko_device_type_map:
f5: f5_ltm
dellos10: dell_os10
The configuration above defines the mapping between the NAPALM ``os`` Grain
and the Netmiko ``device_type``, e.g., when the NAPALM Grain is ``f5``, it
would use the ``f5_ltm`` SSH Netmiko driver to execute commands over SSH on
the remote network device.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_args | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L421-L488 | train |
saltstack/salt | salt/modules/napalm_mod.py | netmiko_fun | def netmiko_fun(fun, *args, **kwargs):
'''
.. versionadded:: 2019.2.0
Call an arbitrary function from the :mod:`Netmiko<salt.modules.netmiko_mod>`
module, passing the authentication details from the existing NAPALM
connection.
fun
The name of the function from the :mod:`Netmiko<salt.modules.netmiko_mod>`
to invoke.
args
List of arguments to send to the execution function specified in
``fun``.
kwargs
Key-value arguments to send to the execution function specified in
``fun``.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_fun send_command 'show version'
'''
if 'netmiko.' not in fun:
fun = 'netmiko.{fun}'.format(fun=fun)
netmiko_kwargs = netmiko_args()
kwargs.update(netmiko_kwargs)
return __salt__[fun](*args, **kwargs) | python | def netmiko_fun(fun, *args, **kwargs):
'''
.. versionadded:: 2019.2.0
Call an arbitrary function from the :mod:`Netmiko<salt.modules.netmiko_mod>`
module, passing the authentication details from the existing NAPALM
connection.
fun
The name of the function from the :mod:`Netmiko<salt.modules.netmiko_mod>`
to invoke.
args
List of arguments to send to the execution function specified in
``fun``.
kwargs
Key-value arguments to send to the execution function specified in
``fun``.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_fun send_command 'show version'
'''
if 'netmiko.' not in fun:
fun = 'netmiko.{fun}'.format(fun=fun)
netmiko_kwargs = netmiko_args()
kwargs.update(netmiko_kwargs)
return __salt__[fun](*args, **kwargs) | [
"def",
"netmiko_fun",
"(",
"fun",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'netmiko.'",
"not",
"in",
"fun",
":",
"fun",
"=",
"'netmiko.{fun}'",
".",
"format",
"(",
"fun",
"=",
"fun",
")",
"netmiko_kwargs",
"=",
"netmiko_args",
"(",
... | .. versionadded:: 2019.2.0
Call an arbitrary function from the :mod:`Netmiko<salt.modules.netmiko_mod>`
module, passing the authentication details from the existing NAPALM
connection.
fun
The name of the function from the :mod:`Netmiko<salt.modules.netmiko_mod>`
to invoke.
args
List of arguments to send to the execution function specified in
``fun``.
kwargs
Key-value arguments to send to the execution function specified in
``fun``.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_fun send_command 'show version' | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L492-L522 | train |
saltstack/salt | salt/modules/napalm_mod.py | netmiko_call | def netmiko_call(method, *args, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute an arbitrary Netmiko method, passing the authentication details from
the existing NAPALM connection.
method
The name of the Netmiko method to execute.
args
List of arguments to send to the Netmiko method specified in ``method``.
kwargs
Key-value arguments to send to the execution function specified in
``method``.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_call send_command 'show version'
'''
netmiko_kwargs = netmiko_args()
kwargs.update(netmiko_kwargs)
return __salt__['netmiko.call'](method, *args, **kwargs) | python | def netmiko_call(method, *args, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute an arbitrary Netmiko method, passing the authentication details from
the existing NAPALM connection.
method
The name of the Netmiko method to execute.
args
List of arguments to send to the Netmiko method specified in ``method``.
kwargs
Key-value arguments to send to the execution function specified in
``method``.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_call send_command 'show version'
'''
netmiko_kwargs = netmiko_args()
kwargs.update(netmiko_kwargs)
return __salt__['netmiko.call'](method, *args, **kwargs) | [
"def",
"netmiko_call",
"(",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"netmiko_kwargs",
"=",
"netmiko_args",
"(",
")",
"kwargs",
".",
"update",
"(",
"netmiko_kwargs",
")",
"return",
"__salt__",
"[",
"'netmiko.call'",
"]",
"(",
"method"... | .. versionadded:: 2019.2.0
Execute an arbitrary Netmiko method, passing the authentication details from
the existing NAPALM connection.
method
The name of the Netmiko method to execute.
args
List of arguments to send to the Netmiko method specified in ``method``.
kwargs
Key-value arguments to send to the execution function specified in
``method``.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_call send_command 'show version' | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L526-L551 | train |
saltstack/salt | salt/modules/napalm_mod.py | netmiko_multi_call | def netmiko_multi_call(*methods, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute a list of arbitrary Netmiko methods, passing the authentication
details from the existing NAPALM connection.
methods
List of dictionaries with the following keys:
- ``name``: the name of the Netmiko function to invoke.
- ``args``: list of arguments to send to the ``name`` method.
- ``kwargs``: key-value arguments to send to the ``name`` method.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_multi_call "{'name': 'send_command', 'args': ['show version']}" "{'name': 'send_command', 'args': ['show interfaces']}"
'''
netmiko_kwargs = netmiko_args()
kwargs.update(netmiko_kwargs)
return __salt__['netmiko.multi_call'](*methods, **kwargs) | python | def netmiko_multi_call(*methods, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute a list of arbitrary Netmiko methods, passing the authentication
details from the existing NAPALM connection.
methods
List of dictionaries with the following keys:
- ``name``: the name of the Netmiko function to invoke.
- ``args``: list of arguments to send to the ``name`` method.
- ``kwargs``: key-value arguments to send to the ``name`` method.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_multi_call "{'name': 'send_command', 'args': ['show version']}" "{'name': 'send_command', 'args': ['show interfaces']}"
'''
netmiko_kwargs = netmiko_args()
kwargs.update(netmiko_kwargs)
return __salt__['netmiko.multi_call'](*methods, **kwargs) | [
"def",
"netmiko_multi_call",
"(",
"*",
"methods",
",",
"*",
"*",
"kwargs",
")",
":",
"netmiko_kwargs",
"=",
"netmiko_args",
"(",
")",
"kwargs",
".",
"update",
"(",
"netmiko_kwargs",
")",
"return",
"__salt__",
"[",
"'netmiko.multi_call'",
"]",
"(",
"*",
"meth... | .. versionadded:: 2019.2.0
Execute a list of arbitrary Netmiko methods, passing the authentication
details from the existing NAPALM connection.
methods
List of dictionaries with the following keys:
- ``name``: the name of the Netmiko function to invoke.
- ``args``: list of arguments to send to the ``name`` method.
- ``kwargs``: key-value arguments to send to the ``name`` method.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_multi_call "{'name': 'send_command', 'args': ['show version']}" "{'name': 'send_command', 'args': ['show interfaces']}" | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L555-L578 | train |
saltstack/salt | salt/modules/napalm_mod.py | netmiko_commands | def netmiko_commands(*commands, **kwargs):
'''
.. versionadded:: 2019.2.0
Invoke one or more commands to be executed on the remote device, via Netmiko.
Returns a list of strings, with the output from each command.
commands
A list of commands to be executed.
expect_string
Regular expression pattern to use for determining end of output.
If left blank will default to being based on router prompt.
delay_factor: ``1``
Multiplying factor used to adjust delays (default: ``1``).
max_loops: ``500``
Controls wait time in conjunction with delay_factor. Will default to be
based upon self.timeout.
auto_find_prompt: ``True``
Whether it should try to auto-detect the prompt (default: ``True``).
strip_prompt: ``True``
Remove the trailing router prompt from the output (default: ``True``).
strip_command: ``True``
Remove the echo of the command from the output (default: ``True``).
normalize: ``True``
Ensure the proper enter is sent at end of command (default: ``True``).
use_textfsm: ``False``
Process command output through TextFSM template (default: ``False``).
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_commands 'show version' 'show interfaces'
'''
conn = netmiko_conn(**kwargs)
ret = []
for cmd in commands:
ret.append(conn.send_command(cmd))
return ret | python | def netmiko_commands(*commands, **kwargs):
'''
.. versionadded:: 2019.2.0
Invoke one or more commands to be executed on the remote device, via Netmiko.
Returns a list of strings, with the output from each command.
commands
A list of commands to be executed.
expect_string
Regular expression pattern to use for determining end of output.
If left blank will default to being based on router prompt.
delay_factor: ``1``
Multiplying factor used to adjust delays (default: ``1``).
max_loops: ``500``
Controls wait time in conjunction with delay_factor. Will default to be
based upon self.timeout.
auto_find_prompt: ``True``
Whether it should try to auto-detect the prompt (default: ``True``).
strip_prompt: ``True``
Remove the trailing router prompt from the output (default: ``True``).
strip_command: ``True``
Remove the echo of the command from the output (default: ``True``).
normalize: ``True``
Ensure the proper enter is sent at end of command (default: ``True``).
use_textfsm: ``False``
Process command output through TextFSM template (default: ``False``).
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_commands 'show version' 'show interfaces'
'''
conn = netmiko_conn(**kwargs)
ret = []
for cmd in commands:
ret.append(conn.send_command(cmd))
return ret | [
"def",
"netmiko_commands",
"(",
"*",
"commands",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"netmiko_conn",
"(",
"*",
"*",
"kwargs",
")",
"ret",
"=",
"[",
"]",
"for",
"cmd",
"in",
"commands",
":",
"ret",
".",
"append",
"(",
"conn",
".",
"send_... | .. versionadded:: 2019.2.0
Invoke one or more commands to be executed on the remote device, via Netmiko.
Returns a list of strings, with the output from each command.
commands
A list of commands to be executed.
expect_string
Regular expression pattern to use for determining end of output.
If left blank will default to being based on router prompt.
delay_factor: ``1``
Multiplying factor used to adjust delays (default: ``1``).
max_loops: ``500``
Controls wait time in conjunction with delay_factor. Will default to be
based upon self.timeout.
auto_find_prompt: ``True``
Whether it should try to auto-detect the prompt (default: ``True``).
strip_prompt: ``True``
Remove the trailing router prompt from the output (default: ``True``).
strip_command: ``True``
Remove the echo of the command from the output (default: ``True``).
normalize: ``True``
Ensure the proper enter is sent at end of command (default: ``True``).
use_textfsm: ``False``
Process command output through TextFSM template (default: ``False``).
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_commands 'show version' 'show interfaces' | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L582-L628 | train |
saltstack/salt | salt/modules/napalm_mod.py | netmiko_config | def netmiko_config(*config_commands, **kwargs):
'''
.. versionadded:: 2019.2.0
Load a list of configuration commands on the remote device, via Netmiko.
.. warning::
Please remember that ``netmiko`` does not have any rollback safeguards
and any configuration change will be directly loaded into the running
config if the platform doesn't have the concept of ``candidate`` config.
On Junos, or other platforms that have this capability, the changes will
not be loaded into the running config, and the user must set the
``commit`` argument to ``True`` to transfer the changes from the
candidate into the running config before exiting.
config_commands
A list of configuration commands to be loaded on the remote device.
config_file
Read the configuration commands from a file. The file can equally be a
template that can be rendered using the engine of choice (see
``template_engine``).
This can be specified using the absolute path to the file, or using one
of the following URL schemes:
- ``salt://``, to fetch the file from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
exit_config_mode: ``True``
Determines whether or not to exit config mode after complete.
delay_factor: ``1``
Factor to adjust delays.
max_loops: ``150``
Controls wait time in conjunction with delay_factor (default: ``150``).
strip_prompt: ``False``
Determines whether or not to strip the prompt (default: ``False``).
strip_command: ``False``
Determines whether or not to strip the command (default: ``False``).
config_mode_command
The command to enter into config mode.
commit: ``False``
Commit the configuration changes before exiting the config mode. This
option is by default disabled, as many platforms don't have this
capability natively.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_config 'set system ntp peer 1.2.3.4' commit=True
salt '*' napalm.netmiko_config https://bit.ly/2sgljCB
'''
netmiko_kwargs = netmiko_args()
kwargs.update(netmiko_kwargs)
return __salt__['netmiko.send_config'](config_commands=config_commands,
**kwargs) | python | def netmiko_config(*config_commands, **kwargs):
'''
.. versionadded:: 2019.2.0
Load a list of configuration commands on the remote device, via Netmiko.
.. warning::
Please remember that ``netmiko`` does not have any rollback safeguards
and any configuration change will be directly loaded into the running
config if the platform doesn't have the concept of ``candidate`` config.
On Junos, or other platforms that have this capability, the changes will
not be loaded into the running config, and the user must set the
``commit`` argument to ``True`` to transfer the changes from the
candidate into the running config before exiting.
config_commands
A list of configuration commands to be loaded on the remote device.
config_file
Read the configuration commands from a file. The file can equally be a
template that can be rendered using the engine of choice (see
``template_engine``).
This can be specified using the absolute path to the file, or using one
of the following URL schemes:
- ``salt://``, to fetch the file from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
exit_config_mode: ``True``
Determines whether or not to exit config mode after complete.
delay_factor: ``1``
Factor to adjust delays.
max_loops: ``150``
Controls wait time in conjunction with delay_factor (default: ``150``).
strip_prompt: ``False``
Determines whether or not to strip the prompt (default: ``False``).
strip_command: ``False``
Determines whether or not to strip the command (default: ``False``).
config_mode_command
The command to enter into config mode.
commit: ``False``
Commit the configuration changes before exiting the config mode. This
option is by default disabled, as many platforms don't have this
capability natively.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_config 'set system ntp peer 1.2.3.4' commit=True
salt '*' napalm.netmiko_config https://bit.ly/2sgljCB
'''
netmiko_kwargs = netmiko_args()
kwargs.update(netmiko_kwargs)
return __salt__['netmiko.send_config'](config_commands=config_commands,
**kwargs) | [
"def",
"netmiko_config",
"(",
"*",
"config_commands",
",",
"*",
"*",
"kwargs",
")",
":",
"netmiko_kwargs",
"=",
"netmiko_args",
"(",
")",
"kwargs",
".",
"update",
"(",
"netmiko_kwargs",
")",
"return",
"__salt__",
"[",
"'netmiko.send_config'",
"]",
"(",
"config... | .. versionadded:: 2019.2.0
Load a list of configuration commands on the remote device, via Netmiko.
.. warning::
Please remember that ``netmiko`` does not have any rollback safeguards
and any configuration change will be directly loaded into the running
config if the platform doesn't have the concept of ``candidate`` config.
On Junos, or other platforms that have this capability, the changes will
not be loaded into the running config, and the user must set the
``commit`` argument to ``True`` to transfer the changes from the
candidate into the running config before exiting.
config_commands
A list of configuration commands to be loaded on the remote device.
config_file
Read the configuration commands from a file. The file can equally be a
template that can be rendered using the engine of choice (see
``template_engine``).
This can be specified using the absolute path to the file, or using one
of the following URL schemes:
- ``salt://``, to fetch the file from the Salt fileserver.
- ``http://`` or ``https://``
- ``ftp://``
- ``s3://``
- ``swift://``
exit_config_mode: ``True``
Determines whether or not to exit config mode after complete.
delay_factor: ``1``
Factor to adjust delays.
max_loops: ``150``
Controls wait time in conjunction with delay_factor (default: ``150``).
strip_prompt: ``False``
Determines whether or not to strip the prompt (default: ``False``).
strip_command: ``False``
Determines whether or not to strip the command (default: ``False``).
config_mode_command
The command to enter into config mode.
commit: ``False``
Commit the configuration changes before exiting the config mode. This
option is by default disabled, as many platforms don't have this
capability natively.
CLI Example:
.. code-block:: bash
salt '*' napalm.netmiko_config 'set system ntp peer 1.2.3.4' commit=True
salt '*' napalm.netmiko_config https://bit.ly/2sgljCB | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L632-L699 | train |
saltstack/salt | salt/modules/napalm_mod.py | junos_rpc | def junos_rpc(cmd=None, dest=None, format=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute an RPC request on the remote Junos device.
cmd
The RPC request to the executed. To determine the RPC request, you can
check the from the command line of the device, by executing the usual
command followed by ``| display xml rpc``, e.g.,
``show lldp neighbors | display xml rpc``.
dest
Destination file where the RPC output is stored. Note that the file will
be stored on the Proxy Minion. To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
format: ``xml``
The format in which the RPC reply is received from the device.
dev_timeout: ``30``
The NETCONF RPC timeout.
filter
Used with the ``get-config`` RPC request to filter out the config tree.
terse: ``False``
Whether to return terse output.
.. note::
Some RPC requests may not support this argument.
interface_name
Name of the interface to query.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_rpc get-lldp-neighbors-information
salt '*' napalm.junos_rcp get-config <configuration><system><ntp/></system></configuration>
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
if not format:
format = 'xml'
rpc_ret = __salt__['junos.rpc'](cmd=cmd,
dest=dest,
format=format,
**kwargs)
rpc_ret['comment'] = rpc_ret.pop('message', '')
rpc_ret['result'] = rpc_ret.pop('out', False)
rpc_ret['out'] = rpc_ret.pop('rpc_reply', None)
# The comment field is "message" in the Junos module
return rpc_ret | python | def junos_rpc(cmd=None, dest=None, format=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute an RPC request on the remote Junos device.
cmd
The RPC request to the executed. To determine the RPC request, you can
check the from the command line of the device, by executing the usual
command followed by ``| display xml rpc``, e.g.,
``show lldp neighbors | display xml rpc``.
dest
Destination file where the RPC output is stored. Note that the file will
be stored on the Proxy Minion. To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
format: ``xml``
The format in which the RPC reply is received from the device.
dev_timeout: ``30``
The NETCONF RPC timeout.
filter
Used with the ``get-config`` RPC request to filter out the config tree.
terse: ``False``
Whether to return terse output.
.. note::
Some RPC requests may not support this argument.
interface_name
Name of the interface to query.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_rpc get-lldp-neighbors-information
salt '*' napalm.junos_rcp get-config <configuration><system><ntp/></system></configuration>
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
if not format:
format = 'xml'
rpc_ret = __salt__['junos.rpc'](cmd=cmd,
dest=dest,
format=format,
**kwargs)
rpc_ret['comment'] = rpc_ret.pop('message', '')
rpc_ret['result'] = rpc_ret.pop('out', False)
rpc_ret['out'] = rpc_ret.pop('rpc_reply', None)
# The comment field is "message" in the Junos module
return rpc_ret | [
"def",
"junos_rpc",
"(",
"cmd",
"=",
"None",
",",
"dest",
"=",
"None",
",",
"format",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"prep",
"=",
"_junos_prep_fun",
"(",
"napalm_device",
")",
"# pylint: disable=undefined-variable",
"if",
"not",
"prep",
"[... | .. versionadded:: 2019.2.0
Execute an RPC request on the remote Junos device.
cmd
The RPC request to the executed. To determine the RPC request, you can
check the from the command line of the device, by executing the usual
command followed by ``| display xml rpc``, e.g.,
``show lldp neighbors | display xml rpc``.
dest
Destination file where the RPC output is stored. Note that the file will
be stored on the Proxy Minion. To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
format: ``xml``
The format in which the RPC reply is received from the device.
dev_timeout: ``30``
The NETCONF RPC timeout.
filter
Used with the ``get-config`` RPC request to filter out the config tree.
terse: ``False``
Whether to return terse output.
.. note::
Some RPC requests may not support this argument.
interface_name
Name of the interface to query.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_rpc get-lldp-neighbors-information
salt '*' napalm.junos_rcp get-config <configuration><system><ntp/></system></configuration> | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L729-L785 | train |
saltstack/salt | salt/modules/napalm_mod.py | junos_install_os | def junos_install_os(path=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Installs the given image on the device.
path
The image file source. This argument supports the following URIs:
- Absolute path on the Minion.
- ``salt://`` to fetch from the Salt fileserver.
- ``http://`` and ``https://``
- ``ftp://``
- ``swift:/``
- ``s3://``
dev_timeout: ``30``
The NETCONF RPC timeout (in seconds)
reboot: ``False``
Whether to reboot the device after the installation is complete.
no_copy: ``False``
If ``True`` the software package will not be copied to the remote
device.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_install_os salt://images/junos_16_1.tgz reboot=True
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
return __salt__['junos.install_os'](path=path, **kwargs) | python | def junos_install_os(path=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Installs the given image on the device.
path
The image file source. This argument supports the following URIs:
- Absolute path on the Minion.
- ``salt://`` to fetch from the Salt fileserver.
- ``http://`` and ``https://``
- ``ftp://``
- ``swift:/``
- ``s3://``
dev_timeout: ``30``
The NETCONF RPC timeout (in seconds)
reboot: ``False``
Whether to reboot the device after the installation is complete.
no_copy: ``False``
If ``True`` the software package will not be copied to the remote
device.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_install_os salt://images/junos_16_1.tgz reboot=True
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
return __salt__['junos.install_os'](path=path, **kwargs) | [
"def",
"junos_install_os",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"prep",
"=",
"_junos_prep_fun",
"(",
"napalm_device",
")",
"# pylint: disable=undefined-variable",
"if",
"not",
"prep",
"[",
"'result'",
"]",
":",
"return",
"prep",
"return... | .. versionadded:: 2019.2.0
Installs the given image on the device.
path
The image file source. This argument supports the following URIs:
- Absolute path on the Minion.
- ``salt://`` to fetch from the Salt fileserver.
- ``http://`` and ``https://``
- ``ftp://``
- ``swift:/``
- ``s3://``
dev_timeout: ``30``
The NETCONF RPC timeout (in seconds)
reboot: ``False``
Whether to reboot the device after the installation is complete.
no_copy: ``False``
If ``True`` the software package will not be copied to the remote
device.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_install_os salt://images/junos_16_1.tgz reboot=True | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L838-L873 | train |
saltstack/salt | salt/modules/napalm_mod.py | junos_facts | def junos_facts(**kwargs):
'''
.. versionadded:: 2019.2.0
The complete list of Junos facts collected by ``junos-eznc``.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_facts
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
facts = dict(napalm_device['DRIVER'].device.facts) # pylint: disable=undefined-variable
if 'version_info' in facts:
facts['version_info'] = \
dict(facts['version_info'])
# For backward compatibility. 'junos_info' is present
# only of in newer versions of facts.
if 'junos_info' in facts:
for re in facts['junos_info']:
facts['junos_info'][re]['object'] = \
dict(facts['junos_info'][re]['object'])
return facts | python | def junos_facts(**kwargs):
'''
.. versionadded:: 2019.2.0
The complete list of Junos facts collected by ``junos-eznc``.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_facts
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
facts = dict(napalm_device['DRIVER'].device.facts) # pylint: disable=undefined-variable
if 'version_info' in facts:
facts['version_info'] = \
dict(facts['version_info'])
# For backward compatibility. 'junos_info' is present
# only of in newer versions of facts.
if 'junos_info' in facts:
for re in facts['junos_info']:
facts['junos_info'][re]['object'] = \
dict(facts['junos_info'][re]['object'])
return facts | [
"def",
"junos_facts",
"(",
"*",
"*",
"kwargs",
")",
":",
"prep",
"=",
"_junos_prep_fun",
"(",
"napalm_device",
")",
"# pylint: disable=undefined-variable",
"if",
"not",
"prep",
"[",
"'result'",
"]",
":",
"return",
"prep",
"facts",
"=",
"dict",
"(",
"napalm_dev... | .. versionadded:: 2019.2.0
The complete list of Junos facts collected by ``junos-eznc``.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_facts | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L877-L902 | train |
saltstack/salt | salt/modules/napalm_mod.py | junos_cli | def junos_cli(command, format=None, dev_timeout=None, dest=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute a CLI command and return the output in the specified format.
command
The command to execute on the Junos CLI.
format: ``text``
Format in which to get the CLI output (either ``text`` or ``xml``).
dev_timeout: ``30``
The NETCONF RPC timeout (in seconds).
dest
Destination file where the RPC output is stored. Note that the file will
be stored on the Proxy Minion. To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>`.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_cli 'show lldp neighbors'
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
return __salt__['junos.cli'](command,
format=format,
dev_timeout=dev_timeout,
dest=dest,
**kwargs) | python | def junos_cli(command, format=None, dev_timeout=None, dest=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute a CLI command and return the output in the specified format.
command
The command to execute on the Junos CLI.
format: ``text``
Format in which to get the CLI output (either ``text`` or ``xml``).
dev_timeout: ``30``
The NETCONF RPC timeout (in seconds).
dest
Destination file where the RPC output is stored. Note that the file will
be stored on the Proxy Minion. To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>`.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_cli 'show lldp neighbors'
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
return __salt__['junos.cli'](command,
format=format,
dev_timeout=dev_timeout,
dest=dest,
**kwargs) | [
"def",
"junos_cli",
"(",
"command",
",",
"format",
"=",
"None",
",",
"dev_timeout",
"=",
"None",
",",
"dest",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"prep",
"=",
"_junos_prep_fun",
"(",
"napalm_device",
")",
"# pylint: disable=undefined-variable",
"... | .. versionadded:: 2019.2.0
Execute a CLI command and return the output in the specified format.
command
The command to execute on the Junos CLI.
format: ``text``
Format in which to get the CLI output (either ``text`` or ``xml``).
dev_timeout: ``30``
The NETCONF RPC timeout (in seconds).
dest
Destination file where the RPC output is stored. Note that the file will
be stored on the Proxy Minion. To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>`.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_cli 'show lldp neighbors' | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L906-L939 | train |
saltstack/salt | salt/modules/napalm_mod.py | junos_copy_file | def junos_copy_file(src, dst, **kwargs):
'''
.. versionadded:: 2019.2.0
Copies the file on the remote Junos device.
src
The source file path. This argument accepts the usual Salt URIs (e.g.,
``salt://``, ``http://``, ``https://``, ``s3://``, ``ftp://``, etc.).
dst
The destination path on the device where to copy the file.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_copy_file https://example.com/junos.cfg /var/tmp/myjunos.cfg
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
cached_src = __salt__['cp.cache_file'](src)
return __salt__['junos.file_copy'](cached_src, dst) | python | def junos_copy_file(src, dst, **kwargs):
'''
.. versionadded:: 2019.2.0
Copies the file on the remote Junos device.
src
The source file path. This argument accepts the usual Salt URIs (e.g.,
``salt://``, ``http://``, ``https://``, ``s3://``, ``ftp://``, etc.).
dst
The destination path on the device where to copy the file.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_copy_file https://example.com/junos.cfg /var/tmp/myjunos.cfg
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
cached_src = __salt__['cp.cache_file'](src)
return __salt__['junos.file_copy'](cached_src, dst) | [
"def",
"junos_copy_file",
"(",
"src",
",",
"dst",
",",
"*",
"*",
"kwargs",
")",
":",
"prep",
"=",
"_junos_prep_fun",
"(",
"napalm_device",
")",
"# pylint: disable=undefined-variable",
"if",
"not",
"prep",
"[",
"'result'",
"]",
":",
"return",
"prep",
"cached_sr... | .. versionadded:: 2019.2.0
Copies the file on the remote Junos device.
src
The source file path. This argument accepts the usual Salt URIs (e.g.,
``salt://``, ``http://``, ``https://``, ``s3://``, ``ftp://``, etc.).
dst
The destination path on the device where to copy the file.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_copy_file https://example.com/junos.cfg /var/tmp/myjunos.cfg | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L943-L966 | train |
saltstack/salt | salt/modules/napalm_mod.py | junos_call | def junos_call(fun, *args, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute an arbitrary function from the
:mod:`junos execution module <salt.module.junos>`. To check what ``args``
and ``kwargs`` you must send to the function, please consult the appropriate
documentation.
fun
The name of the function. E.g., ``set_hostname``.
args
List of arguments to send to the ``junos`` function invoked.
kwargs
Dictionary of key-value arguments to send to the ``juno`` function
invoked.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_fun cli 'show system commit'
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
if 'junos.' not in fun:
mod_fun = 'junos.{}'.format(fun)
else:
mod_fun = fun
if mod_fun not in __salt__:
return {
'out': None,
'result': False,
'comment': '{} is not a valid function'.format(fun)
}
return __salt__[mod_fun](*args, **kwargs) | python | def junos_call(fun, *args, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute an arbitrary function from the
:mod:`junos execution module <salt.module.junos>`. To check what ``args``
and ``kwargs`` you must send to the function, please consult the appropriate
documentation.
fun
The name of the function. E.g., ``set_hostname``.
args
List of arguments to send to the ``junos`` function invoked.
kwargs
Dictionary of key-value arguments to send to the ``juno`` function
invoked.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_fun cli 'show system commit'
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['result']:
return prep
if 'junos.' not in fun:
mod_fun = 'junos.{}'.format(fun)
else:
mod_fun = fun
if mod_fun not in __salt__:
return {
'out': None,
'result': False,
'comment': '{} is not a valid function'.format(fun)
}
return __salt__[mod_fun](*args, **kwargs) | [
"def",
"junos_call",
"(",
"fun",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"prep",
"=",
"_junos_prep_fun",
"(",
"napalm_device",
")",
"# pylint: disable=undefined-variable",
"if",
"not",
"prep",
"[",
"'result'",
"]",
":",
"return",
"prep",
"if",
... | .. versionadded:: 2019.2.0
Execute an arbitrary function from the
:mod:`junos execution module <salt.module.junos>`. To check what ``args``
and ``kwargs`` you must send to the function, please consult the appropriate
documentation.
fun
The name of the function. E.g., ``set_hostname``.
args
List of arguments to send to the ``junos`` function invoked.
kwargs
Dictionary of key-value arguments to send to the ``juno`` function
invoked.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_fun cli 'show system commit' | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L970-L1008 | train |
saltstack/salt | salt/modules/napalm_mod.py | pyeapi_nxos_api_args | def pyeapi_nxos_api_args(**prev_kwargs):
'''
.. versionadded:: 2019.2.0
Return the key-value arguments used for the authentication arguments for the
:mod:`pyeapi execution module <salt.module.arista_pyeapi>`.
CLI Example:
.. code-block:: bash
salt '*' napalm.pyeapi_nxos_api_args
'''
kwargs = {}
napalm_opts = salt.utils.napalm.get_device_opts(__opts__, salt_obj=__salt__)
optional_args = napalm_opts['OPTIONAL_ARGS']
kwargs['host'] = napalm_opts['HOSTNAME']
kwargs['username'] = napalm_opts['USERNAME']
kwargs['password'] = napalm_opts['PASSWORD']
kwargs['timeout'] = napalm_opts['TIMEOUT']
kwargs['transport'] = optional_args.get('transport')
kwargs['port'] = optional_args.get('port')
kwargs['verify'] = optional_args.get('verify')
prev_kwargs.update(kwargs)
return prev_kwargs | python | def pyeapi_nxos_api_args(**prev_kwargs):
'''
.. versionadded:: 2019.2.0
Return the key-value arguments used for the authentication arguments for the
:mod:`pyeapi execution module <salt.module.arista_pyeapi>`.
CLI Example:
.. code-block:: bash
salt '*' napalm.pyeapi_nxos_api_args
'''
kwargs = {}
napalm_opts = salt.utils.napalm.get_device_opts(__opts__, salt_obj=__salt__)
optional_args = napalm_opts['OPTIONAL_ARGS']
kwargs['host'] = napalm_opts['HOSTNAME']
kwargs['username'] = napalm_opts['USERNAME']
kwargs['password'] = napalm_opts['PASSWORD']
kwargs['timeout'] = napalm_opts['TIMEOUT']
kwargs['transport'] = optional_args.get('transport')
kwargs['port'] = optional_args.get('port')
kwargs['verify'] = optional_args.get('verify')
prev_kwargs.update(kwargs)
return prev_kwargs | [
"def",
"pyeapi_nxos_api_args",
"(",
"*",
"*",
"prev_kwargs",
")",
":",
"kwargs",
"=",
"{",
"}",
"napalm_opts",
"=",
"salt",
".",
"utils",
".",
"napalm",
".",
"get_device_opts",
"(",
"__opts__",
",",
"salt_obj",
"=",
"__salt__",
")",
"optional_args",
"=",
"... | .. versionadded:: 2019.2.0
Return the key-value arguments used for the authentication arguments for the
:mod:`pyeapi execution module <salt.module.arista_pyeapi>`.
CLI Example:
.. code-block:: bash
salt '*' napalm.pyeapi_nxos_api_args | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1011-L1035 | train |
saltstack/salt | salt/modules/napalm_mod.py | pyeapi_call | def pyeapi_call(method, *args, **kwargs):
'''
.. versionadded:: 2019.2.0
Invoke an arbitrary method from the ``pyeapi`` library.
This function forwards the existing connection details to the
:mod:`pyeapi.run_commands <salt.module.arista_pyeapi.run_commands>`
execution function.
method
The name of the ``pyeapi`` method to invoke.
kwargs
Key-value arguments to send to the ``pyeapi`` method.
CLI Example:
.. code-block:: bash
salt '*' napalm.pyeapi_call run_commands 'show version' encoding=text
salt '*' napalm.pyeapi_call get_config as_string=True
'''
pyeapi_kwargs = pyeapi_nxos_api_args(**kwargs)
return __salt__['pyeapi.call'](method, *args, **pyeapi_kwargs) | python | def pyeapi_call(method, *args, **kwargs):
'''
.. versionadded:: 2019.2.0
Invoke an arbitrary method from the ``pyeapi`` library.
This function forwards the existing connection details to the
:mod:`pyeapi.run_commands <salt.module.arista_pyeapi.run_commands>`
execution function.
method
The name of the ``pyeapi`` method to invoke.
kwargs
Key-value arguments to send to the ``pyeapi`` method.
CLI Example:
.. code-block:: bash
salt '*' napalm.pyeapi_call run_commands 'show version' encoding=text
salt '*' napalm.pyeapi_call get_config as_string=True
'''
pyeapi_kwargs = pyeapi_nxos_api_args(**kwargs)
return __salt__['pyeapi.call'](method, *args, **pyeapi_kwargs) | [
"def",
"pyeapi_call",
"(",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pyeapi_kwargs",
"=",
"pyeapi_nxos_api_args",
"(",
"*",
"*",
"kwargs",
")",
"return",
"__salt__",
"[",
"'pyeapi.call'",
"]",
"(",
"method",
",",
"*",
"args",
",",
... | .. versionadded:: 2019.2.0
Invoke an arbitrary method from the ``pyeapi`` library.
This function forwards the existing connection details to the
:mod:`pyeapi.run_commands <salt.module.arista_pyeapi.run_commands>`
execution function.
method
The name of the ``pyeapi`` method to invoke.
kwargs
Key-value arguments to send to the ``pyeapi`` method.
CLI Example:
.. code-block:: bash
salt '*' napalm.pyeapi_call run_commands 'show version' encoding=text
salt '*' napalm.pyeapi_call get_config as_string=True | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1065-L1088 | train |
saltstack/salt | salt/modules/napalm_mod.py | pyeapi_config | def pyeapi_config(commands=None,
config_file=None,
template_engine='jinja',
context=None,
defaults=None,
saltenv='base',
**kwargs):
'''
.. versionadded:: 2019.2.0
Configures the Arista switch with the specified commands, via the ``pyeapi``
library. This function forwards the existing connection details to the
:mod:`pyeapi.run_commands <salt.module.arista_pyeapi.run_commands>`
execution function.
commands
The list of configuration commands to load on the Arista switch.
.. note::
This argument is ignored when ``config_file`` is specified.
config_file
The source file with the configuration commands to be sent to the device.
The file can also be a template that can be rendered using the template
engine of choice. This can be specified using the absolute path to the
file, or using one of the following URL schemes:
- ``salt://``
- ``https://``
- ``ftp:/``
- ``s3:/``
- ``swift://``
template_engine: ``jinja``
The template engine to use when rendering the source file. Default:
``jinja``. To simply fetch the file without attempting to render, set
this argument to ``None``.
context: ``None``
Variables to add to the template context.
defaults: ``None``
Default values of the ``context`` dict.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. Ignored if
``config_file`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.pyeapi_config 'ntp server 1.2.3.4'
'''
pyeapi_kwargs = pyeapi_nxos_api_args(**kwargs)
return __salt__['pyeapi.config'](commands=commands,
config_file=config_file,
template_engine=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
**pyeapi_kwargs) | python | def pyeapi_config(commands=None,
config_file=None,
template_engine='jinja',
context=None,
defaults=None,
saltenv='base',
**kwargs):
'''
.. versionadded:: 2019.2.0
Configures the Arista switch with the specified commands, via the ``pyeapi``
library. This function forwards the existing connection details to the
:mod:`pyeapi.run_commands <salt.module.arista_pyeapi.run_commands>`
execution function.
commands
The list of configuration commands to load on the Arista switch.
.. note::
This argument is ignored when ``config_file`` is specified.
config_file
The source file with the configuration commands to be sent to the device.
The file can also be a template that can be rendered using the template
engine of choice. This can be specified using the absolute path to the
file, or using one of the following URL schemes:
- ``salt://``
- ``https://``
- ``ftp:/``
- ``s3:/``
- ``swift://``
template_engine: ``jinja``
The template engine to use when rendering the source file. Default:
``jinja``. To simply fetch the file without attempting to render, set
this argument to ``None``.
context: ``None``
Variables to add to the template context.
defaults: ``None``
Default values of the ``context`` dict.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. Ignored if
``config_file`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.pyeapi_config 'ntp server 1.2.3.4'
'''
pyeapi_kwargs = pyeapi_nxos_api_args(**kwargs)
return __salt__['pyeapi.config'](commands=commands,
config_file=config_file,
template_engine=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
**pyeapi_kwargs) | [
"def",
"pyeapi_config",
"(",
"commands",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"template_engine",
"=",
"'jinja'",
",",
"context",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
... | .. versionadded:: 2019.2.0
Configures the Arista switch with the specified commands, via the ``pyeapi``
library. This function forwards the existing connection details to the
:mod:`pyeapi.run_commands <salt.module.arista_pyeapi.run_commands>`
execution function.
commands
The list of configuration commands to load on the Arista switch.
.. note::
This argument is ignored when ``config_file`` is specified.
config_file
The source file with the configuration commands to be sent to the device.
The file can also be a template that can be rendered using the template
engine of choice. This can be specified using the absolute path to the
file, or using one of the following URL schemes:
- ``salt://``
- ``https://``
- ``ftp:/``
- ``s3:/``
- ``swift://``
template_engine: ``jinja``
The template engine to use when rendering the source file. Default:
``jinja``. To simply fetch the file without attempting to render, set
this argument to ``None``.
context: ``None``
Variables to add to the template context.
defaults: ``None``
Default values of the ``context`` dict.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. Ignored if
``config_file`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.pyeapi_config 'ntp server 1.2.3.4' | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1117-L1179 | train |
saltstack/salt | salt/modules/napalm_mod.py | nxos_api_rpc | def nxos_api_rpc(commands,
method='cli',
**kwargs):
'''
.. versionadded:: 2019.2.0
Execute an arbitrary RPC request via the Nexus API.
commands
The RPC commands to be executed.
method: ``cli``
The type of the response, i.e., raw text (``cli_ascii``) or structured
document (``cli``). Defaults to ``cli`` (structured data).
CLI Example:
.. code-block:: bash
salt '*' napalm.nxos_api_rpc 'show version'
'''
nxos_api_kwargs = pyeapi_nxos_api_args(**kwargs)
return __salt__['nxos_api.rpc'](commands, method=method, **nxos_api_kwargs) | python | def nxos_api_rpc(commands,
method='cli',
**kwargs):
'''
.. versionadded:: 2019.2.0
Execute an arbitrary RPC request via the Nexus API.
commands
The RPC commands to be executed.
method: ``cli``
The type of the response, i.e., raw text (``cli_ascii``) or structured
document (``cli``). Defaults to ``cli`` (structured data).
CLI Example:
.. code-block:: bash
salt '*' napalm.nxos_api_rpc 'show version'
'''
nxos_api_kwargs = pyeapi_nxos_api_args(**kwargs)
return __salt__['nxos_api.rpc'](commands, method=method, **nxos_api_kwargs) | [
"def",
"nxos_api_rpc",
"(",
"commands",
",",
"method",
"=",
"'cli'",
",",
"*",
"*",
"kwargs",
")",
":",
"nxos_api_kwargs",
"=",
"pyeapi_nxos_api_args",
"(",
"*",
"*",
"kwargs",
")",
"return",
"__salt__",
"[",
"'nxos_api.rpc'",
"]",
"(",
"commands",
",",
"m... | .. versionadded:: 2019.2.0
Execute an arbitrary RPC request via the Nexus API.
commands
The RPC commands to be executed.
method: ``cli``
The type of the response, i.e., raw text (``cli_ascii``) or structured
document (``cli``). Defaults to ``cli`` (structured data).
CLI Example:
.. code-block:: bash
salt '*' napalm.nxos_api_rpc 'show version' | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1183-L1205 | train |
saltstack/salt | salt/modules/napalm_mod.py | nxos_api_config | def nxos_api_config(commands=None,
config_file=None,
template_engine='jinja',
context=None,
defaults=None,
saltenv='base',
**kwargs):
'''
.. versionadded:: 2019.2.0
Configures the Nexus switch with the specified commands, via the NX-API.
commands
The list of configuration commands to load on the Nexus switch.
.. note::
This argument is ignored when ``config_file`` is specified.
config_file
The source file with the configuration commands to be sent to the device.
The file can also be a template that can be rendered using the template
engine of choice. This can be specified using the absolute path to the
file, or using one of the following URL schemes:
- ``salt://``
- ``https://``
- ``ftp:/``
- ``s3:/``
- ``swift://``
template_engine: ``jinja``
The template engine to use when rendering the source file. Default:
``jinja``. To simply fetch the file without attempting to render, set
this argument to ``None``.
context: ``None``
Variables to add to the template context.
defaults: ``None``
Default values of the ``context`` dict.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. Ignored if
``config_file`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.nxos_api_config 'spanning-tree mode mstp'
salt '*' napalm.nxos_api_config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}"
'''
nxos_api_kwargs = pyeapi_nxos_api_args(**kwargs)
return __salt__['nxos_api.config'](commands=commands,
config_file=config_file,
template_engine=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
**nxos_api_kwargs) | python | def nxos_api_config(commands=None,
config_file=None,
template_engine='jinja',
context=None,
defaults=None,
saltenv='base',
**kwargs):
'''
.. versionadded:: 2019.2.0
Configures the Nexus switch with the specified commands, via the NX-API.
commands
The list of configuration commands to load on the Nexus switch.
.. note::
This argument is ignored when ``config_file`` is specified.
config_file
The source file with the configuration commands to be sent to the device.
The file can also be a template that can be rendered using the template
engine of choice. This can be specified using the absolute path to the
file, or using one of the following URL schemes:
- ``salt://``
- ``https://``
- ``ftp:/``
- ``s3:/``
- ``swift://``
template_engine: ``jinja``
The template engine to use when rendering the source file. Default:
``jinja``. To simply fetch the file without attempting to render, set
this argument to ``None``.
context: ``None``
Variables to add to the template context.
defaults: ``None``
Default values of the ``context`` dict.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. Ignored if
``config_file`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.nxos_api_config 'spanning-tree mode mstp'
salt '*' napalm.nxos_api_config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}"
'''
nxos_api_kwargs = pyeapi_nxos_api_args(**kwargs)
return __salt__['nxos_api.config'](commands=commands,
config_file=config_file,
template_engine=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
**nxos_api_kwargs) | [
"def",
"nxos_api_config",
"(",
"commands",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"template_engine",
"=",
"'jinja'",
",",
"context",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
... | .. versionadded:: 2019.2.0
Configures the Nexus switch with the specified commands, via the NX-API.
commands
The list of configuration commands to load on the Nexus switch.
.. note::
This argument is ignored when ``config_file`` is specified.
config_file
The source file with the configuration commands to be sent to the device.
The file can also be a template that can be rendered using the template
engine of choice. This can be specified using the absolute path to the
file, or using one of the following URL schemes:
- ``salt://``
- ``https://``
- ``ftp:/``
- ``s3:/``
- ``swift://``
template_engine: ``jinja``
The template engine to use when rendering the source file. Default:
``jinja``. To simply fetch the file without attempting to render, set
this argument to ``None``.
context: ``None``
Variables to add to the template context.
defaults: ``None``
Default values of the ``context`` dict.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file. Ignored if
``config_file`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.nxos_api_config 'spanning-tree mode mstp'
salt '*' napalm.nxos_api_config config_file=https://bit.ly/2LGLcDy context="{'servers': ['1.2.3.4']}" | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1209-L1269 | train |
saltstack/salt | salt/modules/napalm_mod.py | nxos_api_show | def nxos_api_show(commands, raw_text=True, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute one or more show (non-configuration) commands.
commands
The commands to be executed.
raw_text: ``True``
Whether to return raw text or structured data.
CLI Example:
.. code-block:: bash
salt '*' napalm.nxos_api_show 'show version'
salt '*' napalm.nxos_api_show 'show bgp sessions' 'show processes' raw_text=False
'''
nxos_api_kwargs = pyeapi_nxos_api_args(**kwargs)
return __salt__['nxos_api.show'](commands,
raw_text=raw_text,
**nxos_api_kwargs) | python | def nxos_api_show(commands, raw_text=True, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute one or more show (non-configuration) commands.
commands
The commands to be executed.
raw_text: ``True``
Whether to return raw text or structured data.
CLI Example:
.. code-block:: bash
salt '*' napalm.nxos_api_show 'show version'
salt '*' napalm.nxos_api_show 'show bgp sessions' 'show processes' raw_text=False
'''
nxos_api_kwargs = pyeapi_nxos_api_args(**kwargs)
return __salt__['nxos_api.show'](commands,
raw_text=raw_text,
**nxos_api_kwargs) | [
"def",
"nxos_api_show",
"(",
"commands",
",",
"raw_text",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"nxos_api_kwargs",
"=",
"pyeapi_nxos_api_args",
"(",
"*",
"*",
"kwargs",
")",
"return",
"__salt__",
"[",
"'nxos_api.show'",
"]",
"(",
"commands",
",",
... | .. versionadded:: 2019.2.0
Execute one or more show (non-configuration) commands.
commands
The commands to be executed.
raw_text: ``True``
Whether to return raw text or structured data.
CLI Example:
.. code-block:: bash
salt '*' napalm.nxos_api_show 'show version'
salt '*' napalm.nxos_api_show 'show bgp sessions' 'show processes' raw_text=False | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1273-L1295 | train |
saltstack/salt | salt/modules/napalm_mod.py | rpc | def rpc(command, **kwargs):
'''
.. versionadded:: 2019.2.0
This is a wrapper to execute RPC requests on various network operating
systems supported by NAPALM, invoking the following functions for the NAPALM
native drivers:
- :py:func:`napalm.junos_rpc <salt.modules.napalm_mod.junos_rpc>` for ``junos``
- :py:func:`napalm.pyeapi_run_commands <salt.modules.napalm_mod.pyeapi_run_commands>`
for ``eos``
- :py:func:`napalm.nxos_api_rpc <salt.modules.napalm_mod.nxos_api_rpc>` for
``nxos``
- :py:func:`napalm.netmiko_commands <salt.modules.napalm_mod.netmiko_commands>`
for ``ios``, ``iosxr``, and ``nxos_ssh``
command
The RPC command to execute. This depends on the nature of the operating
system.
kwargs
Key-value arguments to be sent to the underlying Execution function.
The function capabilities are extensible in the user environment via the
``napalm_rpc_map`` configuration option / Pillar, e.g.,
.. code-block:: yaml
napalm_rpc_map:
f5: napalm.netmiko_commands
panos: panos.call
The mapping above reads: when the NAPALM ``os`` Grain is ``f5``, then call
``napalm.netmiko_commands`` for RPC requests.
By default, if the user does not specify any map, non-native NAPALM drivers
will invoke the ``napalm.netmiko_commands`` Execution function.
CLI Example:
.. code-block:: bash
salt '*' napalm.rpc 'show version'
salt '*' napalm.rpc get-interfaces
'''
default_map = {
'junos': 'napalm.junos_rpc',
'eos': 'napalm.pyeapi_run_commands',
'nxos': 'napalm.nxos_api_rpc'
}
napalm_map = __salt__['config.get']('napalm_rpc_map', {})
napalm_map.update(default_map)
fun = napalm_map.get(__grains__['os'], 'napalm.netmiko_commands')
return __salt__[fun](command, **kwargs) | python | def rpc(command, **kwargs):
'''
.. versionadded:: 2019.2.0
This is a wrapper to execute RPC requests on various network operating
systems supported by NAPALM, invoking the following functions for the NAPALM
native drivers:
- :py:func:`napalm.junos_rpc <salt.modules.napalm_mod.junos_rpc>` for ``junos``
- :py:func:`napalm.pyeapi_run_commands <salt.modules.napalm_mod.pyeapi_run_commands>`
for ``eos``
- :py:func:`napalm.nxos_api_rpc <salt.modules.napalm_mod.nxos_api_rpc>` for
``nxos``
- :py:func:`napalm.netmiko_commands <salt.modules.napalm_mod.netmiko_commands>`
for ``ios``, ``iosxr``, and ``nxos_ssh``
command
The RPC command to execute. This depends on the nature of the operating
system.
kwargs
Key-value arguments to be sent to the underlying Execution function.
The function capabilities are extensible in the user environment via the
``napalm_rpc_map`` configuration option / Pillar, e.g.,
.. code-block:: yaml
napalm_rpc_map:
f5: napalm.netmiko_commands
panos: panos.call
The mapping above reads: when the NAPALM ``os`` Grain is ``f5``, then call
``napalm.netmiko_commands`` for RPC requests.
By default, if the user does not specify any map, non-native NAPALM drivers
will invoke the ``napalm.netmiko_commands`` Execution function.
CLI Example:
.. code-block:: bash
salt '*' napalm.rpc 'show version'
salt '*' napalm.rpc get-interfaces
'''
default_map = {
'junos': 'napalm.junos_rpc',
'eos': 'napalm.pyeapi_run_commands',
'nxos': 'napalm.nxos_api_rpc'
}
napalm_map = __salt__['config.get']('napalm_rpc_map', {})
napalm_map.update(default_map)
fun = napalm_map.get(__grains__['os'], 'napalm.netmiko_commands')
return __salt__[fun](command, **kwargs) | [
"def",
"rpc",
"(",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"default_map",
"=",
"{",
"'junos'",
":",
"'napalm.junos_rpc'",
",",
"'eos'",
":",
"'napalm.pyeapi_run_commands'",
",",
"'nxos'",
":",
"'napalm.nxos_api_rpc'",
"}",
"napalm_map",
"=",
"__salt__",
... | .. versionadded:: 2019.2.0
This is a wrapper to execute RPC requests on various network operating
systems supported by NAPALM, invoking the following functions for the NAPALM
native drivers:
- :py:func:`napalm.junos_rpc <salt.modules.napalm_mod.junos_rpc>` for ``junos``
- :py:func:`napalm.pyeapi_run_commands <salt.modules.napalm_mod.pyeapi_run_commands>`
for ``eos``
- :py:func:`napalm.nxos_api_rpc <salt.modules.napalm_mod.nxos_api_rpc>` for
``nxos``
- :py:func:`napalm.netmiko_commands <salt.modules.napalm_mod.netmiko_commands>`
for ``ios``, ``iosxr``, and ``nxos_ssh``
command
The RPC command to execute. This depends on the nature of the operating
system.
kwargs
Key-value arguments to be sent to the underlying Execution function.
The function capabilities are extensible in the user environment via the
``napalm_rpc_map`` configuration option / Pillar, e.g.,
.. code-block:: yaml
napalm_rpc_map:
f5: napalm.netmiko_commands
panos: panos.call
The mapping above reads: when the NAPALM ``os`` Grain is ``f5``, then call
``napalm.netmiko_commands`` for RPC requests.
By default, if the user does not specify any map, non-native NAPALM drivers
will invoke the ``napalm.netmiko_commands`` Execution function.
CLI Example:
.. code-block:: bash
salt '*' napalm.rpc 'show version'
salt '*' napalm.rpc get-interfaces | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1299-L1352 | train |
saltstack/salt | salt/modules/napalm_mod.py | config_find_lines | def config_find_lines(regex, source='running'):
r'''
.. versionadded:: 2019.2.0
Return the configuration lines that match the regular expressions from the
``regex`` argument. The configuration is read from the network device
interrogated.
regex
The regular expression to match the configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_find_lines '^interface Ethernet1\d'
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['ciscoconfparse.find_lines'](config=config_txt,
regex=regex) | python | def config_find_lines(regex, source='running'):
r'''
.. versionadded:: 2019.2.0
Return the configuration lines that match the regular expressions from the
``regex`` argument. The configuration is read from the network device
interrogated.
regex
The regular expression to match the configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_find_lines '^interface Ethernet1\d'
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['ciscoconfparse.find_lines'](config=config_txt,
regex=regex) | [
"def",
"config_find_lines",
"(",
"regex",
",",
"source",
"=",
"'running'",
")",
":",
"config_txt",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
"source",
"=",
"source",
")",
"[",
"'out'",
"]",
"[",
"source",
"]",
"return",
"__salt__",
"[",
"'ciscoconfpa... | r'''
.. versionadded:: 2019.2.0
Return the configuration lines that match the regular expressions from the
``regex`` argument. The configuration is read from the network device
interrogated.
regex
The regular expression to match the configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_find_lines '^interface Ethernet1\d' | [
"r",
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1356-L1379 | train |
saltstack/salt | salt/modules/napalm_mod.py | config_lines_w_child | def config_lines_w_child(parent_regex, child_regex, source='running'):
r'''
.. versionadded:: 2019.2.0
Return the configuration lines that match the regular expressions from the
``parent_regex`` argument, having child lines matching ``child_regex``.
The configuration is read from the network device interrogated.
.. note::
This function is only available only when the underlying library
`ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
is installed. See
:py:func:`ciscoconfparse module <salt.modules.ciscoconfparse_mod>` for
more details.
parent_regex
The regular expression to match the parent configuration lines against.
child_regex
The regular expression to match the child configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_lines_w_child '^interface' 'ip address'
salt '*' napalm.config_lines_w_child '^interface' 'shutdown' source=candidate
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['ciscoconfparse.find_lines_w_child'](config=config_txt,
parent_regex=parent_regex,
child_regex=child_regex) | python | def config_lines_w_child(parent_regex, child_regex, source='running'):
r'''
.. versionadded:: 2019.2.0
Return the configuration lines that match the regular expressions from the
``parent_regex`` argument, having child lines matching ``child_regex``.
The configuration is read from the network device interrogated.
.. note::
This function is only available only when the underlying library
`ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
is installed. See
:py:func:`ciscoconfparse module <salt.modules.ciscoconfparse_mod>` for
more details.
parent_regex
The regular expression to match the parent configuration lines against.
child_regex
The regular expression to match the child configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_lines_w_child '^interface' 'ip address'
salt '*' napalm.config_lines_w_child '^interface' 'shutdown' source=candidate
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['ciscoconfparse.find_lines_w_child'](config=config_txt,
parent_regex=parent_regex,
child_regex=child_regex) | [
"def",
"config_lines_w_child",
"(",
"parent_regex",
",",
"child_regex",
",",
"source",
"=",
"'running'",
")",
":",
"config_txt",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
"source",
"=",
"source",
")",
"[",
"'out'",
"]",
"[",
"source",
"]",
"return",
... | r'''
.. versionadded:: 2019.2.0
Return the configuration lines that match the regular expressions from the
``parent_regex`` argument, having child lines matching ``child_regex``.
The configuration is read from the network device interrogated.
.. note::
This function is only available only when the underlying library
`ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
is installed. See
:py:func:`ciscoconfparse module <salt.modules.ciscoconfparse_mod>` for
more details.
parent_regex
The regular expression to match the parent configuration lines against.
child_regex
The regular expression to match the child configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_lines_w_child '^interface' 'ip address'
salt '*' napalm.config_lines_w_child '^interface' 'shutdown' source=candidate | [
"r",
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1383-L1418 | train |
saltstack/salt | salt/modules/napalm_mod.py | config_lines_wo_child | def config_lines_wo_child(parent_regex, child_regex, source='running'):
'''
.. versionadded:: 2019.2.0
Return the configuration lines that match the regular expressions from the
``parent_regex`` argument, having the child lines *not* matching
``child_regex``.
The configuration is read from the network device interrogated.
.. note::
This function is only available only when the underlying library
`ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
is installed. See
:py:func:`ciscoconfparse module <salt.modules.ciscoconfparse_mod>` for
more details.
parent_regex
The regular expression to match the parent configuration lines against.
child_regex
The regular expression to match the child configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_lines_wo_child '^interface' 'ip address'
salt '*' napalm.config_lines_wo_child '^interface' 'shutdown' source=candidate
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['ciscoconfparse.find_lines_wo_child'](config=config_txt,
parent_regex=parent_regex,
child_regex=child_regex) | python | def config_lines_wo_child(parent_regex, child_regex, source='running'):
'''
.. versionadded:: 2019.2.0
Return the configuration lines that match the regular expressions from the
``parent_regex`` argument, having the child lines *not* matching
``child_regex``.
The configuration is read from the network device interrogated.
.. note::
This function is only available only when the underlying library
`ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
is installed. See
:py:func:`ciscoconfparse module <salt.modules.ciscoconfparse_mod>` for
more details.
parent_regex
The regular expression to match the parent configuration lines against.
child_regex
The regular expression to match the child configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_lines_wo_child '^interface' 'ip address'
salt '*' napalm.config_lines_wo_child '^interface' 'shutdown' source=candidate
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['ciscoconfparse.find_lines_wo_child'](config=config_txt,
parent_regex=parent_regex,
child_regex=child_regex) | [
"def",
"config_lines_wo_child",
"(",
"parent_regex",
",",
"child_regex",
",",
"source",
"=",
"'running'",
")",
":",
"config_txt",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
"source",
"=",
"source",
")",
"[",
"'out'",
"]",
"[",
"source",
"]",
"return",
... | .. versionadded:: 2019.2.0
Return the configuration lines that match the regular expressions from the
``parent_regex`` argument, having the child lines *not* matching
``child_regex``.
The configuration is read from the network device interrogated.
.. note::
This function is only available only when the underlying library
`ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
is installed. See
:py:func:`ciscoconfparse module <salt.modules.ciscoconfparse_mod>` for
more details.
parent_regex
The regular expression to match the parent configuration lines against.
child_regex
The regular expression to match the child configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_lines_wo_child '^interface' 'ip address'
salt '*' napalm.config_lines_wo_child '^interface' 'shutdown' source=candidate | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1422-L1458 | train |
saltstack/salt | salt/modules/napalm_mod.py | config_filter_lines | def config_filter_lines(parent_regex, child_regex, source='running'):
r'''
.. versionadded:: 2019.2.0
Return a list of detailed matches, for the configuration blocks (parent-child
relationship) whose parent respects the regular expressions configured via
the ``parent_regex`` argument, and the child matches the ``child_regex``
regular expression. The result is a list of dictionaries with the following
keys:
- ``match``: a boolean value that tells whether ``child_regex`` matched any
children lines.
- ``parent``: the parent line (as text).
- ``child``: the child line (as text). If no child line matched, this field
will be ``None``.
.. note::
This function is only available only when the underlying library
`ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
is installed. See
:py:func:`ciscoconfparse module <salt.modules.ciscoconfparse_mod>` for
more details.
parent_regex
The regular expression to match the parent configuration lines against.
child_regex
The regular expression to match the child configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_filter_lines '^interface' 'ip address'
salt '*' napalm.config_filter_lines '^interface' 'shutdown' source=candidate
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['ciscoconfparse.filter_lines'](config=config_txt,
parent_regex=parent_regex,
child_regex=child_regex) | python | def config_filter_lines(parent_regex, child_regex, source='running'):
r'''
.. versionadded:: 2019.2.0
Return a list of detailed matches, for the configuration blocks (parent-child
relationship) whose parent respects the regular expressions configured via
the ``parent_regex`` argument, and the child matches the ``child_regex``
regular expression. The result is a list of dictionaries with the following
keys:
- ``match``: a boolean value that tells whether ``child_regex`` matched any
children lines.
- ``parent``: the parent line (as text).
- ``child``: the child line (as text). If no child line matched, this field
will be ``None``.
.. note::
This function is only available only when the underlying library
`ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
is installed. See
:py:func:`ciscoconfparse module <salt.modules.ciscoconfparse_mod>` for
more details.
parent_regex
The regular expression to match the parent configuration lines against.
child_regex
The regular expression to match the child configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_filter_lines '^interface' 'ip address'
salt '*' napalm.config_filter_lines '^interface' 'shutdown' source=candidate
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['ciscoconfparse.filter_lines'](config=config_txt,
parent_regex=parent_regex,
child_regex=child_regex) | [
"def",
"config_filter_lines",
"(",
"parent_regex",
",",
"child_regex",
",",
"source",
"=",
"'running'",
")",
":",
"config_txt",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
"source",
"=",
"source",
")",
"[",
"'out'",
"]",
"[",
"source",
"]",
"return",
"... | r'''
.. versionadded:: 2019.2.0
Return a list of detailed matches, for the configuration blocks (parent-child
relationship) whose parent respects the regular expressions configured via
the ``parent_regex`` argument, and the child matches the ``child_regex``
regular expression. The result is a list of dictionaries with the following
keys:
- ``match``: a boolean value that tells whether ``child_regex`` matched any
children lines.
- ``parent``: the parent line (as text).
- ``child``: the child line (as text). If no child line matched, this field
will be ``None``.
.. note::
This function is only available only when the underlying library
`ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
is installed. See
:py:func:`ciscoconfparse module <salt.modules.ciscoconfparse_mod>` for
more details.
parent_regex
The regular expression to match the parent configuration lines against.
child_regex
The regular expression to match the child configuration lines against.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_filter_lines '^interface' 'ip address'
salt '*' napalm.config_filter_lines '^interface' 'shutdown' source=candidate | [
"r",
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1462-L1505 | train |
saltstack/salt | salt/modules/napalm_mod.py | config_tree | def config_tree(source='running', with_tags=False):
'''
.. versionadded:: 2019.2.0
Transform Cisco IOS style configuration to structured Python dictionary.
Depending on the value of the ``with_tags`` argument, this function may
provide different views, valuable in different situations.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
with_tags: ``False``
Whether this function should return a detailed view, with tags.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_tree
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['iosconfig.tree'](config=config_txt) | python | def config_tree(source='running', with_tags=False):
'''
.. versionadded:: 2019.2.0
Transform Cisco IOS style configuration to structured Python dictionary.
Depending on the value of the ``with_tags`` argument, this function may
provide different views, valuable in different situations.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
with_tags: ``False``
Whether this function should return a detailed view, with tags.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_tree
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['iosconfig.tree'](config=config_txt) | [
"def",
"config_tree",
"(",
"source",
"=",
"'running'",
",",
"with_tags",
"=",
"False",
")",
":",
"config_txt",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
"source",
"=",
"source",
")",
"[",
"'out'",
"]",
"[",
"source",
"]",
"return",
"__salt__",
"[",... | .. versionadded:: 2019.2.0
Transform Cisco IOS style configuration to structured Python dictionary.
Depending on the value of the ``with_tags`` argument, this function may
provide different views, valuable in different situations.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
with_tags: ``False``
Whether this function should return a detailed view, with tags.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_tree | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1508-L1530 | train |
saltstack/salt | salt/modules/napalm_mod.py | config_merge_tree | def config_merge_tree(source='running',
merge_config=None,
merge_path=None,
saltenv='base'):
'''
.. versionadded:: 2019.2.0
Return the merge tree of the ``initial_config`` with the ``merge_config``,
as a Python dictionary.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_merge_tree merge_path=salt://path/to/merge.cfg
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['iosconfig.merge_tree'](initial_config=config_txt,
merge_config=merge_config,
merge_path=merge_path,
saltenv=saltenv) | python | def config_merge_tree(source='running',
merge_config=None,
merge_path=None,
saltenv='base'):
'''
.. versionadded:: 2019.2.0
Return the merge tree of the ``initial_config`` with the ``merge_config``,
as a Python dictionary.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_merge_tree merge_path=salt://path/to/merge.cfg
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['iosconfig.merge_tree'](initial_config=config_txt,
merge_config=merge_config,
merge_path=merge_path,
saltenv=saltenv) | [
"def",
"config_merge_tree",
"(",
"source",
"=",
"'running'",
",",
"merge_config",
"=",
"None",
",",
"merge_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"config_txt",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
"source",
"=",
"source",
"... | .. versionadded:: 2019.2.0
Return the merge tree of the ``initial_config`` with the ``merge_config``,
as a Python dictionary.
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_merge_tree merge_path=salt://path/to/merge.cfg | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1533-L1571 | train |
saltstack/salt | salt/modules/napalm_mod.py | config_merge_text | def config_merge_text(source='running',
merge_config=None,
merge_path=None,
saltenv='base'):
'''
.. versionadded:: 2019.2.0
Return the merge result of the configuration from ``source`` with the
merge configuration, as plain text (without loading the config on the
device).
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_merge_text merge_path=salt://path/to/merge.cfg
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['iosconfig.merge_text'](initial_config=config_txt,
merge_config=merge_config,
merge_path=merge_path,
saltenv=saltenv) | python | def config_merge_text(source='running',
merge_config=None,
merge_path=None,
saltenv='base'):
'''
.. versionadded:: 2019.2.0
Return the merge result of the configuration from ``source`` with the
merge configuration, as plain text (without loading the config on the
device).
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_merge_text merge_path=salt://path/to/merge.cfg
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['iosconfig.merge_text'](initial_config=config_txt,
merge_config=merge_config,
merge_path=merge_path,
saltenv=saltenv) | [
"def",
"config_merge_text",
"(",
"source",
"=",
"'running'",
",",
"merge_config",
"=",
"None",
",",
"merge_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"config_txt",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
"source",
"=",
"source",
"... | .. versionadded:: 2019.2.0
Return the merge result of the configuration from ``source`` with the
merge configuration, as plain text (without loading the config on the
device).
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_merge_text merge_path=salt://path/to/merge.cfg | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1574-L1613 | train |
saltstack/salt | salt/modules/napalm_mod.py | config_merge_diff | def config_merge_diff(source='running',
merge_config=None,
merge_path=None,
saltenv='base'):
'''
.. versionadded:: 2019.2.0
Return the merge diff, as text, after merging the merge config into the
configuration source requested (without loading the config on the device).
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_merge_diff merge_path=salt://path/to/merge.cfg
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['iosconfig.merge_diff'](initial_config=config_txt,
merge_config=merge_config,
merge_path=merge_path,
saltenv=saltenv) | python | def config_merge_diff(source='running',
merge_config=None,
merge_path=None,
saltenv='base'):
'''
.. versionadded:: 2019.2.0
Return the merge diff, as text, after merging the merge config into the
configuration source requested (without loading the config on the device).
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_merge_diff merge_path=salt://path/to/merge.cfg
'''
config_txt = __salt__['net.config'](source=source)['out'][source]
return __salt__['iosconfig.merge_diff'](initial_config=config_txt,
merge_config=merge_config,
merge_path=merge_path,
saltenv=saltenv) | [
"def",
"config_merge_diff",
"(",
"source",
"=",
"'running'",
",",
"merge_config",
"=",
"None",
",",
"merge_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"config_txt",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
"source",
"=",
"source",
"... | .. versionadded:: 2019.2.0
Return the merge diff, as text, after merging the merge config into the
configuration source requested (without loading the config on the device).
source: ``running``
The configuration type to retrieve from the network device. Default:
``running``. Available options: ``running``, ``startup``, ``candidate``.
merge_config
The config to be merged into the initial config, sent as text. This
argument is ignored when ``merge_path`` is set.
merge_path
Absolute or remote path from where to load the merge configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``merge_path`` is not a ``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_merge_diff merge_path=salt://path/to/merge.cfg | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1616-L1654 | train |
saltstack/salt | salt/modules/napalm_mod.py | config_diff_tree | def config_diff_tree(source1='candidate',
candidate_path=None,
source2='running',
running_path=None):
'''
.. versionadded:: 2019.2.0
Return the diff, as Python dictionary, between two different sources.
The sources can be either specified using the ``source1`` and ``source2``
arguments when retrieving from the managed network device.
source1: ``candidate``
The source from where to retrieve the configuration to be compared with.
Available options: ``candidate``, ``running``, ``startup``. Default:
``candidate``.
candidate_path
Absolute or remote path from where to load the candidate configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
source2: ``running``
The source from where to retrieve the configuration to compare with.
Available options: ``candidate``, ``running``, ``startup``. Default:
``running``.
running_path
Absolute or remote path from where to load the runing configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``candidate_path`` or ``running_path`` is not a
``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_diff_text
salt '*' napalm.config_diff_text candidate_path=https://bit.ly/2mAdq7z
# Would compare the running config with the configuration available at
# https://bit.ly/2mAdq7z
CLI Example:
.. code-block:: bash
salt '*' napalm.config_diff_tree
salt '*' napalm.config_diff_tree running startup
'''
get_config = __salt__['net.config']()['out']
candidate_cfg = get_config[source1]
running_cfg = get_config[source2]
return __salt__['iosconfig.diff_tree'](candidate_config=candidate_cfg,
candidate_path=candidate_path,
running_config=running_cfg,
running_path=running_path) | python | def config_diff_tree(source1='candidate',
candidate_path=None,
source2='running',
running_path=None):
'''
.. versionadded:: 2019.2.0
Return the diff, as Python dictionary, between two different sources.
The sources can be either specified using the ``source1`` and ``source2``
arguments when retrieving from the managed network device.
source1: ``candidate``
The source from where to retrieve the configuration to be compared with.
Available options: ``candidate``, ``running``, ``startup``. Default:
``candidate``.
candidate_path
Absolute or remote path from where to load the candidate configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
source2: ``running``
The source from where to retrieve the configuration to compare with.
Available options: ``candidate``, ``running``, ``startup``. Default:
``running``.
running_path
Absolute or remote path from where to load the runing configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``candidate_path`` or ``running_path`` is not a
``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_diff_text
salt '*' napalm.config_diff_text candidate_path=https://bit.ly/2mAdq7z
# Would compare the running config with the configuration available at
# https://bit.ly/2mAdq7z
CLI Example:
.. code-block:: bash
salt '*' napalm.config_diff_tree
salt '*' napalm.config_diff_tree running startup
'''
get_config = __salt__['net.config']()['out']
candidate_cfg = get_config[source1]
running_cfg = get_config[source2]
return __salt__['iosconfig.diff_tree'](candidate_config=candidate_cfg,
candidate_path=candidate_path,
running_config=running_cfg,
running_path=running_path) | [
"def",
"config_diff_tree",
"(",
"source1",
"=",
"'candidate'",
",",
"candidate_path",
"=",
"None",
",",
"source2",
"=",
"'running'",
",",
"running_path",
"=",
"None",
")",
":",
"get_config",
"=",
"__salt__",
"[",
"'net.config'",
"]",
"(",
")",
"[",
"'out'",
... | .. versionadded:: 2019.2.0
Return the diff, as Python dictionary, between two different sources.
The sources can be either specified using the ``source1`` and ``source2``
arguments when retrieving from the managed network device.
source1: ``candidate``
The source from where to retrieve the configuration to be compared with.
Available options: ``candidate``, ``running``, ``startup``. Default:
``candidate``.
candidate_path
Absolute or remote path from where to load the candidate configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
source2: ``running``
The source from where to retrieve the configuration to compare with.
Available options: ``candidate``, ``running``, ``startup``. Default:
``running``.
running_path
Absolute or remote path from where to load the runing configuration
text. This argument allows any URI supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`), e.g., ``salt://``,
``https://``, ``s3://``, ``ftp:/``, etc.
saltenv: ``base``
Salt fileserver environment from which to retrieve the file.
Ignored if ``candidate_path`` or ``running_path`` is not a
``salt://`` URL.
CLI Example:
.. code-block:: bash
salt '*' napalm.config_diff_text
salt '*' napalm.config_diff_text candidate_path=https://bit.ly/2mAdq7z
# Would compare the running config with the configuration available at
# https://bit.ly/2mAdq7z
CLI Example:
.. code-block:: bash
salt '*' napalm.config_diff_tree
salt '*' napalm.config_diff_tree running startup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1657-L1717 | train |
saltstack/salt | salt/modules/napalm_mod.py | scp_get | def scp_get(remote_path,
local_path='',
recursive=False,
preserve_times=False,
**kwargs):
'''
.. versionadded:: 2019.2.0
Transfer files and directories from remote network device to the localhost
of the Minion.
.. note::
This function is only available only when the underlying library
`scp <https://github.com/jbardin/scp.py>`_
is installed. See
:mod:`scp module <salt.modules.scp_mod>` for
more details.
remote_path
Path to retrieve from remote host. Since this is evaluated by scp on the
remote host, shell wildcards and environment variables may be used.
recursive: ``False``
Transfer files and directories recursively.
preserve_times: ``False``
Preserve ``mtime`` and ``atime`` of transferred files and directories.
passphrase
Used for decrypting private keys.
pkey
An optional private key to use for authentication.
key_filename
The filename, or list of filenames, of optional private key(s) and/or
certificates to try for authentication.
timeout
An optional timeout (in seconds) for the TCP connect.
socket_timeout: ``10``
The channel socket timeout in seconds.
buff_size: ``16384``
The size of the SCP send buffer.
allow_agent: ``True``
Set to ``False`` to disable connecting to the SSH agent.
look_for_keys: ``True``
Set to ``False`` to disable searching for discoverable private key
files in ``~/.ssh/``
banner_timeout
An optional timeout (in seconds) to wait for the SSH banner to be
presented.
auth_timeout
An optional timeout (in seconds) to wait for an authentication
response.
auto_add_policy: ``False``
Automatically add the host to the ``known_hosts``.
CLI Example:
.. code-block:: bash
salt '*' napalm.scp_get /var/tmp/file /tmp/file auto_add_policy=True
'''
conn_args = netmiko_args(**kwargs)
conn_args['hostname'] = conn_args['host']
kwargs.update(conn_args)
return __salt__['scp.get'](remote_path,
local_path=local_path,
recursive=recursive,
preserve_times=preserve_times,
**kwargs) | python | def scp_get(remote_path,
local_path='',
recursive=False,
preserve_times=False,
**kwargs):
'''
.. versionadded:: 2019.2.0
Transfer files and directories from remote network device to the localhost
of the Minion.
.. note::
This function is only available only when the underlying library
`scp <https://github.com/jbardin/scp.py>`_
is installed. See
:mod:`scp module <salt.modules.scp_mod>` for
more details.
remote_path
Path to retrieve from remote host. Since this is evaluated by scp on the
remote host, shell wildcards and environment variables may be used.
recursive: ``False``
Transfer files and directories recursively.
preserve_times: ``False``
Preserve ``mtime`` and ``atime`` of transferred files and directories.
passphrase
Used for decrypting private keys.
pkey
An optional private key to use for authentication.
key_filename
The filename, or list of filenames, of optional private key(s) and/or
certificates to try for authentication.
timeout
An optional timeout (in seconds) for the TCP connect.
socket_timeout: ``10``
The channel socket timeout in seconds.
buff_size: ``16384``
The size of the SCP send buffer.
allow_agent: ``True``
Set to ``False`` to disable connecting to the SSH agent.
look_for_keys: ``True``
Set to ``False`` to disable searching for discoverable private key
files in ``~/.ssh/``
banner_timeout
An optional timeout (in seconds) to wait for the SSH banner to be
presented.
auth_timeout
An optional timeout (in seconds) to wait for an authentication
response.
auto_add_policy: ``False``
Automatically add the host to the ``known_hosts``.
CLI Example:
.. code-block:: bash
salt '*' napalm.scp_get /var/tmp/file /tmp/file auto_add_policy=True
'''
conn_args = netmiko_args(**kwargs)
conn_args['hostname'] = conn_args['host']
kwargs.update(conn_args)
return __salt__['scp.get'](remote_path,
local_path=local_path,
recursive=recursive,
preserve_times=preserve_times,
**kwargs) | [
"def",
"scp_get",
"(",
"remote_path",
",",
"local_path",
"=",
"''",
",",
"recursive",
"=",
"False",
",",
"preserve_times",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conn_args",
"=",
"netmiko_args",
"(",
"*",
"*",
"kwargs",
")",
"conn_args",
"[",
... | .. versionadded:: 2019.2.0
Transfer files and directories from remote network device to the localhost
of the Minion.
.. note::
This function is only available only when the underlying library
`scp <https://github.com/jbardin/scp.py>`_
is installed. See
:mod:`scp module <salt.modules.scp_mod>` for
more details.
remote_path
Path to retrieve from remote host. Since this is evaluated by scp on the
remote host, shell wildcards and environment variables may be used.
recursive: ``False``
Transfer files and directories recursively.
preserve_times: ``False``
Preserve ``mtime`` and ``atime`` of transferred files and directories.
passphrase
Used for decrypting private keys.
pkey
An optional private key to use for authentication.
key_filename
The filename, or list of filenames, of optional private key(s) and/or
certificates to try for authentication.
timeout
An optional timeout (in seconds) for the TCP connect.
socket_timeout: ``10``
The channel socket timeout in seconds.
buff_size: ``16384``
The size of the SCP send buffer.
allow_agent: ``True``
Set to ``False`` to disable connecting to the SSH agent.
look_for_keys: ``True``
Set to ``False`` to disable searching for discoverable private key
files in ``~/.ssh/``
banner_timeout
An optional timeout (in seconds) to wait for the SSH banner to be
presented.
auth_timeout
An optional timeout (in seconds) to wait for an authentication
response.
auto_add_policy: ``False``
Automatically add the host to the ``known_hosts``.
CLI Example:
.. code-block:: bash
salt '*' napalm.scp_get /var/tmp/file /tmp/file auto_add_policy=True | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1777-L1855 | train |
saltstack/salt | salt/modules/napalm_mod.py | scp_put | def scp_put(files,
remote_path=None,
recursive=False,
preserve_times=False,
saltenv='base',
**kwargs):
'''
.. versionadded:: 2019.2.0
Transfer files and directories to remote network device.
.. note::
This function is only available only when the underlying library
`scp <https://github.com/jbardin/scp.py>`_
is installed. See
:mod:`scp module <salt.modules.scp_mod>` for
more details.
files
A single path or a list of paths to be transferred.
remote_path
The path on the remote device where to store the files.
recursive: ``True``
Transfer files and directories recursively.
preserve_times: ``False``
Preserve ``mtime`` and ``atime`` of transferred files and directories.
saltenv: ``base``
The name of the Salt environment. Ignored when ``files`` is not a
``salt://`` URL.
hostname
The hostname of the remote device.
port: ``22``
The port of the remote device.
username
The username required for SSH authentication on the device.
password
Used for password authentication. It is also used for private key
decryption if ``passphrase`` is not given.
passphrase
Used for decrypting private keys.
pkey
An optional private key to use for authentication.
key_filename
The filename, or list of filenames, of optional private key(s) and/or
certificates to try for authentication.
timeout
An optional timeout (in seconds) for the TCP connect.
socket_timeout: ``10``
The channel socket timeout in seconds.
buff_size: ``16384``
The size of the SCP send buffer.
allow_agent: ``True``
Set to ``False`` to disable connecting to the SSH agent.
look_for_keys: ``True``
Set to ``False`` to disable searching for discoverable private key
files in ``~/.ssh/``
banner_timeout
An optional timeout (in seconds) to wait for the SSH banner to be
presented.
auth_timeout
An optional timeout (in seconds) to wait for an authentication
response.
auto_add_policy: ``False``
Automatically add the host to the ``known_hosts``.
CLI Example:
.. code-block:: bash
salt '*' napalm.scp_put /path/to/file /var/tmp/file auto_add_policy=True
'''
conn_args = netmiko_args(**kwargs)
conn_args['hostname'] = conn_args['host']
kwargs.update(conn_args)
return __salt__['scp.put'](files,
remote_path=remote_path,
recursive=recursive,
preserve_times=preserve_times,
saltenv=saltenv,
**kwargs) | python | def scp_put(files,
remote_path=None,
recursive=False,
preserve_times=False,
saltenv='base',
**kwargs):
'''
.. versionadded:: 2019.2.0
Transfer files and directories to remote network device.
.. note::
This function is only available only when the underlying library
`scp <https://github.com/jbardin/scp.py>`_
is installed. See
:mod:`scp module <salt.modules.scp_mod>` for
more details.
files
A single path or a list of paths to be transferred.
remote_path
The path on the remote device where to store the files.
recursive: ``True``
Transfer files and directories recursively.
preserve_times: ``False``
Preserve ``mtime`` and ``atime`` of transferred files and directories.
saltenv: ``base``
The name of the Salt environment. Ignored when ``files`` is not a
``salt://`` URL.
hostname
The hostname of the remote device.
port: ``22``
The port of the remote device.
username
The username required for SSH authentication on the device.
password
Used for password authentication. It is also used for private key
decryption if ``passphrase`` is not given.
passphrase
Used for decrypting private keys.
pkey
An optional private key to use for authentication.
key_filename
The filename, or list of filenames, of optional private key(s) and/or
certificates to try for authentication.
timeout
An optional timeout (in seconds) for the TCP connect.
socket_timeout: ``10``
The channel socket timeout in seconds.
buff_size: ``16384``
The size of the SCP send buffer.
allow_agent: ``True``
Set to ``False`` to disable connecting to the SSH agent.
look_for_keys: ``True``
Set to ``False`` to disable searching for discoverable private key
files in ``~/.ssh/``
banner_timeout
An optional timeout (in seconds) to wait for the SSH banner to be
presented.
auth_timeout
An optional timeout (in seconds) to wait for an authentication
response.
auto_add_policy: ``False``
Automatically add the host to the ``known_hosts``.
CLI Example:
.. code-block:: bash
salt '*' napalm.scp_put /path/to/file /var/tmp/file auto_add_policy=True
'''
conn_args = netmiko_args(**kwargs)
conn_args['hostname'] = conn_args['host']
kwargs.update(conn_args)
return __salt__['scp.put'](files,
remote_path=remote_path,
recursive=recursive,
preserve_times=preserve_times,
saltenv=saltenv,
**kwargs) | [
"def",
"scp_put",
"(",
"files",
",",
"remote_path",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"preserve_times",
"=",
"False",
",",
"saltenv",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
"conn_args",
"=",
"netmiko_args",
"(",
"*",
"*",
"kw... | .. versionadded:: 2019.2.0
Transfer files and directories to remote network device.
.. note::
This function is only available only when the underlying library
`scp <https://github.com/jbardin/scp.py>`_
is installed. See
:mod:`scp module <salt.modules.scp_mod>` for
more details.
files
A single path or a list of paths to be transferred.
remote_path
The path on the remote device where to store the files.
recursive: ``True``
Transfer files and directories recursively.
preserve_times: ``False``
Preserve ``mtime`` and ``atime`` of transferred files and directories.
saltenv: ``base``
The name of the Salt environment. Ignored when ``files`` is not a
``salt://`` URL.
hostname
The hostname of the remote device.
port: ``22``
The port of the remote device.
username
The username required for SSH authentication on the device.
password
Used for password authentication. It is also used for private key
decryption if ``passphrase`` is not given.
passphrase
Used for decrypting private keys.
pkey
An optional private key to use for authentication.
key_filename
The filename, or list of filenames, of optional private key(s) and/or
certificates to try for authentication.
timeout
An optional timeout (in seconds) for the TCP connect.
socket_timeout: ``10``
The channel socket timeout in seconds.
buff_size: ``16384``
The size of the SCP send buffer.
allow_agent: ``True``
Set to ``False`` to disable connecting to the SSH agent.
look_for_keys: ``True``
Set to ``False`` to disable searching for discoverable private key
files in ``~/.ssh/``
banner_timeout
An optional timeout (in seconds) to wait for the SSH banner to be
presented.
auth_timeout
An optional timeout (in seconds) to wait for an authentication
response.
auto_add_policy: ``False``
Automatically add the host to the ``known_hosts``.
CLI Example:
.. code-block:: bash
salt '*' napalm.scp_put /path/to/file /var/tmp/file auto_add_policy=True | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_mod.py#L1859-L1957 | train |
saltstack/salt | salt/utils/nacl.py | _get_config | def _get_config(**kwargs):
'''
Return configuration
'''
config = {
'box_type': 'sealedbox',
'sk': None,
'sk_file': os.path.join(kwargs['opts'].get('pki_dir'), 'master/nacl'),
'pk': None,
'pk_file': os.path.join(kwargs['opts'].get('pki_dir'), 'master/nacl.pub'),
}
config_key = '{0}.config'.format(__virtualname__)
try:
config.update(__salt__['config.get'](config_key, {}))
except (NameError, KeyError) as e:
# likely using salt-run so fallback to __opts__
config.update(kwargs['opts'].get(config_key, {}))
# pylint: disable=C0201
for k in set(config.keys()) & set(kwargs.keys()):
config[k] = kwargs[k]
return config | python | def _get_config(**kwargs):
'''
Return configuration
'''
config = {
'box_type': 'sealedbox',
'sk': None,
'sk_file': os.path.join(kwargs['opts'].get('pki_dir'), 'master/nacl'),
'pk': None,
'pk_file': os.path.join(kwargs['opts'].get('pki_dir'), 'master/nacl.pub'),
}
config_key = '{0}.config'.format(__virtualname__)
try:
config.update(__salt__['config.get'](config_key, {}))
except (NameError, KeyError) as e:
# likely using salt-run so fallback to __opts__
config.update(kwargs['opts'].get(config_key, {}))
# pylint: disable=C0201
for k in set(config.keys()) & set(kwargs.keys()):
config[k] = kwargs[k]
return config | [
"def",
"_get_config",
"(",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"{",
"'box_type'",
":",
"'sealedbox'",
",",
"'sk'",
":",
"None",
",",
"'sk_file'",
":",
"os",
".",
"path",
".",
"join",
"(",
"kwargs",
"[",
"'opts'",
"]",
".",
"get",
"(",
"'pk... | Return configuration | [
"Return",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L43-L64 | train |
saltstack/salt | salt/utils/nacl.py | _get_sk | def _get_sk(**kwargs):
'''
Return sk
'''
config = _get_config(**kwargs)
key = salt.utils.stringutils.to_str(config['sk'])
sk_file = config['sk_file']
if not key and sk_file:
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
key = salt.utils.stringutils.to_unicode(keyf.read()).rstrip('\n')
if key is None:
raise Exception('no key or sk_file found')
return base64.b64decode(key) | python | def _get_sk(**kwargs):
'''
Return sk
'''
config = _get_config(**kwargs)
key = salt.utils.stringutils.to_str(config['sk'])
sk_file = config['sk_file']
if not key and sk_file:
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
key = salt.utils.stringutils.to_unicode(keyf.read()).rstrip('\n')
if key is None:
raise Exception('no key or sk_file found')
return base64.b64decode(key) | [
"def",
"_get_sk",
"(",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"_get_config",
"(",
"*",
"*",
"kwargs",
")",
"key",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_str",
"(",
"config",
"[",
"'sk'",
"]",
")",
"sk_file",
"=",
"config",
"[... | Return sk | [
"Return",
"sk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L67-L79 | train |
saltstack/salt | salt/utils/nacl.py | _get_pk | def _get_pk(**kwargs):
'''
Return pk
'''
config = _get_config(**kwargs)
pubkey = salt.utils.stringutils.to_str(config['pk'])
pk_file = config['pk_file']
if not pubkey and pk_file:
with salt.utils.files.fopen(pk_file, 'rb') as keyf:
pubkey = salt.utils.stringutils.to_unicode(keyf.read()).rstrip('\n')
if pubkey is None:
raise Exception('no pubkey or pk_file found')
pubkey = six.text_type(pubkey)
return base64.b64decode(pubkey) | python | def _get_pk(**kwargs):
'''
Return pk
'''
config = _get_config(**kwargs)
pubkey = salt.utils.stringutils.to_str(config['pk'])
pk_file = config['pk_file']
if not pubkey and pk_file:
with salt.utils.files.fopen(pk_file, 'rb') as keyf:
pubkey = salt.utils.stringutils.to_unicode(keyf.read()).rstrip('\n')
if pubkey is None:
raise Exception('no pubkey or pk_file found')
pubkey = six.text_type(pubkey)
return base64.b64decode(pubkey) | [
"def",
"_get_pk",
"(",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"_get_config",
"(",
"*",
"*",
"kwargs",
")",
"pubkey",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_str",
"(",
"config",
"[",
"'pk'",
"]",
")",
"pk_file",
"=",
"config",
... | Return pk | [
"Return",
"pk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L82-L95 | train |
saltstack/salt | salt/utils/nacl.py | keygen | def keygen(sk_file=None, pk_file=None, **kwargs):
'''
Use libnacl to generate a keypair.
If no `sk_file` is defined return a keypair.
If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`.
When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated
using the `sk_file`.
CLI Examples:
.. code-block:: bash
salt-call nacl.keygen
salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl
salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub
salt-call --local nacl.keygen
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk_file\' argument instead.'
)
sk_file = kwargs['keyfile']
if sk_file is None:
kp = libnacl.public.SecretKey()
return {'sk': base64.b64encode(kp.sk), 'pk': base64.b64encode(kp.pk)}
if pk_file is None:
pk_file = '{0}.pub'.format(sk_file)
if sk_file and pk_file is None:
if not os.path.isfile(sk_file):
kp = libnacl.public.SecretKey()
with salt.utils.files.fopen(sk_file, 'wb') as keyf:
keyf.write(base64.b64encode(kp.sk))
if salt.utils.platform.is_windows():
cur_user = salt.utils.win_functions.get_current_user()
salt.utils.win_dacl.set_owner(sk_file, cur_user)
salt.utils.win_dacl.set_permissions(sk_file, cur_user, 'full_control', 'grant', reset_perms=True, protected=True)
else:
# chmod 0600 file
os.chmod(sk_file, 1536)
return 'saved sk_file: {0}'.format(sk_file)
else:
raise Exception('sk_file:{0} already exist.'.format(sk_file))
if sk_file is None and pk_file:
raise Exception('sk_file: Must be set inorder to generate a public key.')
if os.path.isfile(sk_file) and os.path.isfile(pk_file):
raise Exception('sk_file:{0} and pk_file:{1} already exist.'.format(sk_file, pk_file))
if os.path.isfile(sk_file) and not os.path.isfile(pk_file):
# generate pk using the sk
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
sk = salt.utils.stringutils.to_unicode(keyf.read()).rstrip('\n')
sk = base64.b64decode(sk)
kp = libnacl.public.SecretKey(sk)
with salt.utils.files.fopen(pk_file, 'wb') as keyf:
keyf.write(base64.b64encode(kp.pk))
return 'saved pk_file: {0}'.format(pk_file)
kp = libnacl.public.SecretKey()
with salt.utils.files.fopen(sk_file, 'wb') as keyf:
keyf.write(base64.b64encode(kp.sk))
if salt.utils.platform.is_windows():
cur_user = salt.utils.win_functions.get_current_user()
salt.utils.win_dacl.set_owner(sk_file, cur_user)
salt.utils.win_dacl.set_permissions(sk_file, cur_user, 'full_control', 'grant', reset_perms=True, protected=True)
else:
# chmod 0600 file
os.chmod(sk_file, 1536)
with salt.utils.files.fopen(pk_file, 'wb') as keyf:
keyf.write(base64.b64encode(kp.pk))
return 'saved sk_file:{0} pk_file: {1}'.format(sk_file, pk_file) | python | def keygen(sk_file=None, pk_file=None, **kwargs):
'''
Use libnacl to generate a keypair.
If no `sk_file` is defined return a keypair.
If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`.
When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated
using the `sk_file`.
CLI Examples:
.. code-block:: bash
salt-call nacl.keygen
salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl
salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub
salt-call --local nacl.keygen
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk_file\' argument instead.'
)
sk_file = kwargs['keyfile']
if sk_file is None:
kp = libnacl.public.SecretKey()
return {'sk': base64.b64encode(kp.sk), 'pk': base64.b64encode(kp.pk)}
if pk_file is None:
pk_file = '{0}.pub'.format(sk_file)
if sk_file and pk_file is None:
if not os.path.isfile(sk_file):
kp = libnacl.public.SecretKey()
with salt.utils.files.fopen(sk_file, 'wb') as keyf:
keyf.write(base64.b64encode(kp.sk))
if salt.utils.platform.is_windows():
cur_user = salt.utils.win_functions.get_current_user()
salt.utils.win_dacl.set_owner(sk_file, cur_user)
salt.utils.win_dacl.set_permissions(sk_file, cur_user, 'full_control', 'grant', reset_perms=True, protected=True)
else:
# chmod 0600 file
os.chmod(sk_file, 1536)
return 'saved sk_file: {0}'.format(sk_file)
else:
raise Exception('sk_file:{0} already exist.'.format(sk_file))
if sk_file is None and pk_file:
raise Exception('sk_file: Must be set inorder to generate a public key.')
if os.path.isfile(sk_file) and os.path.isfile(pk_file):
raise Exception('sk_file:{0} and pk_file:{1} already exist.'.format(sk_file, pk_file))
if os.path.isfile(sk_file) and not os.path.isfile(pk_file):
# generate pk using the sk
with salt.utils.files.fopen(sk_file, 'rb') as keyf:
sk = salt.utils.stringutils.to_unicode(keyf.read()).rstrip('\n')
sk = base64.b64decode(sk)
kp = libnacl.public.SecretKey(sk)
with salt.utils.files.fopen(pk_file, 'wb') as keyf:
keyf.write(base64.b64encode(kp.pk))
return 'saved pk_file: {0}'.format(pk_file)
kp = libnacl.public.SecretKey()
with salt.utils.files.fopen(sk_file, 'wb') as keyf:
keyf.write(base64.b64encode(kp.sk))
if salt.utils.platform.is_windows():
cur_user = salt.utils.win_functions.get_current_user()
salt.utils.win_dacl.set_owner(sk_file, cur_user)
salt.utils.win_dacl.set_permissions(sk_file, cur_user, 'full_control', 'grant', reset_perms=True, protected=True)
else:
# chmod 0600 file
os.chmod(sk_file, 1536)
with salt.utils.files.fopen(pk_file, 'wb') as keyf:
keyf.write(base64.b64encode(kp.pk))
return 'saved sk_file:{0} pk_file: {1}'.format(sk_file, pk_file) | [
"def",
"keygen",
"(",
"sk_file",
"=",
"None",
",",
"pk_file",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'keyfile'",
"in",
"kwargs",
":",
"salt",
".",
"utils",
".",
"versions",
".",
"warn_until",
"(",
"'Neon'",
",",
"'The \\'keyfile\\' argume... | Use libnacl to generate a keypair.
If no `sk_file` is defined return a keypair.
If only the `sk_file` is defined `pk_file` will use the same name with a postfix `.pub`.
When the `sk_file` is already existing, but `pk_file` is not. The `pk_file` will be generated
using the `sk_file`.
CLI Examples:
.. code-block:: bash
salt-call nacl.keygen
salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl
salt-call nacl.keygen sk_file=/etc/salt/pki/master/nacl pk_file=/etc/salt/pki/master/nacl.pub
salt-call --local nacl.keygen | [
"Use",
"libnacl",
"to",
"generate",
"a",
"keypair",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L98-L177 | train |
saltstack/salt | salt/utils/nacl.py | enc | def enc(data, **kwargs):
'''
Alias to `{box_type}_encrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk_file\' argument instead.'
)
kwargs['sk_file'] = kwargs['keyfile']
if 'key' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'key\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk\' argument instead.'
)
kwargs['sk'] = kwargs['key']
box_type = _get_config(**kwargs)['box_type']
if box_type == 'secretbox':
return secretbox_encrypt(data, **kwargs)
return sealedbox_encrypt(data, **kwargs) | python | def enc(data, **kwargs):
'''
Alias to `{box_type}_encrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk_file\' argument instead.'
)
kwargs['sk_file'] = kwargs['keyfile']
if 'key' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'key\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk\' argument instead.'
)
kwargs['sk'] = kwargs['key']
box_type = _get_config(**kwargs)['box_type']
if box_type == 'secretbox':
return secretbox_encrypt(data, **kwargs)
return sealedbox_encrypt(data, **kwargs) | [
"def",
"enc",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'keyfile'",
"in",
"kwargs",
":",
"salt",
".",
"utils",
".",
"versions",
".",
"warn_until",
"(",
"'Neon'",
",",
"'The \\'keyfile\\' argument has been deprecated and will be removed in Salt '",
"'{... | Alias to `{box_type}_encrypt`
box_type: secretbox, sealedbox(default) | [
"Alias",
"to",
"{",
"box_type",
"}",
"_encrypt"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L180-L205 | train |
saltstack/salt | salt/utils/nacl.py | enc_file | def enc_file(name, out=None, **kwargs):
'''
This is a helper function to encrypt a file and return its contents.
You can provide an optional output file using `out`
`name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc.
CLI Examples:
.. code-block:: bash
salt-run nacl.enc_file name=/tmp/id_rsa
salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert
salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \
sk_file=/etc/salt/pki/master/nacl.pub
'''
try:
data = __salt__['cp.get_file_str'](name)
except Exception as e:
# likly using salt-run so fallback to local filesystem
with salt.utils.files.fopen(name, 'rb') as f:
data = salt.utils.stringutils.to_unicode(f.read())
d = enc(data, **kwargs)
if out:
if os.path.isfile(out):
raise Exception('file:{0} already exist.'.format(out))
with salt.utils.files.fopen(out, 'wb') as f:
f.write(salt.utils.stringutils.to_bytes(d))
return 'Wrote: {0}'.format(out)
return d | python | def enc_file(name, out=None, **kwargs):
'''
This is a helper function to encrypt a file and return its contents.
You can provide an optional output file using `out`
`name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc.
CLI Examples:
.. code-block:: bash
salt-run nacl.enc_file name=/tmp/id_rsa
salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert
salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \
sk_file=/etc/salt/pki/master/nacl.pub
'''
try:
data = __salt__['cp.get_file_str'](name)
except Exception as e:
# likly using salt-run so fallback to local filesystem
with salt.utils.files.fopen(name, 'rb') as f:
data = salt.utils.stringutils.to_unicode(f.read())
d = enc(data, **kwargs)
if out:
if os.path.isfile(out):
raise Exception('file:{0} already exist.'.format(out))
with salt.utils.files.fopen(out, 'wb') as f:
f.write(salt.utils.stringutils.to_bytes(d))
return 'Wrote: {0}'.format(out)
return d | [
"def",
"enc_file",
"(",
"name",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"data",
"=",
"__salt__",
"[",
"'cp.get_file_str'",
"]",
"(",
"name",
")",
"except",
"Exception",
"as",
"e",
":",
"# likly using salt-run so fallback to ... | This is a helper function to encrypt a file and return its contents.
You can provide an optional output file using `out`
`name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc.
CLI Examples:
.. code-block:: bash
salt-run nacl.enc_file name=/tmp/id_rsa
salt-call nacl.enc_file name=salt://crt/mycert out=/tmp/cert
salt-run nacl.enc_file name=/tmp/id_rsa box_type=secretbox \
sk_file=/etc/salt/pki/master/nacl.pub | [
"This",
"is",
"a",
"helper",
"function",
"to",
"encrypt",
"a",
"file",
"and",
"return",
"its",
"contents",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L208-L238 | train |
saltstack/salt | salt/utils/nacl.py | dec | def dec(data, **kwargs):
'''
Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk_file\' argument instead.'
)
kwargs['sk_file'] = kwargs['keyfile']
# set boxtype to `secretbox` to maintain backward compatibility
kwargs['box_type'] = 'secretbox'
if 'key' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'key\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk\' argument instead.'
)
kwargs['sk'] = kwargs['key']
# set boxtype to `secretbox` to maintain backward compatibility
kwargs['box_type'] = 'secretbox'
box_type = _get_config(**kwargs)['box_type']
if box_type == 'secretbox':
return secretbox_decrypt(data, **kwargs)
return sealedbox_decrypt(data, **kwargs) | python | def dec(data, **kwargs):
'''
Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk_file\' argument instead.'
)
kwargs['sk_file'] = kwargs['keyfile']
# set boxtype to `secretbox` to maintain backward compatibility
kwargs['box_type'] = 'secretbox'
if 'key' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'key\' argument has been deprecated and will be removed in Salt '
'{version}. Please use \'sk\' argument instead.'
)
kwargs['sk'] = kwargs['key']
# set boxtype to `secretbox` to maintain backward compatibility
kwargs['box_type'] = 'secretbox'
box_type = _get_config(**kwargs)['box_type']
if box_type == 'secretbox':
return secretbox_decrypt(data, **kwargs)
return sealedbox_decrypt(data, **kwargs) | [
"def",
"dec",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'keyfile'",
"in",
"kwargs",
":",
"salt",
".",
"utils",
".",
"versions",
".",
"warn_until",
"(",
"'Neon'",
",",
"'The \\'keyfile\\' argument has been deprecated and will be removed in Salt '",
"'{... | Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default) | [
"Alias",
"to",
"{",
"box_type",
"}",
"_decrypt"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L241-L272 | train |
saltstack/salt | salt/utils/nacl.py | sealedbox_encrypt | def sealedbox_encrypt(data, **kwargs):
'''
Encrypt data using a public key generated from `nacl.keygen`.
The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key.
CLI Examples:
.. code-block:: bash
salt-run nacl.sealedbox_encrypt datatoenc
salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub
salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ='
'''
# ensure data is in bytes
data = salt.utils.stringutils.to_bytes(data)
pk = _get_pk(**kwargs)
b = libnacl.sealed.SealedBox(pk)
return base64.b64encode(b.encrypt(data)) | python | def sealedbox_encrypt(data, **kwargs):
'''
Encrypt data using a public key generated from `nacl.keygen`.
The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key.
CLI Examples:
.. code-block:: bash
salt-run nacl.sealedbox_encrypt datatoenc
salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub
salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ='
'''
# ensure data is in bytes
data = salt.utils.stringutils.to_bytes(data)
pk = _get_pk(**kwargs)
b = libnacl.sealed.SealedBox(pk)
return base64.b64encode(b.encrypt(data)) | [
"def",
"sealedbox_encrypt",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# ensure data is in bytes",
"data",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_bytes",
"(",
"data",
")",
"pk",
"=",
"_get_pk",
"(",
"*",
"*",
"kwargs",
")",
"b",
... | Encrypt data using a public key generated from `nacl.keygen`.
The encryptd data can be decrypted using `nacl.sealedbox_decrypt` only with the secret key.
CLI Examples:
.. code-block:: bash
salt-run nacl.sealedbox_encrypt datatoenc
salt-call --local nacl.sealedbox_encrypt datatoenc pk_file=/etc/salt/pki/master/nacl.pub
salt-call --local nacl.sealedbox_encrypt datatoenc pk='vrwQF7cNiNAVQVAiS3bvcbJUnF0cN6fU9YTZD9mBfzQ=' | [
"Encrypt",
"data",
"using",
"a",
"public",
"key",
"generated",
"from",
"nacl",
".",
"keygen",
".",
"The",
"encryptd",
"data",
"can",
"be",
"decrypted",
"using",
"nacl",
".",
"sealedbox_decrypt",
"only",
"with",
"the",
"secret",
"key",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L308-L326 | train |
saltstack/salt | salt/utils/nacl.py | sealedbox_decrypt | def sealedbox_decrypt(data, **kwargs):
'''
Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`.
CLI Examples:
.. code-block:: bash
salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A=
salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
'''
if data is None:
return None
# ensure data is in bytes
data = salt.utils.stringutils.to_bytes(data)
sk = _get_sk(**kwargs)
keypair = libnacl.public.SecretKey(sk)
b = libnacl.sealed.SealedBox(keypair)
return b.decrypt(base64.b64decode(data)) | python | def sealedbox_decrypt(data, **kwargs):
'''
Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`.
CLI Examples:
.. code-block:: bash
salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A=
salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
'''
if data is None:
return None
# ensure data is in bytes
data = salt.utils.stringutils.to_bytes(data)
sk = _get_sk(**kwargs)
keypair = libnacl.public.SecretKey(sk)
b = libnacl.sealed.SealedBox(keypair)
return b.decrypt(base64.b64decode(data)) | [
"def",
"sealedbox_decrypt",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"# ensure data is in bytes",
"data",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_bytes",
"(",
"data",
")",
"sk",
"=... | Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`.
CLI Examples:
.. code-block:: bash
salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A=
salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' | [
"Decrypt",
"data",
"using",
"a",
"secret",
"key",
"that",
"was",
"encrypted",
"using",
"a",
"public",
"key",
"with",
"nacl",
".",
"sealedbox_encrypt",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L329-L350 | train |
saltstack/salt | salt/utils/nacl.py | secretbox_encrypt | def secretbox_encrypt(data, **kwargs):
'''
Encrypt data using a secret key generated from `nacl.keygen`.
The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`.
CLI Examples:
.. code-block:: bash
salt-run nacl.secretbox_encrypt datatoenc
salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo='
'''
# ensure data is in bytes
data = salt.utils.stringutils.to_bytes(data)
sk = _get_sk(**kwargs)
b = libnacl.secret.SecretBox(sk)
return base64.b64encode(b.encrypt(data)) | python | def secretbox_encrypt(data, **kwargs):
'''
Encrypt data using a secret key generated from `nacl.keygen`.
The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`.
CLI Examples:
.. code-block:: bash
salt-run nacl.secretbox_encrypt datatoenc
salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo='
'''
# ensure data is in bytes
data = salt.utils.stringutils.to_bytes(data)
sk = _get_sk(**kwargs)
b = libnacl.secret.SecretBox(sk)
return base64.b64encode(b.encrypt(data)) | [
"def",
"secretbox_encrypt",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# ensure data is in bytes",
"data",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_bytes",
"(",
"data",
")",
"sk",
"=",
"_get_sk",
"(",
"*",
"*",
"kwargs",
")",
"b",
... | Encrypt data using a secret key generated from `nacl.keygen`.
The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`.
CLI Examples:
.. code-block:: bash
salt-run nacl.secretbox_encrypt datatoenc
salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.secretbox_encrypt datatoenc sk='YmFkcGFzcwo=' | [
"Encrypt",
"data",
"using",
"a",
"secret",
"key",
"generated",
"from",
"nacl",
".",
"keygen",
".",
"The",
"same",
"secret",
"key",
"can",
"be",
"used",
"to",
"decrypt",
"the",
"data",
"using",
"nacl",
".",
"secretbox_decrypt",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L353-L371 | train |
saltstack/salt | salt/utils/nacl.py | secretbox_decrypt | def secretbox_decrypt(data, **kwargs):
'''
Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key
that was generated from `nacl.keygen`.
CLI Examples:
.. code-block:: bash
salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A=
salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
'''
if data is None:
return None
# ensure data is in bytes
data = salt.utils.stringutils.to_bytes(data)
key = _get_sk(**kwargs)
b = libnacl.secret.SecretBox(key=key)
return b.decrypt(base64.b64decode(data)) | python | def secretbox_decrypt(data, **kwargs):
'''
Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key
that was generated from `nacl.keygen`.
CLI Examples:
.. code-block:: bash
salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A=
salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo='
'''
if data is None:
return None
# ensure data is in bytes
data = salt.utils.stringutils.to_bytes(data)
key = _get_sk(**kwargs)
b = libnacl.secret.SecretBox(key=key)
return b.decrypt(base64.b64decode(data)) | [
"def",
"secretbox_decrypt",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"# ensure data is in bytes",
"data",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_bytes",
"(",
"data",
")",
"key",
"... | Decrypt data that was encrypted using `nacl.secretbox_encrypt` using the secret key
that was generated from `nacl.keygen`.
CLI Examples:
.. code-block:: bash
salt-call nacl.secretbox_decrypt pEXHQM6cuaF7A=
salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl
salt-call --local nacl.secretbox_decrypt data='pEXHQM6cuaF7A=' sk='YmFkcGFzcwo=' | [
"Decrypt",
"data",
"that",
"was",
"encrypted",
"using",
"nacl",
".",
"secretbox_encrypt",
"using",
"the",
"secret",
"key",
"that",
"was",
"generated",
"from",
"nacl",
".",
"keygen",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L374-L396 | train |
saltstack/salt | salt/states/grafana_dashboard.py | present | def present(name,
base_dashboards_from_pillar=None,
base_panels_from_pillar=None,
base_rows_from_pillar=None,
dashboard=None,
profile='grafana'):
'''
Ensure the grafana dashboard exists and is managed.
name
Name of the grafana dashboard.
base_dashboards_from_pillar
A pillar key that contains a list of dashboards to inherit from
base_panels_from_pillar
A pillar key that contains a list of panels to inherit from
base_rows_from_pillar
A pillar key that contains a list of rows to inherit from
dashboard
A dict that defines a dashboard that should be managed.
profile
A pillar key or dict that contains grafana information
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
base_dashboards_from_pillar = base_dashboards_from_pillar or []
base_panels_from_pillar = base_panels_from_pillar or []
base_rows_from_pillar = base_rows_from_pillar or []
dashboard = dashboard or {}
if isinstance(profile, six.string_types):
profile = __salt__['config.option'](profile)
# Add pillar keys for default configuration
base_dashboards_from_pillar = ([_DEFAULT_DASHBOARD_PILLAR] +
base_dashboards_from_pillar)
base_panels_from_pillar = ([_DEFAULT_PANEL_PILLAR] +
base_panels_from_pillar)
base_rows_from_pillar = [_DEFAULT_ROW_PILLAR] + base_rows_from_pillar
# Build out all dashboard fields
new_dashboard = _inherited_dashboard(
dashboard, base_dashboards_from_pillar, ret)
new_dashboard['title'] = name
rows = new_dashboard.get('rows', [])
for i, row in enumerate(rows):
rows[i] = _inherited_row(row, base_rows_from_pillar, ret)
for row in rows:
panels = row.get('panels', [])
for i, panel in enumerate(panels):
panels[i] = _inherited_panel(panel, base_panels_from_pillar, ret)
_auto_adjust_panel_spans(new_dashboard)
_ensure_panel_ids(new_dashboard)
_ensure_annotations(new_dashboard)
# Create dashboard if it does not exist
url = 'db/{0}'.format(name)
old_dashboard = _get(url, profile)
if not old_dashboard:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dashboard {0} is set to be created.'.format(name)
return ret
response = _update(new_dashboard, profile)
if response.get('status') == 'success':
ret['comment'] = 'Dashboard {0} created.'.format(name)
ret['changes']['new'] = 'Dashboard {0} created.'.format(name)
else:
ret['result'] = False
ret['comment'] = ("Failed to create dashboard {0}, "
"response={1}").format(name, response)
return ret
# Add unmanaged rows to the dashboard. They appear at the top if they are
# marked as pinned. They appear at the bottom otherwise.
managed_row_titles = [row.get('title')
for row in new_dashboard.get('rows', [])]
new_rows = new_dashboard.get('rows', [])
for old_row in old_dashboard.get('rows', []):
if old_row.get('title') not in managed_row_titles:
new_rows.append(copy.deepcopy(old_row))
_ensure_pinned_rows(new_dashboard)
_ensure_panel_ids(new_dashboard)
# Update dashboard if it differs
dashboard_diff = DictDiffer(_cleaned(new_dashboard),
_cleaned(old_dashboard))
updated_needed = (dashboard_diff.changed() or
dashboard_diff.added() or
dashboard_diff.removed())
if updated_needed:
if __opts__['test']:
ret['result'] = None
ret['comment'] = (
str('Dashboard {0} is set to be updated, changes={1}').format( # future lint: blacklisted-function
name,
salt.utils.json.dumps(
_dashboard_diff(
_cleaned(new_dashboard),
_cleaned(old_dashboard)
),
indent=4
)
)
)
return ret
response = _update(new_dashboard, profile)
if response.get('status') == 'success':
updated_dashboard = _get(url, profile)
dashboard_diff = DictDiffer(_cleaned(updated_dashboard),
_cleaned(old_dashboard))
ret['comment'] = 'Dashboard {0} updated.'.format(name)
ret['changes'] = _dashboard_diff(_cleaned(new_dashboard),
_cleaned(old_dashboard))
else:
ret['result'] = False
ret['comment'] = ("Failed to update dashboard {0}, "
"response={1}").format(name, response)
return ret
ret['comment'] = 'Dashboard present'
return ret | python | def present(name,
base_dashboards_from_pillar=None,
base_panels_from_pillar=None,
base_rows_from_pillar=None,
dashboard=None,
profile='grafana'):
'''
Ensure the grafana dashboard exists and is managed.
name
Name of the grafana dashboard.
base_dashboards_from_pillar
A pillar key that contains a list of dashboards to inherit from
base_panels_from_pillar
A pillar key that contains a list of panels to inherit from
base_rows_from_pillar
A pillar key that contains a list of rows to inherit from
dashboard
A dict that defines a dashboard that should be managed.
profile
A pillar key or dict that contains grafana information
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
base_dashboards_from_pillar = base_dashboards_from_pillar or []
base_panels_from_pillar = base_panels_from_pillar or []
base_rows_from_pillar = base_rows_from_pillar or []
dashboard = dashboard or {}
if isinstance(profile, six.string_types):
profile = __salt__['config.option'](profile)
# Add pillar keys for default configuration
base_dashboards_from_pillar = ([_DEFAULT_DASHBOARD_PILLAR] +
base_dashboards_from_pillar)
base_panels_from_pillar = ([_DEFAULT_PANEL_PILLAR] +
base_panels_from_pillar)
base_rows_from_pillar = [_DEFAULT_ROW_PILLAR] + base_rows_from_pillar
# Build out all dashboard fields
new_dashboard = _inherited_dashboard(
dashboard, base_dashboards_from_pillar, ret)
new_dashboard['title'] = name
rows = new_dashboard.get('rows', [])
for i, row in enumerate(rows):
rows[i] = _inherited_row(row, base_rows_from_pillar, ret)
for row in rows:
panels = row.get('panels', [])
for i, panel in enumerate(panels):
panels[i] = _inherited_panel(panel, base_panels_from_pillar, ret)
_auto_adjust_panel_spans(new_dashboard)
_ensure_panel_ids(new_dashboard)
_ensure_annotations(new_dashboard)
# Create dashboard if it does not exist
url = 'db/{0}'.format(name)
old_dashboard = _get(url, profile)
if not old_dashboard:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dashboard {0} is set to be created.'.format(name)
return ret
response = _update(new_dashboard, profile)
if response.get('status') == 'success':
ret['comment'] = 'Dashboard {0} created.'.format(name)
ret['changes']['new'] = 'Dashboard {0} created.'.format(name)
else:
ret['result'] = False
ret['comment'] = ("Failed to create dashboard {0}, "
"response={1}").format(name, response)
return ret
# Add unmanaged rows to the dashboard. They appear at the top if they are
# marked as pinned. They appear at the bottom otherwise.
managed_row_titles = [row.get('title')
for row in new_dashboard.get('rows', [])]
new_rows = new_dashboard.get('rows', [])
for old_row in old_dashboard.get('rows', []):
if old_row.get('title') not in managed_row_titles:
new_rows.append(copy.deepcopy(old_row))
_ensure_pinned_rows(new_dashboard)
_ensure_panel_ids(new_dashboard)
# Update dashboard if it differs
dashboard_diff = DictDiffer(_cleaned(new_dashboard),
_cleaned(old_dashboard))
updated_needed = (dashboard_diff.changed() or
dashboard_diff.added() or
dashboard_diff.removed())
if updated_needed:
if __opts__['test']:
ret['result'] = None
ret['comment'] = (
str('Dashboard {0} is set to be updated, changes={1}').format( # future lint: blacklisted-function
name,
salt.utils.json.dumps(
_dashboard_diff(
_cleaned(new_dashboard),
_cleaned(old_dashboard)
),
indent=4
)
)
)
return ret
response = _update(new_dashboard, profile)
if response.get('status') == 'success':
updated_dashboard = _get(url, profile)
dashboard_diff = DictDiffer(_cleaned(updated_dashboard),
_cleaned(old_dashboard))
ret['comment'] = 'Dashboard {0} updated.'.format(name)
ret['changes'] = _dashboard_diff(_cleaned(new_dashboard),
_cleaned(old_dashboard))
else:
ret['result'] = False
ret['comment'] = ("Failed to update dashboard {0}, "
"response={1}").format(name, response)
return ret
ret['comment'] = 'Dashboard present'
return ret | [
"def",
"present",
"(",
"name",
",",
"base_dashboards_from_pillar",
"=",
"None",
",",
"base_panels_from_pillar",
"=",
"None",
",",
"base_rows_from_pillar",
"=",
"None",
",",
"dashboard",
"=",
"None",
",",
"profile",
"=",
"'grafana'",
")",
":",
"ret",
"=",
"{",
... | Ensure the grafana dashboard exists and is managed.
name
Name of the grafana dashboard.
base_dashboards_from_pillar
A pillar key that contains a list of dashboards to inherit from
base_panels_from_pillar
A pillar key that contains a list of panels to inherit from
base_rows_from_pillar
A pillar key that contains a list of rows to inherit from
dashboard
A dict that defines a dashboard that should be managed.
profile
A pillar key or dict that contains grafana information | [
"Ensure",
"the",
"grafana",
"dashboard",
"exists",
"and",
"is",
"managed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L63-L190 | train |
saltstack/salt | salt/states/grafana_dashboard.py | absent | def absent(name, profile='grafana'):
'''
Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
profile
A pillar key or dict that contains grafana information
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if isinstance(profile, six.string_types):
profile = __salt__['config.option'](profile)
url = 'db/{0}'.format(name)
existing_dashboard = _get(url, profile)
if existing_dashboard:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dashboard {0} is set to be deleted.'.format(name)
return ret
_delete(url, profile)
ret['comment'] = 'Dashboard {0} deleted.'.format(name)
ret['changes']['new'] = 'Dashboard {0} deleted.'.format(name)
return ret
ret['comment'] = 'Dashboard absent'
return ret | python | def absent(name, profile='grafana'):
'''
Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
profile
A pillar key or dict that contains grafana information
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if isinstance(profile, six.string_types):
profile = __salt__['config.option'](profile)
url = 'db/{0}'.format(name)
existing_dashboard = _get(url, profile)
if existing_dashboard:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dashboard {0} is set to be deleted.'.format(name)
return ret
_delete(url, profile)
ret['comment'] = 'Dashboard {0} deleted.'.format(name)
ret['changes']['new'] = 'Dashboard {0} deleted.'.format(name)
return ret
ret['comment'] = 'Dashboard absent'
return ret | [
"def",
"absent",
"(",
"name",
",",
"profile",
"=",
"'grafana'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"isinstance",
"(",
"profile",
"... | Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
profile
A pillar key or dict that contains grafana information | [
"Ensure",
"the",
"named",
"grafana",
"dashboard",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L193-L222 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _cleaned | def _cleaned(_dashboard):
'''Return a copy without fields that can differ.'''
dashboard = copy.deepcopy(_dashboard)
for ignored_dashboard_field in _IGNORED_DASHBOARD_FIELDS:
dashboard.pop(ignored_dashboard_field, None)
for row in dashboard.get('rows', []):
for ignored_row_field in _IGNORED_ROW_FIELDS:
row.pop(ignored_row_field, None)
for i, panel in enumerate(row.get('panels', [])):
for ignored_panel_field in _IGNORED_PANEL_FIELDS:
panel.pop(ignored_panel_field, None)
for target in panel.get('targets', []):
for ignored_target_field in _IGNORED_TARGET_FIELDS:
target.pop(ignored_target_field, None)
row['panels'][i] = _stripped(panel)
return dashboard | python | def _cleaned(_dashboard):
'''Return a copy without fields that can differ.'''
dashboard = copy.deepcopy(_dashboard)
for ignored_dashboard_field in _IGNORED_DASHBOARD_FIELDS:
dashboard.pop(ignored_dashboard_field, None)
for row in dashboard.get('rows', []):
for ignored_row_field in _IGNORED_ROW_FIELDS:
row.pop(ignored_row_field, None)
for i, panel in enumerate(row.get('panels', [])):
for ignored_panel_field in _IGNORED_PANEL_FIELDS:
panel.pop(ignored_panel_field, None)
for target in panel.get('targets', []):
for ignored_target_field in _IGNORED_TARGET_FIELDS:
target.pop(ignored_target_field, None)
row['panels'][i] = _stripped(panel)
return dashboard | [
"def",
"_cleaned",
"(",
"_dashboard",
")",
":",
"dashboard",
"=",
"copy",
".",
"deepcopy",
"(",
"_dashboard",
")",
"for",
"ignored_dashboard_field",
"in",
"_IGNORED_DASHBOARD_FIELDS",
":",
"dashboard",
".",
"pop",
"(",
"ignored_dashboard_field",
",",
"None",
")",
... | Return a copy without fields that can differ. | [
"Return",
"a",
"copy",
"without",
"fields",
"that",
"can",
"differ",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L241-L258 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _inherited_dashboard | def _inherited_dashboard(dashboard, base_dashboards_from_pillar, ret):
'''Return a dashboard with properties from parents.'''
base_dashboards = []
for base_dashboard_from_pillar in base_dashboards_from_pillar:
base_dashboard = __salt__['pillar.get'](base_dashboard_from_pillar)
if base_dashboard:
base_dashboards.append(base_dashboard)
elif base_dashboard_from_pillar != _DEFAULT_DASHBOARD_PILLAR:
ret.setdefault('warnings', [])
warning_message = 'Cannot find dashboard pillar "{0}".'.format(
base_dashboard_from_pillar)
if warning_message not in ret['warnings']:
ret['warnings'].append(warning_message)
base_dashboards.append(dashboard)
result_dashboard = {}
tags = set()
for dashboard in base_dashboards:
tags.update(dashboard.get('tags', []))
result_dashboard.update(dashboard)
result_dashboard['tags'] = list(tags)
return result_dashboard | python | def _inherited_dashboard(dashboard, base_dashboards_from_pillar, ret):
'''Return a dashboard with properties from parents.'''
base_dashboards = []
for base_dashboard_from_pillar in base_dashboards_from_pillar:
base_dashboard = __salt__['pillar.get'](base_dashboard_from_pillar)
if base_dashboard:
base_dashboards.append(base_dashboard)
elif base_dashboard_from_pillar != _DEFAULT_DASHBOARD_PILLAR:
ret.setdefault('warnings', [])
warning_message = 'Cannot find dashboard pillar "{0}".'.format(
base_dashboard_from_pillar)
if warning_message not in ret['warnings']:
ret['warnings'].append(warning_message)
base_dashboards.append(dashboard)
result_dashboard = {}
tags = set()
for dashboard in base_dashboards:
tags.update(dashboard.get('tags', []))
result_dashboard.update(dashboard)
result_dashboard['tags'] = list(tags)
return result_dashboard | [
"def",
"_inherited_dashboard",
"(",
"dashboard",
",",
"base_dashboards_from_pillar",
",",
"ret",
")",
":",
"base_dashboards",
"=",
"[",
"]",
"for",
"base_dashboard_from_pillar",
"in",
"base_dashboards_from_pillar",
":",
"base_dashboard",
"=",
"__salt__",
"[",
"'pillar.g... | Return a dashboard with properties from parents. | [
"Return",
"a",
"dashboard",
"with",
"properties",
"from",
"parents",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L261-L282 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _inherited_row | def _inherited_row(row, base_rows_from_pillar, ret):
'''Return a row with properties from parents.'''
base_rows = []
for base_row_from_pillar in base_rows_from_pillar:
base_row = __salt__['pillar.get'](base_row_from_pillar)
if base_row:
base_rows.append(base_row)
elif base_row_from_pillar != _DEFAULT_ROW_PILLAR:
ret.setdefault('warnings', [])
warning_message = 'Cannot find row pillar "{0}".'.format(
base_row_from_pillar)
if warning_message not in ret['warnings']:
ret['warnings'].append(warning_message)
base_rows.append(row)
result_row = {}
for row in base_rows:
result_row.update(row)
return result_row | python | def _inherited_row(row, base_rows_from_pillar, ret):
'''Return a row with properties from parents.'''
base_rows = []
for base_row_from_pillar in base_rows_from_pillar:
base_row = __salt__['pillar.get'](base_row_from_pillar)
if base_row:
base_rows.append(base_row)
elif base_row_from_pillar != _DEFAULT_ROW_PILLAR:
ret.setdefault('warnings', [])
warning_message = 'Cannot find row pillar "{0}".'.format(
base_row_from_pillar)
if warning_message not in ret['warnings']:
ret['warnings'].append(warning_message)
base_rows.append(row)
result_row = {}
for row in base_rows:
result_row.update(row)
return result_row | [
"def",
"_inherited_row",
"(",
"row",
",",
"base_rows_from_pillar",
",",
"ret",
")",
":",
"base_rows",
"=",
"[",
"]",
"for",
"base_row_from_pillar",
"in",
"base_rows_from_pillar",
":",
"base_row",
"=",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"base_row_from_pilla... | Return a row with properties from parents. | [
"Return",
"a",
"row",
"with",
"properties",
"from",
"parents",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L285-L303 | train |
saltstack/salt | salt/states/grafana_dashboard.py | _inherited_panel | def _inherited_panel(panel, base_panels_from_pillar, ret):
'''Return a panel with properties from parents.'''
base_panels = []
for base_panel_from_pillar in base_panels_from_pillar:
base_panel = __salt__['pillar.get'](base_panel_from_pillar)
if base_panel:
base_panels.append(base_panel)
elif base_panel_from_pillar != _DEFAULT_PANEL_PILLAR:
ret.setdefault('warnings', [])
warning_message = 'Cannot find panel pillar "{0}".'.format(
base_panel_from_pillar)
if warning_message not in ret['warnings']:
ret['warnings'].append(warning_message)
base_panels.append(panel)
result_panel = {}
for panel in base_panels:
result_panel.update(panel)
return result_panel | python | def _inherited_panel(panel, base_panels_from_pillar, ret):
'''Return a panel with properties from parents.'''
base_panels = []
for base_panel_from_pillar in base_panels_from_pillar:
base_panel = __salt__['pillar.get'](base_panel_from_pillar)
if base_panel:
base_panels.append(base_panel)
elif base_panel_from_pillar != _DEFAULT_PANEL_PILLAR:
ret.setdefault('warnings', [])
warning_message = 'Cannot find panel pillar "{0}".'.format(
base_panel_from_pillar)
if warning_message not in ret['warnings']:
ret['warnings'].append(warning_message)
base_panels.append(panel)
result_panel = {}
for panel in base_panels:
result_panel.update(panel)
return result_panel | [
"def",
"_inherited_panel",
"(",
"panel",
",",
"base_panels_from_pillar",
",",
"ret",
")",
":",
"base_panels",
"=",
"[",
"]",
"for",
"base_panel_from_pillar",
"in",
"base_panels_from_pillar",
":",
"base_panel",
"=",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"base_... | Return a panel with properties from parents. | [
"Return",
"a",
"panel",
"with",
"properties",
"from",
"parents",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L306-L324 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.