INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
r.. versionadded:: 2015. 5. 4
def delete_key_recursive(hive, key, use_32bit_registry=False): r''' .. 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 ...
r Delete a registry value entry or the default value for a key.
def delete_value(hive, key, vname=None, use_32bit_registry=False): r''' 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...
Import registry settings from a Windows REG file by invoking REG. EXE.
def import_file(source, use_32bit_registry=False): ''' Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``. .. versionadded:: 2018.3.0 Args: source (str): The full path of the ``REG`` file. This can be either a local file path or a URL type sup...
Execute a command and read the output as YAML
def ext_pillar(minion_id, pillar, # pylint: disable=W0613 use_grain=False, minion_ids=None, tag_match_key=None, tag_match_value='asis', tag_list_key=None, tag_list_sep=';'): ''' Execute a command and read t...
Return an existing set of certificates
def ext_pillar(minion_id, pillar, conf): ''' Return an existing set of certificates ''' cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR) ret = {} dns_names = cache.fetch('venafi/minions', minion_id) for dns_name in dns_names: data = cache.fetch('venafi/domains', dns_name) ...
Return the status for a service via s6 return pid if running
def status(name, sig=None): ''' Return the status for a service via s6, return pid if running CLI Example: .. code-block:: bash salt '*' s6.status <service name> ''' cmd = 's6-svstat {0}'.format(_service_path(name)) out = __salt__['cmd.run_stdout'](cmd) try: pid = re.s...
Return a list of all available services
def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' s6.get_all ''' if not SERVICE_DIR: raise CommandExecutionError("Could not find service directory.") service_list = [dirname for dirname in os.l...
Add a host object for the given mac.
def add_host(mac, name=None, ip=None, ddns=False, group=None, supersede_host=False): ''' Add a host object for the given mac. CLI Example: .. code-block:: bash salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1 Add ddns-hostname and a fixed-ip statements: .. code-b...
Delete the host with the given mac or name.
def delete_host(mac=None, name=None): ''' Delete the host with the given mac or name. CLI Examples: .. code-block:: bash salt dhcp-server omapi.delete_host name=host1 salt dhcp-server omapi.delete_host mac=ab:ab:ab:ab:ab:ab ''' if not (mac or name): raise TypeError('At...
Return the auth object
def _auth(): ''' Return the auth object ''' if 'auth' not in __context__: try: __context__['auth'] = salt.crypt.SAuth(__opts__) except SaltClientError: log.error('Could not authenticate with master.' 'Mine data will not be transmitted.') ...
Execute the configured functions and send the data back up to the master. The functions to be executed are merged from the master config pillar and minion config under the option mine_functions:
def update(clear=False, mine_functions=None): ''' Execute the configured functions and send the data back up to the master. The functions to be executed are merged from the master config, pillar and minion config under the option `mine_functions`: .. code-block:: yaml mine_functions: ...
Send a specific function to the mine.
def send(func, *args, **kwargs): ''' Send a specific function to the mine. CLI Example: .. code-block:: bash salt '*' mine.send network.ip_addrs eth0 salt '*' mine.send eth0_ip_addrs mine_function=network.ip_addrs eth0 ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) mi...
Get data from the mine based on the target function and tgt_type
def get(tgt, fun, tgt_type='glob', exclude_minion=False): ''' Get data from the mine based on the target, function and tgt_type Targets can be matched based on any standard matching system that can be matched on the master via these keywords: - glob - pcre - grain ...
Remove specific function contents of minion. Returns True on success.
def delete(fun): ''' Remove specific function contents of minion. Returns True on success. CLI Example: .. code-block:: bash salt '*' mine.delete 'network.interfaces' ''' if __opts__['file_client'] == 'local': data = __salt__['data.get']('mine_cache') if isinstance(dat...
.. versionchanged:: 2017. 7. 8 2018. 3. 3 When: conf_minion: docker. update_mine is set to False for a given minion no mine data will be populated for that minion and thus none will be returned for it... versionchanged:: 2019. 2. 0: conf_minion: docker. update_mine now defaults to False
def get_docker(interfaces=None, cidrs=None, with_container_id=False): ''' .. versionchanged:: 2017.7.8,2018.3.3 When :conf_minion:`docker.update_mine` is set to ``False`` for a given minion, no mine data will be populated for that minion, and thus none will be returned for it. .. ver...
List valid entries in mine configuration.
def valid(): ''' List valid entries in mine configuration. CLI Example: .. code-block:: bash salt '*' mine.valid ''' m_data = __salt__['config.merge']('mine_functions', {}) # If we don't have any mine functions configured, then we should just bail out if not m_data: re...
Return data to a Pg server
def returner(ret): ''' Return data to a Pg server ''' try: with _get_serv(ret, commit=True) as cur: sql = '''INSERT INTO salt_returns (fun, jid, return, id, success, full_ret, alter_time) VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))''' ...
Return event to Pg server
def event_return(events): ''' Return event to Pg server Requires that configuration be enabled via 'event_return' option in master config. ''' with _get_serv(events, commit=True) as cur: for event in events: tag = event.get('tag', '') data = event.get('data', '')...
Save the load to the specified jid id
def save_load(jid, load, minions=None): ''' Save the load to the specified jid id ''' with _get_serv(commit=True) as cur: try: cur.execute(PG_SAVE_LOAD_SQL, {'jid': jid, 'load': psycopg2.extras.Json(load)}) except psycopg2.IntegrityError: #...
Return the load data that marks a specified jid
def get_load(jid): ''' Return the load data that marks a specified jid ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT load FROM jids WHERE jid = %s;''' cur.execute(sql, (jid,)) data = cur.fetchone() if data: return data[0] return {}
Return the information returned when the specified job id was executed
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT id, full_ret FROM salt_returns WHERE jid = %s''' cur.execute(sql, (jid,)) data = cur.fetchall() ...
Return a dict of the last function called for all minions
def get_fun(fun): ''' Return a dict of the last function called for all minions ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT s.id,s.jid, s.full_ret FROM salt_returns s JOIN ( SELECT MAX(`jid`) as jid from salt_returns GROU...
Purge records from the returner tables.: param job_age_in_seconds: Purge jobs older than this: return:
def _purge_jobs(timestamp): ''' Purge records from the returner tables. :param job_age_in_seconds: Purge jobs older than this :return: ''' with _get_serv() as cursor: try: sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)' ...
Copy rows to a set of backup tables then purge rows.: param timestamp: Archive rows older than this timestamp: return:
def _archive_jobs(timestamp): ''' Copy rows to a set of backup tables, then purge rows. :param timestamp: Archive rows older than this timestamp :return: ''' source_tables = ['jids', 'salt_returns', 'salt_events'] with _get_serv() as cursor: ...
Called in the master s event loop every loop_interval. Archives and/ or deletes the events and job details from the database.: return:
def clean_old_jobs(): ''' Called in the master's event loop every loop_interval. Archives and/or deletes the events and job details from the database. :return: ''' if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0: try: with _get_serv() as cur: ...
Return information about the CPU.
def cpustats(): ''' Return information about the CPU. Returns dict: A dictionary containing information about the CPU stats CLI Example: .. code-block:: bash salt * status.cpustats ''' # Tries to gather information similar to that returned by a Linux machine # Avoid u...
Return information about physical and virtual memory on the system
def meminfo(): ''' Return information about physical and virtual memory on the system Returns: dict: A dictionary of information about memory on the system CLI Example: .. code-block:: bash salt * status.meminfo ''' # Get physical memory vm_total, vm_available, vm_per...
Return information about the virtual memory on the machine
def vmstats(): ''' Return information about the virtual memory on the machine Returns: dict: A dictionary of virtual memory stats CLI Example: .. code-block:: bash salt * status.vmstats ''' # Setup the SPI Structure spi = SYSTEM_PERFORMANCE_INFORMATION() retlen = ...
.. versionadded:: 2015. 8. 0
def diskusage(human_readable=False, path=None): ''' .. versionadded:: 2015.8.0 Return the disk usage for this minion human_readable : False If ``True``, usage will be in KB/MB/GB etc. CLI Example: .. code-block:: bash salt '*' status.diskusage path=c:/salt ''' if not...
Return the process data
def procs(count=False): ''' Return the process data count : False If ``True``, this function will simply return the number of processes. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' status.procs salt '*' status.procs count ''' wit...
.. versionadded:: 2015. 8. 0
def saltmem(human_readable=False): ''' .. versionadded:: 2015.8.0 Returns the amount of memory that salt is using human_readable : False return the value in a nicely formatted number CLI Example: .. code-block:: bash salt '*' status.saltmem salt '*' status.saltmem hu...
.. versionadded:: 2015. 8. 0
def uptime(human_readable=False): ''' .. versionadded:: 2015.8.0 Return the system uptime for the machine Args: human_readable (bool): Return uptime in human readable format if ``True``, otherwise return seconds. Default is ``False`` .. note:: ...
Return process information
def _get_process_info(proc): ''' Return process information ''' cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '') name = salt.utils.stringutils.to_unicode(proc.Name) info = dict( cmd=cmd, name=name, **_get_process_owner(proc) ) return info
.. versionadded:: 2015. 5. 0
def master(master=None, connected=True): ''' .. versionadded:: 2015.5.0 Fire an event if the minion gets disconnected from its master. This function is meant to be run via a scheduled job from the minion. If master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4 address. CLI ...
Verify the config file is present
def _check_config_exists(config_file=None): ''' Verify the config file is present ''' if config_file is None: config_file = _config_file() if not os.path.isfile(config_file): return False return True
Return True if jail exists False if not
def is_jail(name): ''' Return True if jail exists False if not CLI Example: .. code-block:: bash salt '*' poudriere.is_jail <jail name> ''' jails = list_jails() for jail in jails: if jail.split()[0] == name: return True return False
Make jail jname pkgng aware
def make_pkgng_aware(jname): ''' Make jail ``jname`` pkgng aware CLI Example: .. code-block:: bash salt '*' poudriere.make_pkgng_aware <jail name> ''' ret = {'changes': {}} cdir = _config_dir() # ensure cdir is there if not os.path.isdir(cdir): os.makedirs(cdir) ...
Returns a dict of poudriere main configuration definitions
def parse_config(config_file=None): ''' Returns a dict of poudriere main configuration definitions CLI Example: .. code-block:: bash salt '*' poudriere.parse_config ''' if config_file is None: config_file = _config_file() ret = {} if _check_config_exists(config_file): ...
Creates a new poudriere jail if one does not exist
def create_jail(name, arch, version="9.0-RELEASE"): ''' Creates a new poudriere jail if one does not exist *NOTE* creating a new jail will take some time the master is not hanging CLI Example: .. code-block:: bash salt '*' poudriere.create_jail 90amd64 amd64 ''' # Config file mus...
Run freebsd - update on name poudriere jail
def update_jail(name): ''' Run freebsd-update on `name` poudriere jail CLI Example: .. code-block:: bash salt '*' poudriere.update_jail freebsd:10:x86:64 ''' if is_jail(name): cmd = 'poudriere jail -u -j {0}'.format(name) ret = __salt__['cmd.run'](cmd) return r...
Deletes poudriere jail with name
def delete_jail(name): ''' Deletes poudriere jail with `name` CLI Example: .. code-block:: bash salt '*' poudriere.delete_jail 90amd64 ''' if is_jail(name): cmd = 'poudriere jail -d -j {0}'.format(name) __salt__['cmd.run'](cmd) # Make sure jail is gone ...
Updates the ports tree either the default or the ports_tree specified
def update_ports_tree(ports_tree): ''' Updates the ports tree, either the default or the `ports_tree` specified CLI Example: .. code-block:: bash salt '*' poudriere.update_ports_tree staging ''' _check_config_exists() if ports_tree: cmd = 'poudriere ports -u -p {0}'.format...
Run bulk build on poudriere server.
def bulk_build(jail, pkg_file, keep=False): ''' Run bulk build on poudriere server. Return number of pkg builds, failures, and errors, on error dump to CLI CLI Example: .. code-block:: bash salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list ''' # make sure `pkg f...
NILRT systems determine whether to reboot after various package operations including but not limited to kernel module installs/ removals by checking specific file md5sums & timestamps. These files are touched/ modified by the post - install/ post - remove functions of their respective packages.
def _update_nilrt_restart_state(): ''' NILRT systems determine whether to reboot after various package operations including but not limited to kernel module installs/removals by checking specific file md5sums & timestamps. These files are touched/modified by the post-install/post-remove functions of...
Return restartcheck result and append errors ( if any ) to errors
def _get_restartcheck_result(errors): ''' Return restartcheck result and append errors (if any) to ``errors`` ''' rs_result = __salt__['restartcheck.restartcheck'](verbose=False) if isinstance(rs_result, dict) and 'comment' in rs_result: errors.append(rs_result['comment']) return rs_resu...
Check restartcheck output to see if system/ service restarts were requested and take appropriate action.
def _process_restartcheck_result(rs_result, **kwargs): ''' Check restartcheck output to see if system/service restarts were requested and take appropriate action. ''' if 'No packages seem to need to be restarted' in rs_result: return reboot_required = False for rstr in rs_result: ...
Updates the opkg database to latest packages based upon repositories
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument ''' Updates the opkg database to latest packages based upon repositories Returns a dict, with the keys being package databases and the values being the result of the update attempt. Values can be one of the following: - `...
Builds a list of install commands to be executed in sequence in order to process each of the to_install to_downgrade and to_reinstall lists.
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall): ''' Builds a list of install commands to be executed in sequence in order to process each of the to_install, to_downgrade, and to_reinstall lists. ''' cmds = [] if to_install: cmd = copy.deepcopy(cmd_pre...
Parses the output of opkg install to determine what packages would have been installed by an operation run with the -- noaction flag.
def _parse_reported_packages_from_install_output(output): ''' Parses the output of "opkg install" to determine what packages would have been installed by an operation run with the --noaction flag. We are looking for lines like: Installing <package> (<version>) on <target> or Upgradi...
Executes a command for the install operation. If the command fails its error output will be appended to the errors list. If the command succeeds and parse_output is true updated packages will be appended to the parsed_packages dictionary.
def _execute_install_command(cmd, parse_output, errors, parsed_packages): ''' Executes a command for the install operation. If the command fails, its error output will be appended to the errors list. If the command succeeds and parse_output is true, updated packages will be appended to the parsed_pa...
Install the passed package add refresh = True to update the opkg database.
def install(name=None, refresh=False, pkgs=None, sources=None, reinstall=False, **kwargs): ''' Install the passed package, add refresh=True to update the opkg database. name The name of the package to be installed. Note that this parameter...
Parses the output of opkg remove to determine what packages would have been removed by an operation run with the -- noaction flag.
def _parse_reported_packages_from_remove_output(output): ''' Parses the output of "opkg remove" to determine what packages would have been removed by an operation run with the --noaction flag. We are looking for lines like Removing <package> (<version>) from <Target>... ''' reported_pkg...
Remove packages using opkg remove.
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument ''' Remove packages using ``opkg remove``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name``...
Upgrades all packages via opkg upgrade
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument ''' Upgrades all packages via ``opkg upgrade`` Returns a dictionary containing the changes: .. code-block:: python {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example...
Set package in hold state meaning it will not be upgraded.
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 ''' Set package in 'hold' state, meaning it will not be upgraded. name The name of the package, e.g., 'tmux' CLI Example: .. code-block:: bash salt '*' pkg.hold <package name> pkgs ...
View package state from the opkg database
def _get_state(pkg): ''' View package state from the opkg database Return the state of pkg ''' cmd = ['opkg', 'status'] cmd.append(pkg) out = __salt__['cmd.run'](cmd, python_shell=False) state_flag = '' for line in salt.utils.itertools.split(out, '\n'): if line.startswith('S...
Change package state on the opkg database
def _set_state(pkg, state): ''' Change package state on the opkg database The state can be any of: - hold - noprune - user - ok - installed - unpacked This command is commonly used to mark a specific package to be held from being upgraded, that is, to be kept at a ce...
List all available package upgrades.
def list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument ''' List all available package upgrades. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' ret = {} if salt.utils.data.is_true(refresh): refresh_db() cmd = ['opkg', 'list-upgr...
Helper function for _process_info_installed_output ()
def _convert_to_standard_attr(attr): ''' Helper function for _process_info_installed_output() Converts an opkg attribute name to a standard attribute name which is used across 'pkg' modules. ''' ret_attr = ATTR_MAP.get(attr, None) if ret_attr is None: # All others convert to lowerca...
Helper function for info_installed ()
def _process_info_installed_output(out, filter_attrs): ''' Helper function for info_installed() Processes stdout output from a single invocation of 'opkg status'. ''' ret = {} name = None attrs = {} attr = None for line in salt.utils.itertools.split(out, '\n'): if line ...
Return the information of the named package ( s ) installed on the system.
def info_installed(*names, **kwargs): ''' Return the information of the named package(s), installed on the system. .. versionadded:: 2017.7.0 :param names: Names of the packages to get information about. If none are specified, will return information for all installed packages. :p...
Do a cmp - style comparison on two packages. Return - 1 if pkg1 < pkg2 0 if pkg1 == pkg2 and 1 if pkg1 > pkg2. Return None if there was a problem making the comparison.
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument ''' Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem making the comparison. ignore_epoch : False Set ...
Set the option to repo
def _set_repo_option(repo, option): ''' Set the option to repo ''' if not option: return opt = option.split('=') if len(opt) != 2: return if opt[0] == 'trusted': repo['trusted'] = opt[1] == 'yes' else: repo[opt[0]] = opt[1]
Set the options to the repo.
def _set_repo_options(repo, options): ''' Set the options to the repo. ''' delimiters = "[", "]" pattern = '|'.join(map(re.escape, delimiters)) for option in options: splitted = re.split(pattern, option) for opt in splitted: _set_repo_option(repo, opt)
Create repo
def _create_repo(line, filename): ''' Create repo ''' repo = {} if line.startswith('#'): repo['enabled'] = False line = line[1:] else: repo['enabled'] = True cols = salt.utils.args.shlex_split(line.strip()) repo['compressed'] = not cols[0] in 'src' repo['name'...
Read repos from configuration file
def _read_repos(conf_file, repos, filename, regex): ''' Read repos from configuration file ''' for line in conf_file: line = salt.utils.stringutils.to_unicode(line) if not regex.search(line): continue repo = _create_repo(line, filename) # do not store duplica...
Lists all repos on/ etc/ opkg/ *. conf
def list_repos(**kwargs): # pylint: disable=unused-argument ''' Lists all repos on ``/etc/opkg/*.conf`` CLI Example: .. code-block:: bash salt '*' pkg.list_repos ''' repos = {} regex = re.compile(REPO_REGEXP) for filename in os.listdir(OPKG_CONFDIR): if not filename.en...
Display a repo from the/ etc/ opkg/ *. conf
def get_repo(repo, **kwargs): # pylint: disable=unused-argument ''' Display a repo from the ``/etc/opkg/*.conf`` CLI Examples: .. code-block:: bash salt '*' pkg.get_repo repo ''' repos = list_repos() if repos: for source in six.itervalues(repos): for sub in s...
Remove a repo from filepath
def _del_repo_from_file(repo, filepath): ''' Remove a repo from filepath ''' with salt.utils.files.fopen(filepath) as fhandle: output = [] regex = re.compile(REPO_REGEXP) for line in fhandle: line = salt.utils.stringutils.to_unicode(line) if regex.search(l...
Set trusted option to repo if needed
def _set_trusted_option_if_needed(repostr, trusted): ''' Set trusted option to repo if needed ''' if trusted is True: repostr += ' [trusted=yes]' elif trusted is False: repostr += ' [trusted=no]' return repostr
Add a new repo entry
def _add_new_repo(repo, properties): ''' Add a new repo entry ''' repostr = '# ' if not properties.get('enabled') else '' repostr += 'src/gz ' if properties.get('compressed') else 'src ' if ' ' in repo: repostr += '"' + repo + '" ' else: repostr += repo + ' ' repostr += p...
Replace a repo entry in filepath with repostr
def _mod_repo_in_file(repo, repostr, filepath): ''' Replace a repo entry in filepath with repostr ''' with salt.utils.files.fopen(filepath) as fhandle: output = [] for line in fhandle: cols = salt.utils.args.shlex_split( salt.utils.stringutils.to_unicode(line)...
Delete a repo from/ etc/ opkg/ *. conf
def del_repo(repo, **kwargs): # pylint: disable=unused-argument ''' Delete a repo from ``/etc/opkg/*.conf`` If the file does not contain any other repo configuration, the file itself will be deleted. CLI Examples: .. code-block:: bash salt '*' pkg.del_repo repo ''' refresh =...
Modify one or more values for a repo. If the repo does not exist it will be created so long as uri is defined.
def mod_repo(repo, **kwargs): ''' Modify one or more values for a repo. If the repo does not exist, it will be created, so long as uri is defined. The following options are available to modify a repo definition: repo alias by which opkg refers to the repo. uri the URI to the r...
List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system s package database ( not generally recommended ).
def file_list(*packages, **kwargs): # pylint: disable=unused-argument ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' ...
List the files that belong to a package grouped by package. Not specifying any packages will return a list of _every_ file on the system s package database ( not generally recommended ).
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument ''' List the files that belong to a package, grouped by package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bas...
Return the name of the package that owns the file. Multiple file paths can be passed. Like: mod: pkg. version <salt. modules. opkg. version if a single path is passed a string will be returned and if multiple paths are passed a dictionary of file/ package name pairs will be returned.
def owner(*paths, **kwargs): # pylint: disable=unused-argument ''' Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dic...
send a email to inform user of account creation
def _send_email(name, email): "send a email to inform user of account creation" config = __salt__['config.option']('splunk') email_object = config.get('email') if email_object: cc = email_object.get('cc') subject = email_object.get('subject') message = email_object.get('message')...
Return the splunk client cached into __context__ for performance
def _get_splunk(profile): ''' Return the splunk client, cached into __context__ for performance ''' config = __salt__['config.option'](profile) key = "splunk.{0}:{1}:{2}:{3}".format( config.get('host'), config.get('port'), config.get('username'), config.get('password...
List all users in the splunk DB
def list_users(profile="splunk"): ''' List all users in the splunk DB CLI Example: salt myminion splunk.list_users ''' config = __salt__['config.option'](profile) key = "splunk.users.{0}".format( config.get('host') ) if key not in __context__: _populate_cache(...
Get a splunk user by name/ email
def get_user(email, profile="splunk", **kwargs): ''' Get a splunk user by name/email CLI Example: salt myminion splunk.get_user 'user@example.com' user_details=false salt myminion splunk.get_user 'user@example.com' user_details=true ''' user_map = list_users(profile) user_foun...
create a splunk user by name/ email
def create_user(email, profile="splunk", **kwargs): ''' create a splunk user by name/email CLI Example: salt myminion splunk.create_user user@example.com roles=['user'] realname="Test User" name=testuser ''' client = _get_splunk(profile) email = email.lower() user = list_users(p...
Create a splunk user by email
def update_user(email, profile="splunk", **kwargs): ''' Create a splunk user by email CLI Example: salt myminion splunk.update_user example@domain.com roles=['user'] realname="Test User" ''' client = _get_splunk(profile) email = email.lower() user = list_users(profile).get(email...
Delete a splunk user by email
def delete_user(email, profile="splunk"): ''' Delete a splunk user by email CLI Example: salt myminion splunk_user.delete 'user@example.com' ''' client = _get_splunk(profile) user = list_users(profile).get(email) if user: try: client.users.delete(user.name) ...
Return the default shell to use on this system
def shell(): ''' Return the default shell to use on this system ''' # Provides: # shell if salt.utils.platform.is_windows(): env_var = 'COMSPEC' default = r'C:\Windows\system32\cmd.exe' else: env_var = 'SHELL' default = '/bin/sh' return {'shell': os.env...
Return the grains set in the grains file
def config(): ''' Return the grains set in the grains file ''' if 'conf_file' not in __opts__: return {} if os.path.isdir(__opts__['conf_file']): if salt.utils.platform.is_proxy(): gfn = os.path.join( __opts__['conf_file'], 'proxy.d...
Get the output volume ( range 0 to 100 )
def get_output_volume(): ''' Get the output volume (range 0 to 100) CLI Example: .. code-block:: bash salt '*' desktop.get_output_volume ''' cmd = 'osascript -e "get output volume of (get volume settings)"' call = __salt__['cmd.run_all']( cmd, output_loglevel='debu...
Set the volume of sound.
def set_output_volume(volume): ''' Set the volume of sound. volume The level of volume. Can range from 0 to 100. CLI Example: .. code-block:: bash salt '*' desktop.set_output_volume <volume> ''' cmd = 'osascript -e "set volume output volume {0}"'.format(volume) call =...
Launch the screensaver.
def screensaver(): ''' Launch the screensaver. CLI Example: .. code-block:: bash salt '*' desktop.screensaver ''' cmd = 'open /System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/ScreenSaverEngine.app' call = __salt__['cmd.run_all']( cmd, output_lo...
Say some words.
def say(*words): ''' Say some words. words The words to execute the say command with. CLI Example: .. code-block:: bash salt '*' desktop.say <word0> <word1> ... <wordN> ''' cmd = 'say {0}'.format(' '.join(words)) call = __salt__['cmd.run_all']( cmd, ou...
Check the output of the cmd. run_all function call.
def _check_cmd(call): ''' Check the output of the cmd.run_all function call. ''' if call['retcode'] != 0: comment = '' std_err = call.get('stderr') std_out = call.get('stdout') if std_err: comment += std_err if std_out: comment += std_out ...
r Create a list of Counter objects to be used in the pdh query
def build_counter_list(counter_list): r''' Create a list of Counter objects to be used in the pdh query Args: counter_list (list): A list of tuples containing counter information. Each tuple should contain the object, instance, and counter name. For example, to g...
Get the values for all counters available to a Counter object
def get_all_counters(obj, instance_list=None): ''' Get the values for all counters available to a Counter object Args: obj (str): The name of the counter object. You can get a list of valid names using the ``list_objects`` function instance_list (list): ...
Get the values for the passes list of counters
def get_counters(counter_list): ''' Get the values for the passes list of counters Args: counter_list (list): A list of counters to lookup Returns: dict: A dictionary of counters and their values ''' if not isinstance(counter_list, list): raise CommandExecut...
r Makes a fully resolved counter path. Counter names are formatted like this:
def build_counter(obj, instance, instance_index, counter): r''' Makes a fully resolved counter path. Counter names are formatted like this: ``\Processor(*)\% Processor Time`` The above breaks down like this: obj = 'Processor' instance = '*' ...
Add the current path to the query
def add_to_query(self, query): ''' Add the current path to the query Args: query (obj): The handle to the query to add the counter ''' self.handle = win32pdh.AddCounter(query, self.path)
Get information about the counter
def get_info(self): ''' Get information about the counter .. note:: GetCounterInfo sometimes crashes in the wrapper code. Fewer crashes if this is called after sampling data. ''' if not self.info: ci = win32pdh.GetCounterInfo(self.handle, 0) ...
Return the counter value
def value(self): ''' Return the counter value Returns: long: The counter value ''' (counter_type, value) = win32pdh.GetFormattedCounterValue( self.handle, win32pdh.PDH_FMT_DOUBLE) self.type = counter_type return value
Returns the names of the flags that are set in the Type field
def type_string(self): ''' Returns the names of the flags that are set in the Type field It can be used to format the counter. ''' type = self.get_info()['type'] type_list = [] for member in dir(self): if member.startswith("PERF_"): bi...
Add the directory to the system PATH at index location
def exists(name, index=None): ''' Add the directory to the system PATH at index location index Position where the directory should be placed in the PATH. This is 0-indexed, so 0 means to prepend at the very start of the PATH. .. note:: If the index is not specified, and...