INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return detailed information about the vms. | def vm_info(vm_=None):
'''
Return detailed information about the vms.
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_info
'''
with _get_xapi_session()... |
Return list of all the vms and their state. | def vm_state(vm_=None):
'''
Return list of all the vms and their state.
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_state <vm name>
'''
with _get_x... |
Return a dict with information about this node | def node_info():
'''
Return a dict with information about this node
CLI Example:
.. code-block:: bash
salt '*' virt.node_info
'''
with _get_xapi_session() as xapi:
# get node uuid
host_rec = _get_record(xapi, 'host', _get_all(xapi, 'host')[0])
# get first CPU (... |
Return info about the network interfaces of a named vm | def get_nics(vm_):
'''
Return info about the network interfaces of a named vm
CLI Example:
.. code-block:: bash
salt '*' virt.get_nics <vm name>
'''
with _get_xapi_session() as xapi:
nic = {}
vm_rec = _get_record_by_label(xapi, 'VM', vm_)
if vm_rec is False:
... |
Return a list off MAC addresses from the named vm | def get_macs(vm_):
'''
Return a list off MAC addresses from the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.get_macs <vm name>
'''
macs = []
nics = get_nics(vm_)
if nics is None:
return None
for nic in nics:
macs.append(nic)
return macs |
Return the disks of a named vm | def get_disks(vm_):
'''
Return the disks of a named vm
CLI Example:
.. code-block:: bash
salt '*' virt.get_disks <vm name>
'''
with _get_xapi_session() as xapi:
disk = {}
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if vm_uuid is False:
return False... |
Changes the amount of memory allocated to VM. | def setmem(vm_, memory):
'''
Changes the amount of memory allocated to VM.
Memory is to be specified in MB
CLI Example:
.. code-block:: bash
salt '*' virt.setmem myvm 768
'''
with _get_xapi_session() as xapi:
mem_target = int(memory) * 1024 * 1024
vm_uuid = _get_... |
Changes the amount of vcpus allocated to VM. | def setvcpus(vm_, vcpus):
'''
Changes the amount of vcpus allocated to VM.
vcpus is an int representing the number to be assigned
CLI Example:
.. code-block:: bash
salt '*' virt.setvcpus myvm 2
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm... |
Set which CPUs a VCPU can use. | def vcpu_pin(vm_, vcpu, cpus):
'''
Set which CPUs a VCPU can use.
CLI Example:
.. code-block:: bash
salt 'foo' virt.vcpu_pin domU-id 2 1
salt 'foo' virt.vcpu_pin domU-id 2 2-6
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if ... |
Send a soft shutdown signal to the named vm | def shutdown(vm_):
'''
Send a soft shutdown signal to the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.shutdown <vm name>
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if vm_uuid is False:
return False
... |
Pause the named vm | def pause(vm_):
'''
Pause the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.pause <vm name>
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if vm_uuid is False:
return False
try:
xapi.VM.pause(... |
Resume the named vm | def resume(vm_):
'''
Resume the named vm
CLI Example:
.. code-block:: bash
salt '*' virt.resume <vm name>
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if vm_uuid is False:
return False
try:
xapi.VM.unp... |
Reboot a domain via ACPI request | def reboot(vm_):
'''
Reboot a domain via ACPI request
CLI Example:
.. code-block:: bash
salt '*' virt.reboot <vm name>
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if vm_uuid is False:
return False
try:
... |
Reset a VM by emulating the reset button on a physical machine | def reset(vm_):
'''
Reset a VM by emulating the reset button on a physical machine
CLI Example:
.. code-block:: bash
salt '*' virt.reset <vm name>
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if vm_uuid is False:
return F... |
Migrates the virtual machine to another hypervisor | def migrate(vm_, target,
live=1, port=0, node=-1, ssl=None, change_home_server=0):
'''
Migrates the virtual machine to another hypervisor
CLI Example:
.. code-block:: bash
salt '*' virt.migrate <vm name> <target hypervisor> [live] [port] [node] [ssl] [change_home_server]
Opti... |
Hard power down the virtual machine this is equivalent to pulling the power | def stop(vm_):
'''
Hard power down the virtual machine, this is equivalent to pulling the
power
CLI Example:
.. code-block:: bash
salt '*' virt.stop <vm name>
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if vm_uuid is False:
... |
Returns a bool whether or not this node is a hypervisor of any kind | def is_hyper():
'''
Returns a bool whether or not this node is a hypervisor of any kind
CLI Example:
.. code-block:: bash
salt '*' virt.is_hyper
'''
try:
if __grains__['virtual_subtype'] != 'Xen Dom0':
return False
except KeyError:
# virtual_subtype isn... |
Return cputime used by the vms on this hyper in a list of dicts: | def vm_cputime(vm_=None):
'''
Return cputime used by the vms on this hyper in a
list of dicts:
.. code-block:: python
[
'your-vm': {
'cputime' <int>
'cputime_percent' <int>
},
...
]
If you pass a VM name i... |
Return combined network counters used by the vms on this hyper in a list of dicts: | def vm_netstats(vm_=None):
'''
Return combined network counters used by the vms on this hyper in a
list of dicts:
.. code-block:: python
[
'your-vm': {
'io_read_kbs' : 0,
'io_total_read_kbs' : 0,
'io_total_write_kbs' ... |
Return disk usage counters used by the vms on this hyper in a list of dicts: | def vm_diskstats(vm_=None):
'''
Return disk usage counters used by the vms on this hyper in a
list of dicts:
.. code-block:: python
[
'your-vm': {
'io_read_kbs' : 0,
'io_write_kbs' : 0
},
...
]
If you p... |
Internal helper to sanitize message output | def _clean_message(message):
'''Internal helper to sanitize message output'''
message = message.replace('zonecfg: ', '')
message = message.splitlines()
for line in message:
if line.startswith('On line'):
message.remove(line)
return "\n".join(message) |
Internal helper for parsing configuration values into python values | def _parse_value(value):
'''Internal helper for parsing configuration values into python values'''
if isinstance(value, bool):
return 'true' if value else 'false'
elif isinstance(value, six.string_types):
# parse compacted notation to dict
listparser = re.compile(r'''((?:[^,"']|"[^"]... |
Internal helper for converting pythonic values to configuration file values | def _sanitize_value(value):
'''Internal helper for converting pythonic values to configuration file values'''
# dump dict into compated
if isinstance(value, dict):
new_value = []
new_value.append('(')
for k, v in value.items():
new_value.append(k)
new_value.ap... |
Internal helper for debugging cfg files | def _dump_cfg(cfg_file):
'''Internal helper for debugging cfg files'''
if __salt__['file.file_exists'](cfg_file):
with salt.utils.files.fopen(cfg_file, 'r') as fp_:
log.debug(
"zonecfg - configuration file:\n%s",
"".join(salt.utils.data.decode(fp_.readline... |
Create an in - memory configuration for the specified zone. | def create(zone, brand, zonepath, force=False):
'''
Create an in-memory configuration for the specified zone.
zone : string
name of zone
brand : string
brand name
zonepath : string
path of zone
force : boolean
overwrite configuration
CLI Example:
.. cod... |
Create an in - memory configuration from a template for the specified zone. | def create_from_template(zone, template):
'''
Create an in-memory configuration from a template for the specified zone.
zone : string
name of zone
template : string
name of template
.. warning::
existing config will be overwritten!
CLI Example:
.. code-block:: bas... |
Delete the specified configuration from memory and stable storage. | def delete(zone):
'''
Delete the specified configuration from memory and stable storage.
zone : string
name of zone
CLI Example:
.. code-block:: bash
salt '*' zonecfg.delete epyon
'''
ret = {'status': True}
# delete zone
res = __salt__['cmd.run_all']('zonecfg -z ... |
Export the configuration from memory to stable storage. | def export(zone, path=None):
'''
Export the configuration from memory to stable storage.
zone : string
name of zone
path : string
path of file to export to
CLI Example:
.. code-block:: bash
salt '*' zonecfg.export epyon
salt '*' zonecfg.export epyon /zones/epy... |
Import the configuration to memory from stable storage. | def import_(zone, path):
'''
Import the configuration to memory from stable storage.
zone : string
name of zone
path : string
path of file to export to
CLI Example:
.. code-block:: bash
salt '*' zonecfg.import epyon /zones/epyon.cfg
'''
ret = {'status': True}
... |
internal handler for set and clear_property | def _property(methode, zone, key, value):
'''
internal handler for set and clear_property
methode : string
either set, add, or clear
zone : string
name of zone
key : string
name of property
value : string
value of property
'''
ret = {'status': True}
... |
internal resource hanlder | def _resource(methode, zone, resource_type, resource_selector, **kwargs):
'''
internal resource hanlder
methode : string
add or update
zone : string
name of zone
resource_type : string
type of resource
resource_selector : string
unique resource identifier
**k... |
Add a resource | def update_resource(zone, resource_type, resource_selector, **kwargs):
'''
Add a resource
zone : string
name of zone
resource_type : string
type of resource
resource_selector : string
unique resource identifier
kwargs : string|int|...
resource properties
.. ... |
Remove a resource | def remove_resource(zone, resource_type, resource_key, resource_value):
'''
Remove a resource
zone : string
name of zone
resource_type : string
type of resource
resource_key : string
key for resource selection
resource_value : string
value for resource selection
... |
Display the configuration from memory | def info(zone, show_all=False):
'''
Display the configuration from memory
zone : string
name of zone
show_all : boolean
also include calculated values like capped-cpu, cpu-shares, ...
CLI Example:
.. code-block:: bash
salt '*' zonecfg.info tallgeese
'''
ret = ... |
Verify and display a nag - messsage to the log if vulnerable hash - type is used. | def verify_hash_type(self):
'''
Verify and display a nag-messsage to the log if vulnerable hash-type is used.
:return:
'''
if self.config['hash_type'].lower() in ['md5', 'sha1']:
log.warning(
'IMPORTANT: Do not use %s hashing algorithm! Please set '
... |
Log environment failure for the daemon and exit with the error code. | def environment_failure(self, error):
'''
Log environment failure for the daemon and exit with the error code.
:param error:
:return:
'''
log.exception(
'Failed to create environment for %s: %s',
self.__class__.__name__, get_error_message(error)
... |
Run the preparation sequence required to start a salt master server. | def prepare(self):
'''
Run the preparation sequence required to start a salt master server.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
'''
super(Master, self).prepare()
try:
if self.config['verify_env']:
... |
Start the actual master. | def start(self):
'''
Start the actual master.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
'''
super(Master, self).start()
if check_user(self.config['user']):
... |
If sub - classed run any shutdown operations on this method. | def shutdown(self, exitcode=0, exitmsg=None):
'''
If sub-classed, run any shutdown operations on this method.
'''
self.shutdown_log_info()
msg = 'The salt master is shutdown. '
if exitmsg is not None:
exitmsg = msg + exitmsg
else:
exitmsg =... |
Run the preparation sequence required to start a salt minion. | def prepare(self):
'''
Run the preparation sequence required to start a salt minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
'''
super(Minion, self).prepare()
try:
if self.config['verify_env']:
... |
Start the actual minion. | def start(self):
'''
Start the actual minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
'''
super(Minion, self).start()
while True:
try:
... |
Start the actual minion as a caller minion. | def call(self, cleanup_protecteds):
'''
Start the actual minion as a caller minion.
cleanup_protecteds is list of yard host addresses that should not be
cleaned up this is to fix race condition when salt-caller minion starts up
If sub-classed, don't **ever** forget to run:
... |
If sub - classed run any shutdown operations on this method. | def shutdown(self, exitcode=0, exitmsg=None):
'''
If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg
'''
self.action_log_info('Shutting down')
if hasattr(self, 'minion') and hasattr(self.minion, 'destroy'):
self... |
Run the preparation sequence required to start a salt proxy minion. | def prepare(self):
'''
Run the preparation sequence required to start a salt proxy minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
'''
super(ProxyMinion, self).prepare()
if not self.values.proxyid:
self.... |
Start the actual proxy minion. | def start(self):
'''
Start the actual proxy minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
'''
super(ProxyMinion, self).start()
try:
if check_... |
If sub - classed run any shutdown operations on this method. | def shutdown(self, exitcode=0, exitmsg=None):
'''
If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg
'''
if hasattr(self, 'minion') and 'proxymodule' in self.minion.opts:
proxy_fn = self.minion.opts['proxymodule'].loade... |
Run the preparation sequence required to start a salt syndic minion. | def prepare(self):
'''
Run the preparation sequence required to start a salt syndic minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
'''
super(Syndic, self).prepare()
try:
if self.config['verify_env']:
... |
Start the actual syndic. | def start(self):
'''
Start the actual syndic.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
'''
super(Syndic, self).start()
if check_user(self.config['user']):
... |
If sub - classed run any shutdown operations on this method. | def shutdown(self, exitcode=0, exitmsg=None):
'''
If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg
'''
self.action_log_info('Shutting down')
super(Syndic, self).shutdown(
exitcode, ('The Salt {0} is shutdown. ... |
Execute rac commands | def __execute_cmd(command):
'''
Execute rac commands
'''
cmd = __salt__['cmd.run_all']('racadm {0}'.format(command))
if cmd['retcode'] != 0:
log.warning('racadm return an exit code \'%s\'.', cmd['retcode'])
return False
return True |
Configure the nameservers on the DRAC | def nameservers(*ns):
'''
Configure the nameservers on the DRAC
CLI Example:
.. code-block:: bash
salt dell drac.nameservers [NAMESERVERS]
salt dell drac.nameservers ns1.example.com ns2.example.com
'''
if len(ns) > 2:
log.warning('racadm only supports two nameservers')... |
Configure syslog remote logging by default syslog will automatically be enabled if a server is specified. However if you want to disable syslog you will need to specify a server followed by False | def syslog(server, enable=True):
'''
Configure syslog remote logging, by default syslog will automatically be
enabled if a server is specified. However, if you want to disable syslog
you will need to specify a server followed by False
CLI Example:
.. code-block:: bash
salt dell drac.s... |
List all DRAC users | def list_users():
'''
List all DRAC users
CLI Example:
.. code-block:: bash
salt dell drac.list_users
'''
users = {}
_username = ''
for idx in range(1, 17):
cmd = __salt__['cmd.run_all']('racadm getconfig -g \
cfgUserAdmin -i {0}'.format(idx))
... |
Delete a user | def delete_user(username, uid=None):
'''
Delete a user
CLI Example:
.. code-block:: bash
salt dell drac.delete_user [USERNAME] [UID - optional]
salt dell drac.delete_user diana 4
'''
if uid is None:
user = list_users()
uid = user[username]['index']
if uid:... |
Change users password | def change_password(username, password, uid=None):
'''
Change users password
CLI Example:
.. code-block:: bash
salt dell drac.change_password [USERNAME] [PASSWORD] [UID - optional]
salt dell drac.change_password diana secret
'''
if uid is None:
user = list_users()
... |
Create user accounts | def create_user(username, password, permissions, users=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell drac.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell drac.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* logi... |
Configure users permissions | def set_permissions(username, permissions, uid=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell drac.set_permissions [USERNAME] [PRIVILEGES] [USER INDEX - optional]
salt dell drac.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileg... |
Configure server to PXE perform a one off PXE boot | def server_pxe():
'''
Configure server to PXE perform a one off PXE boot
CLI Example:
.. code-block:: bash
salt dell drac.server_pxe
'''
if __execute_cmd('config -g cfgServerInfo -o \
cfgServerFirstBootDevice PXE'):
if __execute_cmd('config -g cfgServerInfo -o cfgS... |
Get the modified time of the RPM Database. | def _get_mtime():
"""
Get the modified time of the RPM Database.
Returns:
Unix ticks
"""
return os.path.exists(RPM_PATH) and int(os.path.getmtime(RPM_PATH)) or 0 |
Get the checksum of the RPM Database. | def _get_checksum():
"""
Get the checksum of the RPM Database.
Returns:
hexdigest
"""
digest = hashlib.sha256()
with open(RPM_PATH, "rb") as rpm_db_fh:
while True:
buff = rpm_db_fh.read(0x1000)
if not buff:
break
digest.update(... |
Hook after the package installation transaction. | def posttrans_hook(conduit):
"""
Hook after the package installation transaction.
:param conduit:
:return:
"""
# Integrate Yum with Salt
if 'SALT_RUNNING' not in os.environ:
with open(CK_PATH, 'w') as ck_fh:
ck_fh.write('{chksum} {mtime}\n'.format(chksum=_get_checksum(),... |
Parse the master. cf file. This file is essentially a whitespace - delimited columnar file. The columns are: service type private ( yes ) unpriv ( yes ) chroot ( yes ) wakeup ( never ) maxproc ( 100 ) command + args. | def _parse_master(path=MASTER_CF):
'''
Parse the master.cf file. This file is essentially a whitespace-delimited
columnar file. The columns are: service, type, private (yes), unpriv (yes),
chroot (yes), wakeup (never), maxproc (100), command + args.
This function parses out the columns, leaving emp... |
Set a single config value in the master. cf file. If the value does not already exist it will be appended to the end. | def set_master(service,
conn_type,
private='y',
unpriv='y',
chroot='y',
wakeup='n',
maxproc='100',
command='',
write_conf=True,
path=MASTER_CF):
'''
Set a single config value in... |
Format the given values into the style of line normally used in the master. cf file. | def _format_master(service,
conn_type,
private,
unpriv,
chroot,
wakeup,
maxproc,
command):
'''
Format the given values into the style of line normally used in the
master.cf fi... |
Parse files in the style of main. cf. This is not just a name = value file ; there are other rules: | def _parse_main(path=MAIN_CF):
'''
Parse files in the style of main.cf. This is not just a "name = value" file;
there are other rules:
* Comments start with #
* Any whitespace at the beginning of a line denotes that that line is a
continuation from the previous line.
* The whitespace ru... |
Set a single config value in the main. cf file. If the value does not already exist it will be appended to the end. | def set_main(key, value, path=MAIN_CF):
'''
Set a single config value in the main.cf file. If the value does not already
exist, it will be appended to the end.
CLI Example:
salt <minion> postfix.set_main mailq_path /usr/bin/mailq
'''
pairs, conf_list = _parse_main(path)
new_conf =... |
Write out configuration file. | def _write_conf(conf, path=MAIN_CF):
'''
Write out configuration file.
'''
with salt.utils.files.fopen(path, 'w') as fh_:
for line in conf:
line = salt.utils.stringutils.to_str(line)
if isinstance(line, dict):
fh_.write(' '.join(line))
else:
... |
Show contents of the mail queue | def show_queue():
'''
Show contents of the mail queue
CLI Example:
.. code-block:: bash
salt '*' postfix.show_queue
'''
cmd = 'mailq'
out = __salt__['cmd.run'](cmd).splitlines()
queue = []
queue_pattern = re.compile(r"(?P<queue_id>^[A-Z0-9]+)\s+(?P<size>\d+)\s(?P<timesta... |
Delete message ( s ) from the mail queue | def delete(queue_id):
'''
Delete message(s) from the mail queue
CLI Example:
.. code-block:: bash
salt '*' postfix.delete 5C33CA0DEA
salt '*' postfix.delete ALL
'''
ret = {'message': '',
'result': True
}
if not queue_id:
log.error('Require... |
Get collection options | def collection_get_options(collection_name, **kwargs):
'''
Get collection options
Additional parameters (kwargs) may be passed, they will be proxied to http.query
CLI Example:
.. code-block:: bash
salt '*' solrcloud.collection_get_options collection_name
'''
cluster = cluster_st... |
Change collection options | def collection_set_options(collection_name, options, **kwargs):
'''
Change collection options
Additional parameters (kwargs) may be passed, they will be proxied to http.query
Note that not every parameter can be changed after collection creation
CLI Example:
.. code-block:: bash
sal... |
Lists certificates in a keytool managed keystore. | def list(keystore, passphrase, alias=None, return_cert=False):
'''
Lists certificates in a keytool managed keystore.
:param keystore: The path to the keystore file to query
:param passphrase: The passphrase to use to decode the keystore
:param alias: (Optional) If found, displays details on only t... |
Adds certificates to an existing keystore or creates a new one if necesssary. | def add(name, keystore, passphrase, certificate, private_key=None):
'''
Adds certificates to an existing keystore or creates a new one if necesssary.
:param name: alias for the certificate
:param keystore: The path to the keystore file to query
:param passphrase: The passphrase to use to decode the... |
Removes a certificate from an existing keystore. Returns True if remove was successful otherwise False | def remove(name, keystore, passphrase):
'''
Removes a certificate from an existing keystore.
Returns True if remove was successful, otherwise False
:param name: alias for the certificate
:param keystore: The path to the keystore file to query
:param passphrase: The passphrase to use to decode t... |
Store information in a file. | def store(bank, key, data, cachedir):
'''
Store information in a file.
'''
base = os.path.join(cachedir, os.path.normpath(bank))
try:
os.makedirs(base)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise SaltCacheError(
'The cache directory, {0}... |
Fetch information from a file. | def fetch(bank, key, cachedir):
'''
Fetch information from a file.
'''
inkey = False
key_file = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key))
if not os.path.isfile(key_file):
# The bank includes the full filename, and the key is inside the file
key_file = os... |
Return the epoch of the mtime for this cache file | def updated(bank, key, cachedir):
'''
Return the epoch of the mtime for this cache file
'''
key_file = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key))
if not os.path.isfile(key_file):
log.warning('Cache file "%s" does not exist', key_file)
return None
try:
... |
Remove the key from the cache bank with all the key content. | def flush(bank, key=None, cachedir=None):
'''
Remove the key from the cache bank with all the key content.
'''
if cachedir is None:
cachedir = __cachedir()
try:
if key is None:
target = os.path.join(cachedir, os.path.normpath(bank))
if not os.path.isdir(targe... |
Return an iterable object containing all entries stored in the specified bank. | def list_(bank, cachedir):
'''
Return an iterable object containing all entries stored in the specified bank.
'''
base = os.path.join(cachedir, os.path.normpath(bank))
if not os.path.isdir(base):
return []
try:
items = os.listdir(base)
except OSError as exc:
raise Sal... |
Checks if the specified bank contains the specified key. | def contains(bank, key, cachedir):
'''
Checks if the specified bank contains the specified key.
'''
if key is None:
base = os.path.join(cachedir, os.path.normpath(bank))
return os.path.isdir(base)
else:
keyfile = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(k... |
Check that the key is found in the registry. This refers to keys and not value/ data pairs. To check value/ data pairs use value_exists | def key_exists(hive, key, use_32bit_registry=False):
'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs. To check value/data pairs, use ``value_exists``
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_r... |
Check that the value/ data pair is found in the registry. | def value_exists(hive, key, vname, use_32bit_registry=False):
'''
Check that the value/data pair is found in the registry.
.. version-added:: 2018.3.4
Args:
hive (str): The hive to connect to
key (str): The key to check in
vname (str): The name of the value/data pair you're ... |
Refresh the windows environment. | def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
Usage:
.. code-block:: python
... |
Enumerates the subkeys in a registry key or hive. | def list_keys(hive, key=None, use_32bit_registry=False):
'''
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
-... |
Enumerates the values in a registry key or hive. | def list_values(hive, key=None, use_32bit_registry=False, include_default=True):
'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER o... |
r Reads a registry value entry or the default value for a key. To read the default value don t pass vname | def read_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
... |
Sets a value in the registry. If vname is passed it will be the value for that value name otherwise it will be the default value for the specified key | def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it wil... |
Cast the vdata value to the appropriate data type for the registry type specified in vtype | def cast_vdata(vdata=None, vtype='REG_SZ'):
'''
Cast the ``vdata` value to the appropriate data type for the registry type
specified in ``vtype``
Args:
vdata (str, int, list, bytes): The data to cast
vtype (str):
The type of data to be written to the registry. Must be one ... |
.. versionadded:: 2015. 5. 4 | def delete_key_recursive(hive, key, use_32bit_registry=False):
'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
... |
Delete a registry value entry or the default value for a key. | def delete_value(hive, key, vname=None, use_32bit_registry=False):
'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or ... |
List all queued and running jobs or only those with an optional tag. | def atq(tag=None):
'''
List all queued and running jobs or only those with
an optional 'tag'.
CLI Example:
.. code-block:: bash
salt '*' at.atq
salt '*' at.atq [tag]
salt '*' at.atq [job number]
'''
jobs = []
res = __salt__['cmd.run_all']('atq')
if res['r... |
Remove jobs from the queue. | def atrm(*args):
'''
Remove jobs from the queue.
CLI Example:
.. code-block:: bash
salt '*' at.atrm <jobid> <jobid> .. <jobid>
salt '*' at.atrm all
salt '*' at.atrm all [tag]
'''
if not args:
return {'jobs': {'removed': [], 'tag': None}}
if args[0] == 'al... |
Add a job to the queue. | def at(*args, **kwargs): # pylint: disable=C0103
'''
Add a job to the queue.
The 'timespec' follows the format documented in the
at(1) manpage.
CLI Example:
.. code-block:: bash
salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>]
salt '*' at.at 12:05am '/sbin/reboot' ... |
Print the at ( 1 ) script that will run for the passed job id. This is mostly for debugging so the output will just be text. | def atc(jobid):
'''
Print the at(1) script that will run for the passed job
id. This is mostly for debugging so the output will
just be text.
CLI Example:
.. code-block:: bash
salt '*' at.atc <jobid>
'''
atjob_file = '/var/spool/cron/atjobs/{job}'.format(
job=jobid
... |
Return the properly formatted ssh value for the authorized encryption key type. ecdsa defaults to 256 bits must give full ecdsa enc schema string if using higher enc. If the type is not found raise CommandExecutionError. | def _refine_enc(enc):
'''
Return the properly formatted ssh value for the authorized encryption key
type. ecdsa defaults to 256 bits, must give full ecdsa enc schema string
if using higher enc. If the type is not found, raise CommandExecutionError.
'''
rsa = ['r', 'rsa', 'ssh-rsa']
dss = ['... |
Properly format user input. | def _format_auth_line(key, enc, comment, options):
'''
Properly format user input.
'''
line = ''
if options:
line += '{0} '.format(','.join(options))
line += '{0} {1} {2}\n'.format(enc, key, comment)
return line |
Expand the AuthorizedKeysFile expression. Defined in man sshd_config ( 5 ) | def _expand_authorized_keys_path(path, user, home):
'''
Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5)
'''
converted_path = ''
had_escape = False
for char in path:
if had_escape:
had_escape = False
if char == '%':
converted... |
Get absolute path to a user s ssh_config. | def _get_config_file(user, config):
'''
Get absolute path to a user's ssh_config.
'''
uinfo = __salt__['user.info'](user)
if not uinfo:
raise CommandExecutionError('User \'{0}\' does not exist'.format(user))
home = uinfo['home']
config = _expand_authorized_keys_path(config, user, hom... |
Replace an existing key | def _replace_auth_key(
user,
key,
enc='ssh-rsa',
comment='',
options=None,
config='.ssh/authorized_keys'):
'''
Replace an existing key
'''
auth_line = _format_auth_line(key, enc, comment, options or [])
lines = []
full = _get_config_file(user, co... |
Return a dict containing validated keys in the passed file | def _validate_keys(key_file, fingerprint_hash_type):
'''
Return a dict containing validated keys in the passed file
'''
ret = {}
linere = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
try:
with salt.utils.files.fopen(key_file, 'r') as _fh:
for line in _fh:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.