docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Set the mode of a file This just calls get_mode, which returns None because we don't use mode on Windows Args: path: The path to the file or directory mode: The mode (not used) Returns: None CLI Example: .. code-block:: bash salt '*' file.set_mode /etc/passw...
def set_mode(path, mode): func_name = '{0}.set_mode'.format(__virtualname__) if __opts__.get('fun', '') == func_name: log.info('The function %s should not be used on Windows systems; ' 'see function docs for details. The value returned is ' 'always None. Use set_pe...
69,308
Remove the named file or directory Args: path (str): The path to the file or directory to remove. force (bool): Remove even if marked Read-Only. Default is False Returns: bool: True if successful, False if unsuccessful CLI Example: .. code-block:: bash salt '*' file....
def remove(path, force=False): # This must be a recursive function in windows to properly deal with # Symlinks. The shutil.rmtree function will remove the contents of # the Symlink source in windows. path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError...
69,309
Check if the path is a symlink This is only supported on Windows Vista or later. Inline with Unix behavior, this function will raise an error if the path is not a symlink, however, the error raised will be a SaltInvocationError, not an OSError. Args: path (str): The path to a file or dire...
def is_link(path): if sys.getwindowsversion().major < 6: raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.') try: return salt.utils.path.islink(path) except Exception as exc: raise CommandExecutionError(exc)
69,311
Return the path that a symlink points to This is only supported on Windows Vista or later. Inline with Unix behavior, this function will raise an error if the path is not a symlink, however, the error raised will be a SaltInvocationError, not an OSError. Args: path (str): The path to the ...
def readlink(path): if sys.getwindowsversion().major < 6: raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.') try: return salt.utils.path.readlink(path) except OSError as exc: if exc.errno == errno.EINVAL: raise CommandExecutionError(...
69,312
Determine if a package or runtime is installed. Args: name (str): The name of the package or the runtime. Returns: bool: True if the specified package or runtime is installed. CLI Example: .. code-block:: bash salt '*' flatpak.is_installed org.gimp.GIMP
def is_installed(name): out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' info ' + name) if out['retcode'] and out['stderr']: return False else: return True
69,378
Uninstall the specified package. Args: pkg (str): The package name. Returns: dict: The ``result`` and ``output``. CLI Example: .. code-block:: bash salt '*' flatpak.uninstall org.gimp.GIMP
def uninstall(pkg): ret = {'result': None, 'output': ''} out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' uninstall ' + pkg) if out['retcode'] and out['stderr']: ret['stderr'] = out['stderr'].strip() ret['result'] = False else: ret['stdout'] = out['stdout'].strip() ...
69,379
Adds a new location to install flatpak packages from. Args: name (str): The repository's name. location (str): The location of the repository. Returns: dict: The ``result`` and ``output``. CLI Example: .. code-block:: bash salt '*' flatpak.add_remote flathub https://...
def add_remote(name, location): ret = {'result': None, 'output': ''} out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' remote-add ' + name + ' ' + location) if out['retcode'] and out['stderr']: ret['stderr'] = out['stderr'].strip() ret['result'] = False else: ret['stdou...
69,380
Determines if a remote exists. Args: remote (str): The remote's name. Returns: bool: True if the remote has already been added. CLI Example: .. code-block:: bash salt '*' flatpak.is_remote_added flathub
def is_remote_added(remote): out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' remotes') lines = out.splitlines() for item in lines: i = re.split(r'\t+', item.rstrip('\t')) if i[0] == remote: return True return False
69,381
Detect a file's encoding using the following: - Check for Byte Order Marks (BOM) - Check for UTF-8 Markers - Check System Encoding - Check for ascii Args: path (str): The path to the file to check Returns: str: The encoding of the file Raises: CommandExecutionErro...
def get_encoding(path): def check_ascii(_data): # If all characters can be decoded to ASCII, then it's ASCII try: _data.decode('ASCII') log.debug('Found ASCII') except UnicodeDecodeError: return False else: return True def che...
69,938
Helper function for instantiating a Flags object Args: instantiated (bool): True to return an instantiated object, False to return the object definition. Use False if inherited by another class. Default is True. Returns: object: An instance of the Flags obj...
def flags(instantiated=True): if not HAS_WIN32: return class Flags(object): # Flag Dicts ace_perms = { 'file': { 'basic': { 0x1f01ff: 'Full control', 0x1301bf: 'Modify', 0x1201bf: 'Read...
69,987
Helper function for instantiating a Dacl class. Args: obj_name (str): The full path to the object. If None, a blank DACL will be created. Default is None. obj_type (str): The type of object. Default is 'File' Returns: object: An instantiated Dacl o...
def dacl(obj_name=None, obj_type='file'): if not HAS_WIN32: return class Dacl(flags(False)): def __init__(self, obj_name=None, obj_type='file'): # Validate obj_type if obj_type.lower() not in self.obj_type: raise SaltInvocation...
69,988
Converts a username to a sid, or verifies a sid. Required for working with the DACL. Args: principal(str): The principal to lookup the sid. Can be a sid or a username. Returns: PySID Object: A sid Usage: .. code-block:: python # Get a user's sid salt...
def get_sid(principal): # If None is passed, use the Universal Well-known SID "Null SID" if principal is None: principal = 'NULL SID' # Test if the user passed a sid or a name try: sid = salt.utils.win_functions.get_sid_from_name(principal) except CommandExecutionError: ...
69,989
Converts a PySID object to a string SID. Args: principal(str): The principal to lookup the sid. Must be a PySID object. Returns: str: A string sid Usage: .. code-block:: python # Get a PySID object py_sid = salt.utils.win_dacl.get_sid('jsnuffy') ...
def get_sid_string(principal): # If None is passed, use the Universal Well-known SID "Null SID" if principal is None: principal = 'NULL SID' try: return win32security.ConvertSidToStringSid(principal) except TypeError: # Not a PySID object principal = get_sid(princip...
69,990
.. versionadded:: 2015.5.0 Enable firewall profile Args: profile (Optional[str]): The name of the profile to enable. Default is ``allprofiles``. Valid options are: - allprofiles - domainprofile - privateprofile - publicprofile Returns: ...
def enable(profile='allprofiles'): cmd = ['netsh', 'advfirewall', 'set', profile, 'state', 'on'] ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) return True
70,384
.. versionadded:: 2015.5.0 Display all matching rules as specified by name Args: name (Optional[str]): The full name of the rule. ``all`` will return all rules. Default is ``all`` Returns: dict: A dictionary of all rules or rules that match the name exactly Raises: ...
def get_rule(name='all'): cmd = ['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name={0}'.format(name)] ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) return {name: ret['stdout'...
70,385
Add a beacon on the minion Args: name (str): Name of the beacon to configure beacon_data (dict): Dictionary or list containing configuration for beacon. Returns: dict: Boolean and status message on success or failure of add. CLI Example: .. code-bloc...
def add(name, beacon_data, **kwargs): ret = {'comment': 'Failed to add beacon {0}.'.format(name), 'result': False} if name in list_(return_yaml=False, **kwargs): ret['comment'] = 'Beacon {0} is already configured.'.format(name) return ret # Check to see if a beacon_module i...
71,160
Modify an existing beacon. Args: name (str): Name of the beacon to configure. beacon_data (dict): Dictionary or list containing updated configuration for beacon. Returns: dict: Boolean and status message on success or failure of modify. CLI Example: ...
def modify(name, beacon_data, **kwargs): ret = {'comment': '', 'result': True} current_beacons = list_(return_yaml=False, **kwargs) if name not in current_beacons: ret['comment'] = 'Beacon {0} is not configured.'.format(name) return ret if 'test' in kwargs and kwargs['...
71,161
Enable a beacon on the minion. Args: name (str): Name of the beacon to enable. Returns: dict: Boolean and status message on success or failure of enable. CLI Example: .. code-block:: bash salt '*' beacons.enable_beacon ps
def enable_beacon(name, **kwargs): ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Beacon name is required.' ret['result'] = False return ret if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Beacon {0} would be enabled.'.format...
71,164
Helper function for running the auditpol command Args: cmd (str): the auditpol command to run Returns: list: A list containing each line of the return (splitlines) Raises: CommandExecutionError: If the command encounters an error
def _auditpol_cmd(cmd): ret = salt.modules.cmdmod.run_all(cmd='auditpol {0}'.format(cmd), python_shell=True) if ret['retcode'] == 0: return ret['stdout'].splitlines() msg = 'Error executing auditpol command: {0}\n'.format(cmd) msg += '\n'.join(ret['std...
71,249
Is the passed user a member of the Administrators group Args: name (str): The name to check Returns: bool: True if user is a member of the Administrators group, False otherwise
def is_admin(name): groups = get_user_groups(name, True) for group in groups: if group in ('S-1-5-32-544', 'S-1-5-18'): return True return False
71,599
Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids
def get_user_groups(name, sid=False): if name == 'SYSTEM': # 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'. groups = [name] else: groups = win32net.NetUserGetLocalGroups(None, name) if not sid: return groups ret_groups = set() for group in ...
71,600
This is a tool for getting a sid from a name. The name can be any object. Usually a user or a group Args: name (str): The name of the user or group for which to get the sid Returns: str: The corresponding SID
def get_sid_from_name(name): # If None is passed, use the Universal Well-known SID "Null SID" if name is None: name = 'NULL SID' try: sid = win32security.LookupAccountName(None, name)[0] except pywintypes.error as exc: raise CommandExecutionError( 'User {0} not ...
71,601
Gets the user executing the process Args: with_domain (bool): ``True`` will prepend the user name with the machine name or domain separated by a backslash Returns: str: The user name
def get_current_user(with_domain=True): try: user_name = win32api.GetUserNameEx(win32api.NameSamCompatible) if user_name[-1] == '$': # Make the system account easier to identify. # Fetch sid so as to handle other language than english test_user = win32api.Get...
71,602
Converts a compressed GUID (SQUID) back into a GUID Args: squid (str): A valid compressed GUID Returns: str: A valid GUID
def squid_to_guid(squid): squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$') squid_match = squid_pattern.match(squid) guid = '' if squid_match is not None: guid = '{' + \ squid_match.group(1)[::-1]+'-' + \ squ...
71,609
Ensures that the named port exists on bridge, eventually creates it. Args: name: The name of the port. bridge: The name of the bridge. tunnel_type: Optional type of interface to create, currently supports: vlan, vxlan and gre. id: Optional tunnel's key. remote: Remote endpoi...
def present(name, bridge, tunnel_type=None, id=None, remote=None, dst_port=None, internal=False): ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} tunnel_types = ('vlan', 'vxlan', 'gre') if tunnel_type and tunnel_type not in tunnel_types: raise TypeError('The optional type a...
71,751
Ensures that the named port exists on bridge, eventually deletes it. If bridge is not set, port is removed from whatever bridge contains it. Args: name: The name of the port. bridge: The name of the bridge.
def absent(name, bridge=None): ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} bridge_exists = False if bridge: bridge_exists = __salt__['openvswitch.bridge_exists'](bridge) if bridge_exists: port_list = __salt__['openvswitch.port_list'](bridge) e...
71,752
Gets all properties for all profiles in the specified store Args: store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` R...
def get_all_profiles(store='local'): return { 'Domain Profile': get_all_settings(profile='domain', store=store), 'Private Profile': get_all_settings(profile='private', store=store), 'Public Profile': get_all_settings(profile='public', store=store) }
72,097
r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted pat...
def _cmd_quote(cmd): r # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # ...
72,585
Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name>
def available(name): for service in get_all(): if name.lower() == service.lower(): return True return False
72,587
Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bas...
def info(name): try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32servi...
72,591
r''' Check that the key is found in the registry. This refers to keys and not value/data pairs. Args: hive (str): The hive to connect to key (str): The key to check use_32bit_registry (bool): Look in the 32bit portion of the registry Returns: bool: True if exists, ot...
def key_exists(hive, key, use_32bit_registry=False): r return __utils__['reg.key_exists'](hive=hive, key=key, use_32bit_registry=use_32bit_registry)
72,850
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): A list of instances to return. Use this to narrow down the...
def get_all_counters(obj, instance_list=None): counters, instances_avail = win32pdh.EnumObjectItems(None, None, obj, -1, 0) if instance_list is None: instance_list = instances_avail if not isinstance(instance_list, list): instance_list = [instance_list] counter_list = [] for ...
72,958
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
def get_counters(counter_list): if not isinstance(counter_list, list): raise CommandExecutionError('counter_list must be a list of tuples') try: # Start a Query instances query = win32pdh.OpenQuery() # Build the counters counters = build_counter_list(counter_list) ...
72,959
Add the current path to the query Args: query (obj): The handle to the query to add the counter
def add_to_query(self, query): self.handle = win32pdh.AddCounter(query, self.path)
72,962
Check whether or not an upgrade is available for a given package Args: name (str): The name of a single package Kwargs: refresh (bool): Refresh package metadata. Default ``True`` saltenv (str): The salt environment. Default ``base`` Returns: bool: True if new version avail...
def upgrade_available(name, **kwargs): saltenv = kwargs.get('saltenv', 'base') # Refresh before looking for the latest version available, # same default as latest_version refresh = salt.utils.data.is_true(kwargs.get('refresh', True)) # if latest_version returns blank, the latest version is alr...
73,155
List all available package upgrades on this system Args: refresh (bool): Refresh package metadata. Default ``True`` Kwargs: saltenv (str): Salt environment. Default ``base`` Returns: dict: A dictionary of packages with available upgrades CLI Example: .. code-block:: bash...
def list_upgrades(refresh=True, **kwargs): saltenv = kwargs.get('saltenv', 'base') refresh = salt.utils.data.is_true(refresh) _refresh_db_conditional(saltenv, force=refresh) installed_pkgs = list_pkgs(refresh=False, saltenv=saltenv) available_pkgs = get_repo_data(saltenv).get('repo') pkgs ...
73,156
Returns the existing package metadata db. Will create it, if it does not exist, however will not refresh it. Args: saltenv (str): Salt environment. Default ``base`` Returns: dict: A dict containing contents of metadata db. CLI Example: .. code-block:: bash salt '*' pkg.g...
def get_repo_data(saltenv='base'): # we only call refresh_db if it does not exist, as we want to return # the existing data even if its old, other parts of the code call this, # but they will call refresh if they need too. repo_details = _get_repo_details(saltenv) if repo_details.winrepo_age =...
73,171
Compare software package versions Args: ver1 (str): A software version to compare oper (str): The operand to use to compare ver2 (str): A software version to compare Returns: bool: True if the comparison is valid, otherwise False CLI Example: .. code-block:: bash ...
def compare_versions(ver1='', oper='==', ver2=''): if not ver1: raise SaltInvocationError('compare_version, ver1 is blank') if not ver2: raise SaltInvocationError('compare_version, ver2 is blank') # Support version being the special meaning of 'latest' if ver1 == 'latest': ...
73,174
Get the Advanced Auditing policy as configured in ``C:\\Windows\\Security\\Audit\\audit.csv`` Args: option (str): The name of the setting as it appears in audit.csv Returns: bool: ``True`` if successful, otherwise ``False``
def _findOptionValueAdvAudit(option): if 'lgpo.adv_audit_data' not in __context__: system_root = os.environ.get('SystemRoot', 'C:\\Windows') f_audit = os.path.join(system_root, 'security', 'audit', 'audit.csv') f_audit_gpo = os.path.join(system_root, 'System32', 'GroupPolicy', ...
73,201
Helper function that sets the Advanced Audit settings in the two .csv files on Windows. Those files are located at: C:\\Windows\\Security\\Audit\\audit.csv C:\\Windows\\System32\\GroupPolicy\\Machine\\Microsoft\\Windows NT\\Audit\\audit.csv Args: option (str): The name of the option to set ...
def _set_audit_file_data(option, value): # Set up some paths here system_root = os.environ.get('SystemRoot', 'C:\\Windows') f_audit = os.path.join(system_root, 'security', 'audit', 'audit.csv') f_audit_gpo = os.path.join(system_root, 'System32', 'GroupPolicy', 'Machin...
73,202
Helper function that updates the current applied settings to match what has just been set in the audit.csv files. We're doing it this way instead of running `gpupdate` Args: option (str): The name of the option to set value (str): The value to set. ['None', '0', '1', '2', '3'] Returns:...
def _set_auditpol_data(option, value): auditpol_values = {'None': 'No Auditing', '0': 'No Auditing', '1': 'Success', '2': 'Failure', '3': 'Success and Failure'} defaults = _get_audit_defaults(option) return __ut...
73,203
Export an image description for Kiwi. Parameters: * **local**: Specifies True or False if the export has to be in the local file. Default: False. * **path**: If `local=True`, then specifies the path where file with the Kiwi description is written. Default: `/tmp`. CLI Example: .....
def export(local=False, path="/tmp", format='qcow2'): if getpass.getuser() != 'root': raise CommandExecutionError('In order to export system, the minion should run as "root".') try: description = _("query").Query('all', cachedir=__opts__['cachedir'])() return _("collector").Inspecto...
73,374
Create the salt proxy file and start the proxy process if required Parameters: name: The name of this state proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started Exam...
def configure_proxy(name, proxyname='p8000', start=True): ret = __salt__['salt_proxy.configure_proxy'](proxyname, start=start) ret.update({ 'name': name, 'comment': '{0} config messages'.format(name) }) return ret
73,380
Install a pkg file Args: pkg (str): The package to install target (str): The target in which to install the package to store (bool): Should the package be installed as if it was from the store? allow_untrusted (bool): Allow the installation of untrusted package...
def install(pkg, target='LocalSystem', store=False, allow_untrusted=False): if '*.' not in pkg: # If we use wildcards, we cannot use quotes pkg = _quote(pkg) target = _quote(target) cmd = 'installer -pkg {0} -target {1}'.format(pkg, target) if store: cmd += ' -store' i...
73,573
Install an app file by moving it into the specified Applications directory Args: app (str): The location of the .app file target (str): The target in which to install the package to Default is ''/Applications/'' Returns: str: The results of the rsync command ...
def install_app(app, target='/Applications/'): if target[-4:] != '.app': if app[-1:] == '/': base_app = os.path.basename(app[:-1]) else: base_app = os.path.basename(app) target = os.path.join(target, base_app) if not app[-1] == '/': app += '/' ...
73,574
Attempt to mount a dmg file to a temporary location and return the location of the pkg file inside Args: dmg (str): The location of the dmg file to mount Returns: tuple: Tuple containing the results of the command along with the mount point CLI Example: .. code-blo...
def mount(dmg): temp_dir = __salt__['temp.dir'](prefix='dmg-') cmd = 'hdiutil attach -readonly -nobrowse -mountpoint {0} "{1}"'.format(temp_dir, dmg) return __salt__['cmd.run'](cmd), temp_dir
73,575
Attempt to get the package ID from a .pkg file Args: pkg (str): The location of the pkg file Returns: list: List of all of the package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_pkg_id /tmp/test.pkg
def get_pkg_id(pkg): pkg = _quote(pkg) package_ids = [] # Create temp directory temp_dir = __salt__['temp.dir'](prefix='pkg-') try: # List all of the PackageInfo files cmd = 'xar -t -f {0} | grep PackageInfo'.format(pkg) out = __salt__['cmd.run'](cmd, python_shell=True...
73,576
Attempt to get the package IDs from a mounted .mpkg file Args: mpkg (str): The location of the mounted mpkg file Returns: list: List of package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_mpkg_ids /dev/disk2
def get_mpkg_ids(mpkg): mpkg = _quote(mpkg) package_infos = [] base_path = os.path.dirname(mpkg) # List all of the .pkg files cmd = 'find {0} -name *.pkg'.format(base_path) out = __salt__['cmd.run'](cmd, python_shell=True) pkg_files = out.split('\n') for p in pkg_files: pa...
73,577
Ensures that the specified columns of the named record have the specified values. Args: name: The name of the record. table: The name of the table to which the record belongs. data: Dictionary containing a mapping from column names to the desired values. Columns that exist, ...
def managed(name, table, data, record=None): ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if record is None: record = name current_data = { column: __salt__['openvswitch.db_get'](table, record, column) for column in data } # Comment and change mes...
73,726
Activates the firmware backup image. CLI Example: Args: reset(bool): Reset the CIMC device on activate. .. code-block:: bash salt '*' cimc.activate_backup_image salt '*' cimc.activate_backup_image reset=True
def activate_backup_image(reset=False): dn = "sys/rack-unit-1/mgmt/fw-boot-def/bootunit-combined" r = "no" if reset is True: r = "yes" inconfig = .format(r) ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False) return ret
73,772
Create a CIMC user with username and password. Args: uid(int): The user ID slot to create the user account in. username(str): The name of the user. password(str): The clear text password of the user. priv(str): The privilege level of the user. CLI Example: .. code-block...
def create_user(uid=None, username=None, password=None, priv=None): if not uid: raise salt.exceptions.CommandExecutionError("The user ID must be specified.") if not username: raise salt.exceptions.CommandExecutionError("The username must be specified.") if not password: raise...
73,773
Sets the hostname on the server. .. versionadded:: 2019.2.0 Args: hostname(str): The new hostname to set. CLI Example: .. code-block:: bash salt '*' cimc.set_hostname foobar
def set_hostname(hostname=None): if not hostname: raise salt.exceptions.CommandExecutionError("Hostname option must be provided.") dn = "sys/rack-unit-1/mgmt/if-1" inconfig = .format(hostname) ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False) try: if ret['outConf...
73,775
Sets the logging levels of the CIMC devices. The logging levels must match the following options: emergency, alert, critical, error, warning, notice, informational, debug. .. versionadded:: 2019.2.0 Args: remote(str): The logging level for SYSLOG logs. local(str): The logging level fo...
def set_logging_levels(remote=None, local=None): logging_options = ['emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'informational', ...
73,776
Set the SYSLOG server on the host. Args: server(str): The hostname or IP address of the SYSLOG server. type(str): Specifies the type of SYSLOG server. This can either be primary (default) or secondary. CLI Example: .. code-block:: bash salt '*' cimc.set_syslog_server foo.bar.com...
def set_syslog_server(server=None, type="primary"): if not server: raise salt.exceptions.CommandExecutionError("The SYSLOG server must be specified.") if type == "primary": dn = "sys/svc-ext/syslog/client-primary" inconfig = .format(server) elif type == "secondary": dn...
73,779
Sets a CIMC user with specified configurations. .. versionadded:: 2019.2.0 Args: uid(int): The user ID slot to create the user account in. username(str): The name of the user. password(str): The clear text password of the user. priv(str): The privilege level of the user. ...
def set_user(uid=None, username=None, password=None, priv=None, status=None): conf = "" if not uid: raise salt.exceptions.CommandExecutionError("The user ID must be specified.") if status: conf += ' accountStatus="{0}"'.format(status) if username: conf += ' name="{0}"'.fo...
73,780
Update the BIOS firmware through TFTP. Args: server(str): The IP address or hostname of the TFTP server. path(str): The TFTP path and filename for the BIOS image. CLI Example: .. code-block:: bash salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap
def tftp_update_bios(server=None, path=None): if not server: raise salt.exceptions.CommandExecutionError("The server name must be specified.") if not path: raise salt.exceptions.CommandExecutionError("The TFTP path must be specified.") dn = "sys/rack-unit-1/bios/fw-updatable" in...
73,781
A helper function to get a specified group object Args: name (str): The name of the object Returns: object: The specified group object
def _get_group_object(name): with salt.utils.winapi.Com(): nt = win32com.client.Dispatch('AdsNameSpaces') return nt.GetObject('', 'WinNT://./' + name + ',group')
74,134
Add the specified group Args: name (str): The name of the group to add Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' group.add foo
def add(name, **kwargs): if not info(name): comp_obj = _get_computer_object() try: new_group = comp_obj.Create('group', name) new_group.SetInfo() log.info('Successfully created group %s', name) except pywintypes.com_error as exc: msg = 'Fa...
74,136
Remove the named group Args: name (str): The name of the group to remove Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' group.delete foo
def delete(name, **kwargs): if info(name): comp_obj = _get_computer_object() try: comp_obj.Delete('group', name) log.info('Successfully removed group %s', name) except pywintypes.com_error as exc: msg = 'Failed to remove group {0}. {1}'.format( ...
74,137
Return information about a group Args: name (str): The name of the group for which to get information Returns: dict: A dictionary of information about the group CLI Example: .. code-block:: bash salt '*' group.info foo
def info(name): try: groupObj = _get_group_object(name) gr_name = groupObj.Name gr_mem = [_get_username(x) for x in groupObj.members()] except pywintypes.com_error as exc: msg = 'Failed to access group {0}. {1}'.format( name, win32api.FormatMessage(exc.excepinfo[...
74,138
Return info on all groups Args: refresh (bool): Refresh the info for all groups in ``__context__``. If False only the groups in ``__context__`` will be returned. If True the ``__context__`` will be refreshed with current data and returned. Default is False ...
def getent(refresh=False): if 'group.getent' in __context__ and not refresh: return __context__['group.getent'] ret = [] results = _get_all_groups() for result in results: group = {'gid': __salt__['file.group_to_gid'](result.Name), 'members': [_get_username(x) for...
74,139
Add a user to a group Args: name (str): The name of the group to modify username (str): The name of the user to add to the group Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' group.addu...
def adduser(name, username, **kwargs): try: group_obj = _get_group_object(name) except pywintypes.com_error as exc: msg = 'Failed to access group {0}. {1}'.format( name, win32api.FormatMessage(exc.excepinfo[5])) log.error(msg) return False existing_members =...
74,140
Ensure a group contains only the members in the list Args: name (str): The name of the group to modify members_list (str): A single user or a comma separated list of users. The group will contain only the users specified in this list. Returns: bool...
def members(name, members_list, **kwargs): members_list = [salt.utils.win_functions.get_sam_name(m) for m in members_list.split(",")] if not isinstance(members_list, list): log.debug('member_list is not a list') return False try: obj_group = _get_group_object(name) except p...
74,141
Return a list of groups Args: refresh (bool): Refresh the info for all groups in ``__context__``. If False only the groups in ``__context__`` will be returned. If True, the ``__context__`` will be refreshed with current data and returned. Default is False ...
def list_groups(refresh=False): if 'group.list_groups' in __context__ and not refresh: return __context__['group.list_groups'] results = _get_all_groups() ret = [] for result in results: ret.append(result.Name) __context__['group.list_groups'] = ret return ret
74,142
Evaulates Open vSwitch command`s retcode value. Args: retcode: Value of retcode field from response, should be 0, 1 or 2. stdout: Value of stdout filed from response. splitstring: String used to split the stdout default new line. Returns: List or False.
def _stdout_list_split(retcode, stdout='', splitstring='\n'): if retcode == 0: ret = stdout.split(splitstring) return ret else: return False
74,144
Converts from the JSON output provided by ovs-vsctl into a usable Python object tree. In particular, sets and maps are converted from lists to actual sets or maps. Args: obj: Object that shall be recursively converted. Returns: Converted version of object.
def _convert_json(obj): if isinstance(obj, dict): return {_convert_json(key): _convert_json(val) for (key, val) in six.iteritems(obj)} elif isinstance(obj, list) and len(obj) == 2: first = obj[0] second = obj[1] if first == 'set' and isinstance(second, list):...
74,145
Deletes bridge and all of its ports. Args: br: A string - bridge name if_exists: Bool, if False - attempting to delete a bridge that does not exist returns False. Returns: True on success, else False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash ...
def bridge_delete(br, if_exists=True): param_if_exists = _param_if_exists(if_exists) cmd = 'ovs-vsctl {1}del-br {0}'.format(br, param_if_exists) result = __salt__['cmd.run_all'](cmd) retcode = result['retcode'] return _retcode_to_bool(retcode)
74,149
Returns the parent bridge of a bridge. Args: br: A string - bridge name Returns: Name of the parent bridge. This is the same as the bridge name if the bridge is not a fake bridge. If the bridge does not exist, False is returned. CLI Example: .. code-block:: bash ...
def bridge_to_parent(br): cmd = 'ovs-vsctl br-to-parent {0}'.format(br) result = __salt__['cmd.run_all'](cmd) if result['retcode'] != 0: return False return result['stdout']
74,150
Returns the VLAN ID of a bridge. Args: br: A string - bridge name Returns: VLAN ID of the bridge. The VLAN ID is 0 if the bridge is not a fake bridge. If the bridge does not exist, False is returned. CLI Example: .. code-block:: bash salt '*' openvswitch.bridge_to_p...
def bridge_to_vlan(br): cmd = 'ovs-vsctl br-to-vlan {0}'.format(br) result = __salt__['cmd.run_all'](cmd) if result['retcode'] != 0: return False return int(result['stdout'])
74,151
Creates on bridge a new port named port. Returns: True on success, else False. Args: br: A string - bridge name port: A string - port name may_exist: Bool, if False - attempting to create a port that exists returns False. internal: A boolean to create an internal interf...
def port_add(br, port, may_exist=False, internal=False): param_may_exist = _param_may_exist(may_exist) cmd = 'ovs-vsctl {2}add-port {0} {1}'.format(br, port, param_may_exist) if internal: cmd += ' -- set interface {0} type=internal'.format(port) result = __salt__['cmd.run_all'](cmd) ret...
74,152
Deletes port. Args: br: A string - bridge name (If bridge is None, port is removed from whatever bridge contains it) port: A string - port name. if_exists: Bool, if False - attempting to delete a por that does not exist returns False. (Default True) Returns: True on success,...
def port_remove(br, port, if_exists=True): param_if_exists = _param_if_exists(if_exists) if port and not br: cmd = 'ovs-vsctl {1}del-port {0}'.format(port, param_if_exists) else: cmd = 'ovs-vsctl {2}del-port {0} {1}'.format(br, port, param_if_exists) result = __salt__['cmd.run_all'...
74,153
Lists all of the ports within bridge. Args: br: A string - bridge name. Returns: List of bridges (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_list br0
def port_list(br): cmd = 'ovs-vsctl list-ports {0}'.format(br) result = __salt__['cmd.run_all'](cmd) retcode = result['retcode'] stdout = result['stdout'] return _stdout_list_split(retcode, stdout)
74,154
Lists tags of the port. Args: port: A string - port name. Returns: List of tags (or empty list), False on failure. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_get_tag tap0
def port_get_tag(port): cmd = 'ovs-vsctl get port {0} tag'.format(port) result = __salt__['cmd.run_all'](cmd) retcode = result['retcode'] stdout = result['stdout'] return _stdout_list_split(retcode, stdout)
74,155
Isolate VM traffic using VLANs. Args: br: A string - bridge name. port: A string - port name. id: An integer in the valid range 0 to 4095 (inclusive), name of VLAN. internal: A boolean to create an internal interface if one does not exist. Returns: True on success, else...
def port_create_vlan(br, port, id, internal=False): interfaces = __salt__['network.interfaces']() if not 0 <= id <= 4095: return False elif not bridge_exists(br): return False elif not internal and port not in interfaces: return False elif port in port_list(br): ...
74,156
Generic Routing Encapsulation - creates GRE tunnel between endpoints. Args: br: A string - bridge name. port: A string - port name. id: An integer - unsigned 32-bit number, tunnel's key. remote: A string - remote endpoint's IP address. Returns: True on success, else Fal...
def port_create_gre(br, port, id, remote): if not 0 <= id < 2**32: return False elif not __salt__['dig.check_ip'](remote): return False elif not bridge_exists(br): return False elif port in port_list(br): cmd = 'ovs-vsctl set interface {0} type=gre options:remote_ip=...
74,157
Gets a column's value for a specific record. Args: table: A string - name of the database table. record: A string - identifier of the record. column: A string - name of the column. if_exists: A boolean - if True, it is not an error if the record does not exist. Retu...
def db_get(table, record, column, if_exists=False): cmd = ['ovs-vsctl', '--format=json', '--columns={0}'.format(column)] if if_exists: cmd += ['--if-exists'] cmd += ['list', table, record] result = __salt__['cmd.run_all'](cmd) if result['retcode'] != 0: raise CommandExecutionErr...
74,159
Download software packages by filename. Args: filename(str): The filename of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_file PanOS_5000-8.0.0 salt '*' pan...
def download_software_file(filename=None, synch=False): if not filename: raise CommandExecutionError("Filename option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', ...
74,513
Download software packages by version number. Args: version(str): The version of the PANOS file to download. synch (bool): If true then the file will synch to the peer unit. CLI Example: .. code-block:: bash salt '*' panos.download_software_version 8.0.0 salt '*' panos.d...
def download_software_version(version=None, synch=False): if not version: raise CommandExecutionError("Version option must not be none.") if not isinstance(synch, bool): raise CommandExecutionError("Synch option must be boolean..") if synch is True: query = {'type': 'op', ...
74,514
Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending cha...
def set_authentication_profile(profile=None, deploy=False): if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/dev...
74,521
Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash ...
def set_hostname(hostname=None, deploy=False): if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system...
74,522
Enables or disables the ICMP management service on the device. CLI Example: Args: enabled (bool): If true the service will be enabled. If false the service will be disabled. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-blo...
def set_management_icmp(enabled=True, deploy=False): if enabled is True: value = "no" elif enabled is False: value = "yes" else: raise CommandExecutionError("Invalid option provided for service enabled option.") ret = {} query = {'type': 'config', 'action...
74,523
Add an IPv4 address or network to the permitted IP list. CLI Example: Args: address (str): The IPv4 address or network to allow access to add to the Palo Alto device. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: ba...
def set_permitted_ip(address=None, deploy=False): if not address: raise CommandExecutionError("Address option must not be empty.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/syst...
74,526
Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash ...
def set_timezone(tz=None, deploy=False): if not tz: raise CommandExecutionError("Timezone name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/timezo...
74,527
Request the statuses of users. Should be sent once after login. Args: - jids: A list of jids representing the users whose statuses you are trying to get.
def __init__(self, jids, _id = None): super(GetStatusesIqProtocolEntity, self).__init__(self.__class__.XMLNS, _id, _type = "get", to = YowConstants.WHATSAPP_SERVER) self.setGetStatusesProps(jids)
79,332
Return a list of variable names being rejected for high correlation with one of remaining variables. Parameters: ---------- threshold : float Correlation value which is above the threshold are rejected Returns ------- list The lis...
def get_rejected_variables(self, threshold=0.9): variable_profile = self.description_set['variables'] result = [] if hasattr(variable_profile, 'correlation'): result = variable_profile.index[variable_profile.correlation > threshold].tolist() return result
82,141
Write the report to a file. By default a name is generated. Parameters: ---------- outputfile : str The name or the path of the file to generale including the extension (.html).
def to_file(self, outputfile=DEFAULT_OUTPUTFILE): if outputfile != NO_OUTPUTFILE: if outputfile == DEFAULT_OUTPUTFILE: outputfile = 'profile_' + str(hash(self)) + ".html" # TODO: should be done in the template with codecs.open(outputfile, 'w+b', ...
82,142
Tries to get the bucket region from Location.LocationConstraint Special cases: LocationConstraint EU defaults to eu-west-1 LocationConstraint null defaults to us-east-1 Args: b (object): A bucket object Returns: string: an aws region string
def get_region(b): remap = {None: 'us-east-1', 'EU': 'eu-west-1'} region = b.get('Location', {}).get('LocationConstraint') return remap.get(region, region)
82,319
STS Role assume a boto3.Session With automatic credential renewal. Args: role_arn: iam role arn to assume session_name: client session identifier session: an optional extant session, note session is captured in a function closure for renewing the sts assumed role. :return: a boto3...
def assumed_session(role_arn, session_name, session=None, region=None, external_id=None): if session is None: session = Session() retry = get_retry(('Throttling',)) def refresh(): parameters = {"RoleArn": role_arn, "RoleSessionName": session_name} if external_id is not None:...
82,581
jsonschema generation helper params: - type_name: name of the type - inherits: list of document fragments that are required via anyOf[$ref] - rinherit: use another schema as a base for this, basically work around inherits issues with additionalProperties and type enums. - alias...
def type_schema( type_name, inherits=None, rinherit=None, aliases=None, required=None, **props): if aliases: type_names = [type_name] type_names.extend(aliases) else: type_names = [type_name] if rinherit: s = copy.deepcopy(rinherit) s['properties...
83,106
Safely initialize a repository class to a property. Args: repository_class (class): The class to initialize. version (str): The gcp service version for the repository. Returns: object: An instance of repository_class.
def client(self, service_name, version, component, **kw): service = _create_service_api( self._credentials, service_name, version, kw.get('developer_key'), kw.get('cache_discovery', False), self._http or _build_http()) ret...
83,318
Builds HttpRequest object. Args: verb (str): Request verb (ex. insert, update, delete). verb_arguments (dict): Arguments to be passed with the request. Returns: httplib2.HttpRequest: HttpRequest to be sent to the API.
def _build_request(self, verb, verb_arguments): method = getattr(self._component, verb) # Python insists that keys in **kwargs be strings (not variables). # Since we initially build our kwargs as a dictionary where one of the # keys is a variable (target), we need to convert ke...
83,321
Executes query (ex. list) via a dedicated http object. Args: verb (str): Method to execute on the component (ex. get, list). verb_arguments (dict): key-value pairs to be passed to _BuildRequest. Yields: dict: Service Response. Raises: Pagination...
def execute_paged_query(self, verb, verb_arguments): if not self.supports_pagination(verb=verb): raise PaginationNotSupported('{} does not support pagination') request = self._build_request(verb, verb_arguments) number_of_pages_processed = 0 while request is not No...
83,324
Executes query (ex. search) via a dedicated http object. Args: verb (str): Method to execute on the component (ex. search). verb_arguments (dict): key-value pairs to be passed to _BuildRequest. Yields: dict: Service Response.
def execute_search_query(self, verb, verb_arguments): # Implementation of search does not follow the standard API pattern. # Fields need to be in the body rather than sent seperately. next_page_token = None number_of_pages_processed = 0 while True: req_body =...
83,325
Executes query (ex. get) via a dedicated http object. Args: verb (str): Method to execute on the component (ex. get, list). verb_arguments (dict): key-value pairs to be passed to _BuildRequest. Returns: dict: Service Response.
def execute_query(self, verb, verb_arguments): request = self._build_request(verb, verb_arguments) return self._execute(request)
83,326
Run execute with retries and rate limiting. Args: request (object): The HttpRequest object to execute. Returns: dict: The response from the API.
def _execute(self, request): if self._rate_limiter: # Since the ratelimiter library only exposes a context manager # interface the code has to be duplicated to handle the case where # no rate limiter is defined. with self._rate_limiter: re...
83,327
Create new IndexTable object. Args: preread: func, Pre-processing, applied to each field as it is read. precompile: func, Pre-compilation, applied to each field before compiling. file_path: String, Location of file to use as input.
def __init__(self, preread=None, precompile=None, file_path=None): self.index = None self.compiled = None if file_path: self._index_file = file_path self._index_handle = open(self._index_file, "r") self._ParseIndex(preread, precompile)
86,081
Reads index file and stores entries in TextTable. For optimisation reasons, a second table is created with compiled entries. Args: preread: func, Pre-processing, applied to each field as it is read. precompile: func, Pre-compilation, applied to each field before compiling. Raises: IndexTab...
def _ParseIndex(self, preread, precompile): self.index = texttable.TextTable() self.index.CsvToTable(self._index_handle) if preread: for row in self.index: for col in row.header: row[col] = preread(col, row[col]) self.compiled = ...
86,083
Create new CLiTable object. Args: index_file: String, file where template/command mappings reside. template_dir: String, directory where index file and templates reside.
def __init__(self, index_file=None, template_dir=None): # pylint: disable=E1002 super(CliTable, self).__init__() self._keys = set() self.raw = None self.index_file = index_file self.template_dir = template_dir if index_file: self.ReadIndex(ind...
86,086
Reads the IndexTable index file of commands and templates. Args: index_file: String, file where template/command mappings reside. Raises: CliTableError: A template column was not found in the table.
def ReadIndex(self, index_file=None): self.index_file = index_file or self.index_file fullpath = os.path.join(self.template_dir, self.index_file) if self.index_file and fullpath not in self.INDEX: self.index = IndexTable(self._PreParse, self._PreCompile, fullpath) ...
86,087
Creates a TextTable table of values from cmd_input string. Parses command output with template/s. If more than one template is found subsequent tables are merged if keys match (dropped otherwise). Args: cmd_input: String, Device/command response. attributes: Dict, attribute that further refine m...
def ParseCmd(self, cmd_input, attributes=None, templates=None): # Store raw command data within the object. self.raw = cmd_input if not templates: # Find template in template index. row_idx = self.index.GetRowMatch(attributes) if row_idx: ...
86,089