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/passwd 0644
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_perms instead.', func_name) return get_mode(path)
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.remove C:\\Temp
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('File path must be absolute: {0}'.format(path)) # Does the file/folder exists if not os.path.exists(path) and not is_link(path): raise CommandExecutionError('Path not found: {0}'.format(path)) # Remove ReadOnly Attribute if force: # Get current file attributes file_attributes = win32api.GetFileAttributes(path) win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL) try: if os.path.isfile(path): # A file and a symlinked file are removed the same way os.remove(path) elif is_link(path): # If it's a symlink directory, use the rmdir command os.rmdir(path) else: for name in os.listdir(path): item = '{0}\\{1}'.format(path, name) # If it's a normal directory, recurse to remove it's contents remove(item, force) # rmdir will work now because the directory is empty os.rmdir(path) except (OSError, IOError) as exc: if force: # Reset attributes to the original if delete fails. win32api.SetFileAttributes(path, file_attributes) raise CommandExecutionError( 'Could not remove \'{0}\': {1}'.format(path, exc) ) return True
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 directory Returns: bool: True if path is a symlink, otherwise False CLI Example: .. code-block:: bash salt '*' file.is_link /path/to/link
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 symlink Returns: str: The path that the symlink points to CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link
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('{0} is not a symbolic link'.format(path)) raise CommandExecutionError(exc.__str__()) except Exception as exc: raise CommandExecutionError(exc)
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() ret['result'] = True return ret
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://flathub.org/repo/flathub.flatpakrepo
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['stdout'] = out['stdout'].strip() ret['result'] = True return ret
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: CommandExecutionError: If the encoding cannot be detected
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 check_bom(_data): # Supported Python Codecs # https://docs.python.org/2/library/codecs.html # https://docs.python.org/3/library/codecs.html boms = [ ('UTF-32-BE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF32_BE)), ('UTF-32-LE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF32_LE)), ('UTF-16-BE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF16_BE)), ('UTF-16-LE', salt.utils.stringutils.to_bytes(codecs.BOM_UTF16_LE)), ('UTF-8', salt.utils.stringutils.to_bytes(codecs.BOM_UTF8)), ('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x38\x2D')), ('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x38')), ('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x39')), ('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x2b')), ('UTF-7', salt.utils.stringutils.to_bytes('\x2b\x2f\x76\x2f')), ] for _encoding, bom in boms: if _data.startswith(bom): log.debug('Found BOM for %s', _encoding) return _encoding return False def check_utf8_markers(_data): try: decoded = _data.decode('UTF-8') except UnicodeDecodeError: return False else: # Reject surrogate characters in Py2 (Py3 behavior) if six.PY2: for char in decoded: if 0xD800 <= ord(char) <= 0xDFFF: return False return True def check_system_encoding(_data): try: _data.decode(__salt_system_encoding__) except UnicodeDecodeError: return False else: return True if not os.path.isfile(path): raise CommandExecutionError('Not a file') try: with fopen(path, 'rb') as fp_: data = fp_.read(2048) except os.error: raise CommandExecutionError('Failed to open file') # Check for Unicode BOM encoding = check_bom(data) if encoding: return encoding # Check for UTF-8 markers if check_utf8_markers(data): return 'UTF-8' # Check system encoding if check_system_encoding(data): return __salt_system_encoding__ # Check for ASCII first if check_ascii(data): return 'ASCII' raise CommandExecutionError('Could not detect file encoding')
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 object or its definition
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 & execute with write', 0x1200a9: 'Read & execute', 0x120089: 'Read', 0x100116: 'Write', 'full_control': 0x1f01ff, 'modify': 0x1301bf, 'read_execute': 0x1200a9, 'read': 0x120089, 'write': 0x100116, }, 'advanced': { # Advanced 0x0001: 'List folder / read data', 0x0002: 'Create files / write data', 0x0004: 'Create folders / append data', 0x0008: 'Read extended attributes', 0x0010: 'Write extended attributes', 0x0020: 'Traverse folder / execute file', 0x0040: 'Delete subfolders and files', 0x0080: 'Read attributes', 0x0100: 'Write attributes', 0x10000: 'Delete', 0x20000: 'Read permissions', 0x40000: 'Change permissions', 0x80000: 'Take ownership', # 0x100000: 'SYNCHRONIZE', # This is in all of them 'list_folder': 0x0001, 'read_data': 0x0001, 'create_files': 0x0002, 'write_data': 0x0002, 'create_folders': 0x0004, 'append_data': 0x0004, 'read_ea': 0x0008, 'write_ea': 0x0010, 'traverse_folder': 0x0020, 'execute_file': 0x0020, 'delete_subfolders_files': 0x0040, 'read_attributes': 0x0080, 'write_attributes': 0x0100, 'delete': 0x10000, 'read_permissions': 0x20000, 'change_permissions': 0x40000, 'take_ownership': 0x80000, }, }, 'registry': { 'basic': { 0xf003f: 'Full Control', 0x20019: 'Read', 0x20006: 'Write', # Generic Values (These sometimes get hit) 0x10000000: 'Full Control', 0x20000000: 'Execute', 0x40000000: 'Write', 0xffffffff80000000: 'Read', 'full_control': 0xf003f, 'read': 0x20019, 'write': 0x20006, }, 'advanced': { # Advanced 0x0001: 'Query Value', 0x0002: 'Set Value', 0x0004: 'Create Subkey', 0x0008: 'Enumerate Subkeys', 0x0010: 'Notify', 0x0020: 'Create Link', 0x10000: 'Delete', 0x20000: 'Read Control', 0x40000: 'Write DAC', 0x80000: 'Write Owner', 'query_value': 0x0001, 'set_value': 0x0002, 'create_subkey': 0x0004, 'enum_subkeys': 0x0008, 'notify': 0x0010, 'create_link': 0x0020, 'delete': 0x10000, 'read_control': 0x20000, 'write_dac': 0x40000, 'write_owner': 0x80000, }, }, 'share': { 'basic': { 0x1f01ff: 'Full control', 0x1301bf: 'Change', 0x1200a9: 'Read', 'full_control': 0x1f01ff, 'change': 0x1301bf, 'read': 0x1200a9, }, 'advanced': {}, # No 'advanced' for shares, needed for lookup }, 'printer': { 'basic': { 0x20008: 'Print', 0xf000c: 'Manage this printer', 0xf0030: 'Manage documents', 'print': 0x20008, 'manage_printer': 0xf000c, 'manage_documents': 0xf0030, }, 'advanced': { # Advanced 0x10004: 'Manage this printer', 0x0008: 'Print', 0x20000: 'Read permissions', 0x40000: 'Change permissions', 0x80000: 'Take ownership', 'manage_printer': 0x10004, 'print': 0x0008, 'read_permissions': 0x20000, 'change_permissions': 0x40000, 'take_ownership': 0x80000, }, }, 'service': { 'basic': { 0xf01ff: 'Full Control', 0x2008f: 'Read & Write', 0x2018d: 'Read', 0x20002: 'Write', 'full_control': 0xf01ff, 'read_write': 0x2008f, 'read': 0x2018d, 'write': 0x20002, }, 'advanced': { 0x0001: 'Query Config', 0x0002: 'Change Config', 0x0004: 'Query Status', 0x0008: 'Enumerate Dependents', 0x0010: 'Start', 0x0020: 'Stop', 0x0040: 'Pause/Resume', 0x0080: 'Interrogate', 0x0100: 'User-Defined Control', # 0x10000: 'Delete', # Not visible in the GUI 0x20000: 'Read Permissions', 0x40000: 'Change Permissions', 0x80000: 'Change Owner', 'query_config': 0x0001, 'change_config': 0x0002, 'query_status': 0x0004, 'enum_dependents': 0x0008, 'start': 0x0010, 'stop': 0x0020, 'pause_resume': 0x0040, 'interrogate': 0x0080, 'user_defined': 0x0100, 'read_permissions': 0x20000, 'change_permissions': 0x40000, 'change_owner': 0x80000, }, } } # These denote inheritance # 0x0000 : Not inherited, I don't know the enumeration for this # 0x0010 : win32security.INHERITED_ACE # All the values in the dict below are combinations of the following # enumerations or'ed together # 0x0001 : win32security.OBJECT_INHERIT_ACE # 0x0002 : win32security.CONTAINER_INHERIT_ACE # 0x0004 : win32security.NO_PROPAGATE_INHERIT_ACE # 0x0008 : win32security.INHERIT_ONLY_ACE ace_prop = { 'file': { # for report 0x0000: 'Not Inherited (file)', 0x0001: 'This folder and files', 0x0002: 'This folder and subfolders', 0x0003: 'This folder, subfolders and files', 0x0006: 'This folder only', 0x0009: 'Files only', 0x000a: 'Subfolders only', 0x000b: 'Subfolders and files only', 0x0010: 'Inherited (file)', # for setting 'this_folder_only': 0x0006, 'this_folder_subfolders_files': 0x0003, 'this_folder_subfolders': 0x0002, 'this_folder_files': 0x0001, 'subfolders_files': 0x000b, 'subfolders_only': 0x000a, 'files_only': 0x0009, }, 'registry': { 0x0000: 'Not Inherited', 0x0002: 'This key and subkeys', 0x0006: 'This key only', 0x000a: 'Subkeys only', 0x0010: 'Inherited', 'this_key_only': 0x0006, 'this_key_subkeys': 0x0002, 'subkeys_only': 0x000a, }, 'registry32': { 0x0000: 'Not Inherited', 0x0002: 'This key and subkeys', 0x0006: 'This key only', 0x000a: 'Subkeys only', 0x0010: 'Inherited', 'this_key_only': 0x0006, 'this_key_subkeys': 0x0002, 'subkeys_only': 0x000a, }, } ace_type = { 'grant': win32security.ACCESS_ALLOWED_ACE_TYPE, 'deny': win32security.ACCESS_DENIED_ACE_TYPE, win32security.ACCESS_ALLOWED_ACE_TYPE: 'grant', win32security.ACCESS_DENIED_ACE_TYPE: 'deny', } element = { 'dacl': win32security.DACL_SECURITY_INFORMATION, 'group': win32security.GROUP_SECURITY_INFORMATION, 'owner': win32security.OWNER_SECURITY_INFORMATION, } inheritance = { 'protected': win32security.PROTECTED_DACL_SECURITY_INFORMATION, 'unprotected': win32security.UNPROTECTED_DACL_SECURITY_INFORMATION, } obj_type = { 'file': win32security.SE_FILE_OBJECT, 'service': win32security.SE_SERVICE, 'printer': win32security.SE_PRINTER, 'registry': win32security.SE_REGISTRY_KEY, 'registry32': win32security.SE_REGISTRY_WOW64_32KEY, 'share': win32security.SE_LMSHARE, } return Flags() if instantiated else Flags
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 object
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 SaltInvocationError( 'Invalid "obj_type" passed: {0}'.format(obj_type)) self.dacl_type = obj_type.lower() if obj_name is None: self.dacl = win32security.ACL() else: if 'registry' in self.dacl_type: obj_name = self.get_reg_name(obj_name) try: sd = win32security.GetNamedSecurityInfo( obj_name, self.obj_type[self.dacl_type], self.element['dacl']) except pywintypes.error as exc: if 'The system cannot find' in exc.strerror: msg = 'System cannot find {0}'.format(obj_name) log.exception(msg) raise CommandExecutionError(msg) raise self.dacl = sd.GetSecurityDescriptorDacl() if self.dacl is None: self.dacl = win32security.ACL() def get_reg_name(self, obj_name): # Make sure the hive is correct # Should be MACHINE, USERS, CURRENT_USER, or CLASSES_ROOT hives = { # MACHINE 'HKEY_LOCAL_MACHINE': 'MACHINE', 'MACHINE': 'MACHINE', 'HKLM': 'MACHINE', # USERS 'HKEY_USERS': 'USERS', 'USERS': 'USERS', 'HKU': 'USERS', # CURRENT_USER 'HKEY_CURRENT_USER': 'CURRENT_USER', 'CURRENT_USER': 'CURRENT_USER', 'HKCU': 'CURRENT_USER', # CLASSES ROOT 'HKEY_CLASSES_ROOT': 'CLASSES_ROOT', 'CLASSES_ROOT': 'CLASSES_ROOT', 'HKCR': 'CLASSES_ROOT', } reg = obj_name.split('\\') passed_hive = reg.pop(0) try: valid_hive = hives[passed_hive.upper()] except KeyError: log.exception('Invalid Registry Hive: %s', passed_hive) raise CommandExecutionError( 'Invalid Registry Hive: {0}'.format(passed_hive)) reg.insert(0, valid_hive) return r'\\'.join(reg) def add_ace(self, principal, access_mode, permissions, applies_to): sid = get_sid(principal) if self.dacl is None: raise SaltInvocationError( 'You must load the DACL before adding an ACE') # Get the permission flag perm_flag = 0 if isinstance(permissions, six.string_types): try: perm_flag = self.ace_perms[self.dacl_type]['basic'][permissions] except KeyError as exc: msg = 'Invalid permission specified: {0}'.format(permissions) log.exception(msg) raise CommandExecutionError(msg, exc) else: try: for perm in permissions: perm_flag |= self.ace_perms[self.dacl_type]['advanced'][perm] except KeyError as exc: msg = 'Invalid permission specified: {0}'.format(perm) log.exception(msg) raise CommandExecutionError(msg, exc) if access_mode.lower() not in ['grant', 'deny']: raise SaltInvocationError('Invalid Access Mode: {0}'.format(access_mode)) # Add ACE to the DACL # Grant or Deny try: if access_mode.lower() == 'grant': self.dacl.AddAccessAllowedAceEx( win32security.ACL_REVISION_DS, # Some types don't support propagation # May need to use 0x0000 instead of None self.ace_prop.get(self.dacl_type, {}).get(applies_to), perm_flag, sid) elif access_mode.lower() == 'deny': self.dacl.AddAccessDeniedAceEx( win32security.ACL_REVISION_DS, self.ace_prop.get(self.dacl_type, {}).get(applies_to), perm_flag, sid) else: log.exception('Invalid access mode: %s', access_mode) raise SaltInvocationError( 'Invalid access mode: {0}'.format(access_mode)) except Exception as exc: return False, 'Error: {0}'.format(exc) return True def order_acl(self): new_dacl = Dacl() deny_dacl = Dacl() deny_obj_dacl = Dacl() allow_dacl = Dacl() allow_obj_dacl = Dacl() # Load Non-Inherited ACEs first for i in range(0, self.dacl.GetAceCount()): ace = self.dacl.GetAce(i) if ace[0][1] & win32security.INHERITED_ACE == 0: if ace[0][0] == win32security.ACCESS_DENIED_ACE_TYPE: deny_dacl.dacl.AddAccessDeniedAceEx( win32security.ACL_REVISION_DS, ace[0][1], ace[1], ace[2]) elif ace[0][0] == win32security.ACCESS_DENIED_OBJECT_ACE_TYPE: deny_obj_dacl.dacl.AddAccessDeniedAceEx( win32security.ACL_REVISION_DS, ace[0][1], ace[1], ace[2]) elif ace[0][0] == win32security.ACCESS_ALLOWED_ACE_TYPE: allow_dacl.dacl.AddAccessAllowedAceEx( win32security.ACL_REVISION_DS, ace[0][1], ace[1], ace[2]) elif ace[0][0] == win32security.ACCESS_ALLOWED_OBJECT_ACE_TYPE: allow_obj_dacl.dacl.AddAccessAllowedAceEx( win32security.ACL_REVISION_DS, ace[0][1], ace[1], ace[2]) # Load Inherited ACEs last for i in range(0, self.dacl.GetAceCount()): ace = self.dacl.GetAce(i) if ace[0][1] & win32security.INHERITED_ACE == \ win32security.INHERITED_ACE: ace_prop = ace[0][1] ^ win32security.INHERITED_ACE if ace[0][0] == win32security.ACCESS_DENIED_ACE_TYPE: deny_dacl.dacl.AddAccessDeniedAceEx( win32security.ACL_REVISION_DS, ace_prop, ace[1], ace[2]) elif ace[0][0] == win32security.ACCESS_DENIED_OBJECT_ACE_TYPE: deny_obj_dacl.dacl.AddAccessDeniedAceEx( win32security.ACL_REVISION_DS, ace_prop, ace[1], ace[2]) elif ace[0][0] == win32security.ACCESS_ALLOWED_ACE_TYPE: allow_dacl.dacl.AddAccessAllowedAceEx( win32security.ACL_REVISION_DS, ace_prop, ace[1], ace[2]) elif ace[0][0] == win32security.ACCESS_ALLOWED_OBJECT_ACE_TYPE: allow_obj_dacl.dacl.AddAccessAllowedAceEx( win32security.ACL_REVISION_DS, ace_prop, ace[1], ace[2]) # Combine ACEs in the proper order # Deny, Deny Object, Allow, Allow Object # Deny for i in range(0, deny_dacl.dacl.GetAceCount()): ace = deny_dacl.dacl.GetAce(i) new_dacl.dacl.AddAccessDeniedAceEx( win32security.ACL_REVISION_DS, ace[0][1], ace[1], ace[2]) # Deny Object for i in range(0, deny_obj_dacl.dacl.GetAceCount()): ace = deny_obj_dacl.dacl.GetAce(i) new_dacl.dacl.AddAccessDeniedAceEx( win32security.ACL_REVISION_DS, ace[0][1] ^ win32security.INHERITED_ACE, ace[1], ace[2]) # Allow for i in range(0, allow_dacl.dacl.GetAceCount()): ace = allow_dacl.dacl.GetAce(i) new_dacl.dacl.AddAccessAllowedAceEx( win32security.ACL_REVISION_DS, ace[0][1], ace[1], ace[2]) # Allow Object for i in range(0, allow_obj_dacl.dacl.GetAceCount()): ace = allow_obj_dacl.dacl.GetAce(i) new_dacl.dacl.AddAccessAllowedAceEx( win32security.ACL_REVISION_DS, ace[0][1] ^ win32security.INHERITED_ACE, ace[1], ace[2]) # Set the new dacl self.dacl = new_dacl.dacl def get_ace(self, principal): principal = get_name(principal) aces = self.list_aces() # Filter for the principal ret = {} for inheritance in aces: if principal in aces[inheritance]: ret[inheritance] = {principal: aces[inheritance][principal]} return ret def list_aces(self): ret = {'Inherited': {}, 'Not Inherited': {}} # loop through each ACE in the DACL for i in range(0, self.dacl.GetAceCount()): ace = self.dacl.GetAce(i) # Get ACE Elements user, a_type, a_prop, a_perms, inheritance = self._ace_to_dict(ace) if user in ret[inheritance]: ret[inheritance][user][a_type] = { 'applies to': a_prop, 'permissions': a_perms, } else: ret[inheritance][user] = { a_type: { 'applies to': a_prop, 'permissions': a_perms, }} return ret def _ace_to_dict(self, ace): # Get the principal from the sid (object sid) sid = win32security.ConvertSidToStringSid(ace[2]) try: principal = get_name(sid) except CommandExecutionError: principal = sid # Get the ace type ace_type = self.ace_type[ace[0][0]] # Is the inherited ace flag present inherited = ace[0][1] & win32security.INHERITED_ACE == 16 # Ace Propagation ace_prop = 'NA' # Get the ace propagation properties if self.dacl_type in ['file', 'registry', 'registry32']: ace_prop = ace[0][1] # Remove the inherited ace flag and get propagation if inherited: ace_prop = ace[0][1] ^ win32security.INHERITED_ACE # Lookup the propagation try: ace_prop = self.ace_prop[self.dacl_type][ace_prop] except KeyError: ace_prop = 'Unknown propagation' # Get the object type obj_type = 'registry' if self.dacl_type == 'registry32' \ else self.dacl_type # Get the ace permissions # Check basic permissions first ace_perms = self.ace_perms[obj_type]['basic'].get(ace[1], []) # If it didn't find basic perms, check advanced permissions if not ace_perms: ace_perms = [] for perm in self.ace_perms[obj_type]['advanced']: # Don't match against the string perms if isinstance(perm, six.string_types): continue if ace[1] & perm == perm: ace_perms.append( self.ace_perms[obj_type]['advanced'][perm]) # If still nothing, it must be undefined if not ace_perms: ace_perms = ['Undefined Permission: {0}'.format(ace[1])] return principal, ace_type, ace_prop, ace_perms, \ 'Inherited' if inherited else 'Not Inherited' def rm_ace(self, principal, ace_type='all'): sid = get_sid(principal) offset = 0 ret = [] for i in range(0, self.dacl.GetAceCount()): ace = self.dacl.GetAce(i - offset) # Is the inherited ace flag present inherited = ace[0][1] & win32security.INHERITED_ACE == 16 if ace[2] == sid and not inherited: if self.ace_type[ace[0][0]] == ace_type.lower() or \ ace_type == 'all': self.dacl.DeleteAce(i - offset) ret.append(self._ace_to_dict(ace)) offset += 1 if not ret: ret = ['ACE not found for {0}'.format(principal)] return ret def save(self, obj_name, protected=None): sec_info = self.element['dacl'] if protected is not None: if protected: sec_info = sec_info | self.inheritance['protected'] else: sec_info = sec_info | self.inheritance['unprotected'] if self.dacl_type in ['registry', 'registry32']: obj_name = self.get_reg_name(obj_name) try: win32security.SetNamedSecurityInfo( obj_name, self.obj_type[self.dacl_type], sec_info, None, None, self.dacl, None) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to set permissions: {0}'.format(obj_name), exc.strerror) return True return Dacl(obj_name, obj_type)
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.utils.win_dacl.get_sid('jsnuffy') # Verify that the sid is valid salt.utils.win_dacl.get_sid('S-1-5-32-544')
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: sid = principal # Test if the SID is valid try: sid = win32security.ConvertStringSidToSid(sid) except pywintypes.error: log.exception('Invalid user/group or sid: %s', principal) raise CommandExecutionError( 'Invalid user/group or sid: {0}'.format(principal)) except TypeError: raise CommandExecutionError return sid
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') # Get the string version of the SID salt.utils.win_dacl.get_sid_string(py_sid)
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(principal) try: return win32security.ConvertSidToStringSid(principal) except pywintypes.error: log.exception('Invalid principal %s', principal) raise CommandExecutionError('Invalid principal {0}'.format(principal))
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: bool: True if successful Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.enable
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: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.get_rule 'MyAppPort'
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-block:: bash salt '*' beacons.add ps "[{'processes': {'salt-master': 'stopped', 'apache2': 'stopped'}}]"
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 is specified, if so, verify it is # valid and available beacon type. if any('beacon_module' in key for key in beacon_data): res = next(value for value in beacon_data if 'beacon_module' in value) beacon_name = res['beacon_module'] else: beacon_name = name if beacon_name not in list_available(return_yaml=False, **kwargs): ret['comment'] = 'Beacon "{0}" is not available.'.format(beacon_name) return ret if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'] = 'Beacon: {0} would be added.'.format(name) else: try: # Attempt to load the beacon module so we have access to the # validate function eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'beacon_data': beacon_data, 'func': 'validate_beacon'}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacon_validation_complete', wait=kwargs.get('timeout', 30)) valid = event_ret['valid'] vcomment = event_ret['vcomment'] if not valid: ret['result'] = False ret['comment'] = ('Beacon {0} configuration invalid, ' 'not adding.\n{1}'.format(name, vcomment)) return ret except KeyError: # Effectively a no-op, since we can't really return without an event # system ret['result'] = False ret['comment'] = 'Event module not available. Beacon add failed.' return ret try: res = __salt__['event.fire']({'name': name, 'beacon_data': beacon_data, 'func': 'add'}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacon_add_complete', wait=kwargs.get('timeout', 30)) if event_ret and event_ret['complete']: beacons = event_ret['beacons'] if name in beacons and beacons[name] == beacon_data: ret['result'] = True ret['comment'] = 'Added beacon: {0}.'.format(name) elif event_ret: ret['result'] = False ret['comment'] = event_ret['comment'] else: ret['result'] = False ret['comment'] = 'Did not receive the manage event ' \ 'before the timeout of {0}s' \ ''.format(kwargs.get('timeout', 30)) return ret except KeyError: # Effectively a no-op, since we can't really return without an event # system ret['result'] = False ret['comment'] = 'Event module not available. Beacon add failed.' return ret
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: .. code-block:: bash salt '*' beacons.modify ps "[{'salt-master': 'stopped'}, {'apache2': 'stopped'}]"
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['test']: ret['result'] = True ret['comment'] = 'Beacon: {0} would be modified.'.format(name) else: try: # Attempt to load the beacon module so we have access to the # validate function eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'beacon_data': beacon_data, 'func': 'validate_beacon'}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacon_validation_complete', wait=kwargs.get('timeout', 30)) valid = event_ret['valid'] vcomment = event_ret['vcomment'] if not valid: ret['result'] = False ret['comment'] = ('Beacon {0} configuration invalid, ' 'not modifying.\n{1}'.format(name, vcomment)) return ret except KeyError: # Effectively a no-op, since we can't really return without an event # system ret['result'] = False ret['comment'] = 'Event module not available. Beacon modify failed.' return ret if not valid: ret['result'] = False ret['comment'] = ('Beacon {0} configuration invalid, ' 'not modifying.\n{1}'.format(name, vcomment)) return ret _current = current_beacons[name] _new = beacon_data if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = [] for _item in _current: _current_lines.extend(['{0}:{1}\n'.format(key, value) for (key, value) in six.iteritems(_item)]) _new_lines = [] for _item in _new: _new_lines.extend(['{0}:{1}\n'.format(key, value) for (key, value) in six.iteritems(_item)]) _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes'] = {} ret['changes']['diff'] = ''.join(_diff) try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'beacon_data': beacon_data, 'func': 'modify'}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacon_modify_complete', wait=kwargs.get('timeout', 30)) if event_ret and event_ret['complete']: beacons = event_ret['beacons'] if name in beacons and beacons[name] == beacon_data: ret['result'] = True ret['comment'] = 'Modified beacon: {0}.'.format(name) elif event_ret: ret['result'] = False ret['comment'] = event_ret['comment'] else: ret['result'] = False ret['comment'] = 'Did not receive the manage event ' \ 'before the timeout of {0}s' \ ''.format(kwargs.get('timeout', 30)) return ret except KeyError: # Effectively a no-op, since we can't really return without an event # system ret['result'] = False ret['comment'] = 'Event module not available. Beacon modify failed.' return ret
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(name) else: _beacons = list_(return_yaml=False, **kwargs) if name not in _beacons: ret['comment'] = 'Beacon {0} is not currently configured.' \ ''.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable_beacon', 'name': name}, 'manage_beacons') if res: event_ret = eventer.get_event( tag='/salt/minion/minion_beacon_enabled_complete', wait=kwargs.get('timeout', 30)) if event_ret and event_ret['complete']: beacons = event_ret['beacons'] beacon_config_dict = _get_beacon_config_dict(beacons[name]) if 'enabled' in beacon_config_dict and beacon_config_dict['enabled']: ret['result'] = True ret['comment'] = 'Enabled beacon {0} on minion.' \ ''.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable beacon {0} on ' \ 'minion.'.format(name) elif event_ret: ret['result'] = False ret['comment'] = event_ret['comment'] else: ret['result'] = False ret['comment'] = 'Did not receive the manage event ' \ 'before the timeout of {0}s' \ ''.format(kwargs.get('timeout', 30)) return ret except KeyError: # Effectively a no-op, since we can't really return without an event # system ret['result'] = False ret['comment'] = 'Event module not available. Beacon enable job ' \ 'failed.' return ret
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['stdout']) raise CommandExecutionError(msg)
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 groups: ret_groups.add(get_sid_from_name(group)) return ret_groups
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 found: {1}'.format(name, exc)) return win32security.ConvertSidToStringSid(sid)
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.GetUserName() if test_user == 'SYSTEM': user_name = 'SYSTEM' elif get_sid_from_name(test_user) == 'S-1-5-18': user_name = 'SYSTEM' elif not with_domain: user_name = win32api.GetUserName() except pywintypes.error as exc: raise CommandExecutionError( 'Failed to get current user: {0}'.format(exc)) if not user_name: return False return user_name
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]+'-' + \ squid_match.group(2)[::-1]+'-' + \ squid_match.group(3)[::-1]+'-' + \ squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-' for index in range(6, 12): guid += squid_match.group(index)[::-1] guid += '}' return guid
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 endpoint's IP address. dst_port: Port to use when creating tunnelport in the switch. internal: Create an internal port if one does not exist
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 argument must be one of these values: {0}.'.format( six.text_type(tunnel_types)) ) bridge_exists = __salt__['openvswitch.bridge_exists'](bridge) port_list = [] if bridge_exists: port_list = __salt__['openvswitch.port_list'](bridge) # Comment and change messages comments = {} comments['comment_bridge_notexists'] = 'Bridge {0} does not exist.'.format(bridge) comments['comment_port_exists'] = 'Port {0} already exists.'.format(name) comments['comment_port_created'] = 'Port {0} created on bridge {1}.'.format(name, bridge) comments['comment_port_notcreated'] = 'Unable to create port {0} on bridge {1}.'.format(name, bridge) comments['changes_port_created'] = {name: {'old': 'No port named {0} present.'.format(name), 'new': 'Created port {1} on bridge {0}.'.format(bridge, name), } } comments['comment_port_internal'] = 'Port {0} already exists, but interface type has been changed to internal.'.format(name) comments['changes_port_internal'] = {'internal': {'old': False, 'new': True}} comments['comment_port_internal_not_changed'] = 'Port {0} already exists, but the interface type could not be changed to internal.'.format(name) if tunnel_type: comments['comment_invalid_ip'] = 'Remote is not valid ip address.' if tunnel_type == "vlan": comments['comment_vlan_invalid_id'] = 'VLANs id must be between 0 and 4095.' comments['comment_vlan_invalid_name'] = 'Could not find network interface {0}.'.format(name) comments['comment_vlan_port_exists'] = 'Port {0} with access to VLAN {1} already exists on bridge {2}.'.format(name, id, bridge) comments['comment_vlan_created'] = 'Created port {0} with access to VLAN {1} on bridge {2}.'.format(name, id, bridge) comments['comment_vlan_notcreated'] = 'Unable to create port {0} with access to VLAN {1} on ' \ 'bridge {2}.'.format(name, id, bridge) comments['changes_vlan_created'] = {name: {'old': 'No port named {0} with access to VLAN {1} present on ' 'bridge {2} present.'.format(name, id, bridge), 'new': 'Created port {1} with access to VLAN {2} on ' 'bridge {0}.'.format(bridge, name, id), } } elif tunnel_type == "gre": comments['comment_gre_invalid_id'] = 'Id of GRE tunnel must be an unsigned 32-bit integer.' comments['comment_gre_interface_exists'] = 'GRE tunnel interface {0} with rempte ip {1} and key {2} ' \ 'already exists on bridge {3}.'.format(name, remote, id, bridge) comments['comment_gre_created'] = 'Created GRE tunnel interface {0} with remote ip {1} and key {2} ' \ 'on bridge {3}.'.format(name, remote, id, bridge) comments['comment_gre_notcreated'] = 'Unable to create GRE tunnel interface {0} with remote ip {1} and key {2} ' \ 'on bridge {3}.'.format(name, remote, id, bridge) comments['changes_gre_created'] = {name: {'old': 'No GRE tunnel interface {0} with remote ip {1} and key {2} ' 'on bridge {3} present.'.format(name, remote, id, bridge), 'new': 'Created GRE tunnel interface {0} with remote ip {1} and key {2} ' 'on bridge {3}.'.format(name, remote, id, bridge), } } elif tunnel_type == "vxlan": comments['comment_dstport'] = ' (dst_port' + six.text_type(dst_port) + ')' if 0 < dst_port <= 65535 else '' comments['comment_vxlan_invalid_id'] = 'Id of VXLAN tunnel must be an unsigned 64-bit integer.' comments['comment_vxlan_interface_exists'] = 'VXLAN tunnel interface {0} with rempte ip {1} and key {2} ' \ 'already exists on bridge {3}{4}.'.format(name, remote, id, bridge, comments['comment_dstport']) comments['comment_vxlan_created'] = 'Created VXLAN tunnel interface {0} with remote ip {1} and key {2} ' \ 'on bridge {3}{4}.'.format(name, remote, id, bridge, comments['comment_dstport']) comments['comment_vxlan_notcreated'] = 'Unable to create VXLAN tunnel interface {0} with remote ip {1} and key {2} ' \ 'on bridge {3}{4}.'.format(name, remote, id, bridge, comments['comment_dstport']) comments['changes_vxlan_created'] = {name: {'old': 'No VXLAN tunnel interface {0} with remote ip {1} and key {2} ' 'on bridge {3}{4} present.'.format(name, remote, id, bridge, comments['comment_dstport']), 'new': 'Created VXLAN tunnel interface {0} with remote ip {1} and key {2} ' 'on bridge {3}{4}.'.format(name, remote, id, bridge, comments['comment_dstport']), } } # Check VLANs attributes def _check_vlan(): tag = __salt__['openvswitch.port_get_tag'](name) interfaces = __salt__['network.interfaces']() if not 0 <= id <= 4095: ret['result'] = False ret['comment'] = comments['comment_vlan_invalid_id'] elif not internal and name not in interfaces: ret['result'] = False ret['comment'] = comments['comment_vlan_invalid_name'] elif tag and name in port_list: try: if int(tag[0]) == id: ret['result'] = True ret['comment'] = comments['comment_vlan_port_exists'] except (ValueError, KeyError): pass # Check GRE tunnels attributes def _check_gre(): interface_options = __salt__['openvswitch.interface_get_options'](name) interface_type = __salt__['openvswitch.interface_get_type'](name) if not 0 <= id <= 2**32: ret['result'] = False ret['comment'] = comments['comment_gre_invalid_id'] elif not __salt__['dig.check_ip'](remote): ret['result'] = False ret['comment'] = comments['comment_invalid_ip'] elif interface_options and interface_type and name in port_list: interface_attroptions = '{key=\"' + six.text_type(id) + '\", remote_ip=\"' + six.text_type(remote) + '\"}' try: if interface_type[0] == 'gre' and interface_options[0] == interface_attroptions: ret['result'] = True ret['comment'] = comments['comment_gre_interface_exists'] except KeyError: pass # Check VXLAN tunnels attributes def _check_vxlan(): interface_options = __salt__['openvswitch.interface_get_options'](name) interface_type = __salt__['openvswitch.interface_get_type'](name) if not 0 <= id <= 2**64: ret['result'] = False ret['comment'] = comments['comment_vxlan_invalid_id'] elif not __salt__['dig.check_ip'](remote): ret['result'] = False ret['comment'] = comments['comment_invalid_ip'] elif interface_options and interface_type and name in port_list: opt_port = 'dst_port=\"' + six.text_type(dst_port) + '\", ' if 0 < dst_port <= 65535 else '' interface_attroptions = '{{{0}key=\"'.format(opt_port) + six.text_type(id) + '\", remote_ip=\"' + six.text_type(remote) + '\"}' try: if interface_type[0] == 'vxlan' and interface_options[0] == interface_attroptions: ret['result'] = True ret['comment'] = comments['comment_vxlan_interface_exists'] except KeyError: pass # Dry run, test=true mode if __opts__['test']: if bridge_exists: if tunnel_type == 'vlan': _check_vlan() if not ret['comment']: ret['result'] = None ret['comment'] = comments['comment_vlan_created'] elif tunnel_type == 'vxlan': _check_vxlan() if not ret['comment']: ret['result'] = None ret['comment'] = comments['comment_vxlan_created'] elif tunnel_type == 'gre': _check_gre() if not ret['comment']: ret['result'] = None ret['comment'] = comments['comment_gre_created'] else: if name in port_list: ret['result'] = True current_type = __salt__['openvswitch.interface_get_type']( name) # The interface type is returned as a single-element list. if internal and (current_type != ['internal']): ret['comment'] = comments['comment_port_internal'] else: ret['comment'] = comments['comment_port_exists'] else: ret['result'] = None ret['comment'] = comments['comment_port_created'] else: ret['result'] = None ret['comment'] = comments['comment_bridge_notexists'] return ret if bridge_exists: if tunnel_type == 'vlan': _check_vlan() if not ret['comment']: port_create_vlan = __salt__['openvswitch.port_create_vlan'](bridge, name, id, internal) if port_create_vlan: ret['result'] = True ret['comment'] = comments['comment_vlan_created'] ret['changes'] = comments['changes_vlan_created'] else: ret['result'] = False ret['comment'] = comments['comment_vlan_notcreated'] elif tunnel_type == 'vxlan': _check_vxlan() if not ret['comment']: port_create_vxlan = __salt__['openvswitch.port_create_vxlan'](bridge, name, id, remote, dst_port) if port_create_vxlan: ret['result'] = True ret['comment'] = comments['comment_vxlan_created'] ret['changes'] = comments['changes_vxlan_created'] else: ret['result'] = False ret['comment'] = comments['comment_vxlan_notcreated'] elif tunnel_type == 'gre': _check_gre() if not ret['comment']: port_create_gre = __salt__['openvswitch.port_create_gre'](bridge, name, id, remote) if port_create_gre: ret['result'] = True ret['comment'] = comments['comment_gre_created'] ret['changes'] = comments['changes_gre_created'] else: ret['result'] = False ret['comment'] = comments['comment_gre_notcreated'] else: if name in port_list: current_type = __salt__['openvswitch.interface_get_type'](name) # The interface type is returned as a single-element list. if internal and (current_type != ['internal']): # We do not have a direct way of only setting the interface # type to internal, so we add the port with the --may-exist # option. port_add = __salt__['openvswitch.port_add']( bridge, name, may_exist=True, internal=internal) if port_add: ret['result'] = True ret['comment'] = comments['comment_port_internal'] ret['changes'] = comments['changes_port_internal'] else: ret['result'] = False ret['comment'] = comments[ 'comment_port_internal_not_changed'] else: ret['result'] = True ret['comment'] = comments['comment_port_exists'] else: port_add = __salt__['openvswitch.port_add'](bridge, name, internal=internal) if port_add: ret['result'] = True ret['comment'] = comments['comment_port_created'] ret['changes'] = comments['changes_port_created'] else: ret['result'] = False ret['comment'] = comments['comment_port_notcreated'] else: ret['result'] = False ret['comment'] = comments['comment_bridge_notexists'] return ret
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) else: port_list = () else: port_list = [name] # Comment and change messages comments = {} comments['comment_bridge_notexists'] = 'Bridge {0} does not exist.'.format(bridge) comments['comment_port_notexists'] = 'Port {0} does not exist on bridge {1}.'.format(name, bridge) comments['comment_port_deleted'] = 'Port {0} deleted.'.format(name) comments['comment_port_notdeleted'] = 'Unable to delete port {0}.'.format(name) comments['changes_port_deleted'] = {name: {'old': 'Port named {0} may exist.'.format(name), 'new': 'Deleted port {0}.'.format(name), } } # Dry run, test=true mode if __opts__['test']: if bridge and not bridge_exists: ret['result'] = None ret['comment'] = comments['comment_bridge_notexists'] elif name not in port_list: ret['result'] = True ret['comment'] = comments['comment_port_notexists'] else: ret['result'] = None ret['comment'] = comments['comment_port_deleted'] return ret if bridge and not bridge_exists: ret['result'] = False ret['comment'] = comments['comment_bridge_notexists'] elif name not in port_list: ret['result'] = True ret['comment'] = comments['comment_port_notexists'] else: if bridge: port_remove = __salt__['openvswitch.port_remove'](br=bridge, port=name) else: port_remove = __salt__['openvswitch.port_remove'](br=None, port=name) if port_remove: ret['result'] = True ret['comment'] = comments['comment_port_deleted'] ret['changes'] = comments['changes_port_deleted'] else: ret['result'] = False ret['comment'] = comments['comment_port_notdeleted'] return ret
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`` Returns: dict: A dictionary containing the specified settings for each profile
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 path to the binary
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 # spaces in the path cmd = '"{0}"'.format(cmd) return cmd
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:: bash salt '*' service.info spooler
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 = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret
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, otherwise False CLI Example: .. code-block:: bash salt '*' reg.key_exists HKLM SOFTWARE\Microsoft
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 counters that are returned. .. note:: ``_Total`` is returned as ``*``
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 counter in counters: for instance in instance_list: instance = '*' if instance.lower() == '_total' else instance counter_list.append((obj, instance, counter)) else: # pylint: disable=useless-else-on-loop counter_list.append((obj, None, counter)) return get_counters(counter_list) if counter_list else {}
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) # Add counters to the Query for counter in counters: counter.add_to_query(query) # https://docs.microsoft.com/en-us/windows/desktop/perfctrs/collecting-performance-data win32pdh.CollectQueryData(query) # The sleep here is required for counters that require more than 1 # reading time.sleep(1) win32pdh.CollectQueryData(query) ret = {} for counter in counters: try: ret.update({counter.path: counter.value()}) except pywintypes.error as exc: if exc.strerror == 'No data to return.': # Some counters are not active and will throw an error if # there is no data to return continue else: raise finally: win32pdh.CloseQuery(query) return ret
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 available, otherwise False CLI Example: .. code-block:: bash salt '*' pkg.upgrade_available <package name>
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 already installed or # their is no package definition. This is a salt standard which could be improved. return latest_version(name, saltenv=saltenv, refresh=refresh) != ''
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 salt '*' pkg.list_upgrades
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 = {} for pkg in installed_pkgs: if pkg in available_pkgs: # latest_version() will be blank if the latest version is installed. # or the package name is wrong. Given we check available_pkgs, this # should not be the case of wrong package name. # Note: latest_version() is an expensive way to do this as it # calls list_pkgs each time. latest_ver = latest_version(pkg, refresh=False, saltenv=saltenv) if latest_ver: pkgs[pkg] = latest_ver return 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.get_repo_data
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 == -1: # no repo meta db log.debug('No winrepo.p cache file. Refresh pkg db now.') refresh_db(saltenv=saltenv) if 'winrepo.data' in __context__: log.trace('get_repo_data returning results from __context__') return __context__['winrepo.data'] else: log.trace('get_repo_data called reading from disk') try: serial = salt.payload.Serial(__opts__) with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile: try: repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {}) __context__['winrepo.data'] = repodata return repodata except Exception as exc: log.exception(exc) return {} except IOError as exc: log.error('Not able to read repo file') log.exception(exc) return {}
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 salt '*' pkg.compare_versions 1.2 >= 1.3
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': ver1 = six.text_type(sys.maxsize) if ver2 == 'latest': ver2 = six.text_type(sys.maxsize) # Support version being the special meaning of 'Not Found' if ver1 == 'Not Found': ver1 = '0.0.0.0.0' if ver2 == 'Not Found': ver2 = '0.0.0.0.0' return salt.utils.versions.compare(ver1, oper, ver2, ignore_epoch=True)
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', 'Machine', 'Microsoft', 'Windows NT', 'Audit', 'audit.csv') # Make sure there is an existing audit.csv file on the machine if not __salt__['file.file_exists'](f_audit): if __salt__['file.file_exists'](f_audit_gpo): # If the GPO audit.csv exists, we'll use that one __salt__['file.copy'](f_audit_gpo, f_audit) else: field_names = _get_audit_defaults('fieldnames') # If the file doesn't exist anywhere, create it with default # fieldnames __salt__['file.makedirs'](f_audit) __salt__['file.write'](f_audit, ','.join(field_names)) audit_settings = {} with salt.utils.files.fopen(f_audit, mode='r') as csv_file: reader = csv.DictReader(csv_file) for row in reader: audit_settings.update( {row['Subcategory']: row['Setting Value']}) __context__['lgpo.adv_audit_data'] = audit_settings return __context__['lgpo.adv_audit_data'].get(option, None)
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 value (str): The value to set. ['None', '0', '1', '2', '3'] Returns: bool: ``True`` if successful, otherwise ``False``
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', 'Machine', 'Microsoft', 'Windows NT', 'Audit', 'audit.csv') f_temp = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.csv', prefix='audit') # Lookup dict for "Inclusion Setting" field auditpol_values = {'None': 'No Auditing', '0': 'No Auditing', '1': 'Success', '2': 'Failure', '3': 'Success and Failure'} try: # Open the existing audit.csv and load the csv `reader` with salt.utils.files.fopen(f_audit, mode='r') as csv_file: reader = csv.DictReader(csv_file) # Open the temporary .csv and load the csv `writer` with salt.utils.files.fopen(f_temp.name, mode='w') as tmp_file: writer = csv.DictWriter(tmp_file, fieldnames=reader.fieldnames) # Write the header values (labels) writer.writeheader() value_written = False # Loop through the current audit.csv and write the changes to # the temp csv file for existing settings for row in reader: # If the row matches the value we're setting, update it with # the new value if row['Subcategory'] == option: if not value == 'None': # The value is not None, make the change row['Inclusion Setting'] = auditpol_values[value] row['Setting Value'] = value log.debug('LGPO: Setting {0} to {1}' ''.format(option, value)) writer.writerow(row) else: # value is None, remove it by not writing it to the # temp file log.debug('LGPO: Removing {0}'.format(option)) value_written = True # If it's not the value we're setting, just write it else: writer.writerow(row) # If a value was not written, it is a new setting not found in # the existing audit.cvs file. Add the new setting with values # from the defaults if not value_written: if not value == 'None': # value is not None, write the new value log.debug('LGPO: Setting {0} to {1}' ''.format(option, value)) defaults = _get_audit_defaults(option) writer.writerow({ 'Machine Name': defaults['Machine Name'], 'Policy Target': defaults['Policy Target'], 'Subcategory': defaults['Subcategory'], 'Subcategory GUID': defaults['Subcategory GUID'], 'Inclusion Setting': auditpol_values[value], 'Exclusion Setting': defaults['Exclusion Setting'], 'Setting Value': value}) value_written = True if value_written: # Copy the temporary csv file over the existing audit.csv in both # locations if a value was written __salt__['file.copy'](f_temp.name, f_audit, remove_existing=True) __salt__['file.makedirs'](f_audit_gpo) __salt__['file.copy'](f_temp.name, f_audit_gpo, remove_existing=True) finally: f_temp.close() __salt__['file.remove'](f_temp.name) return value_written
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: bool: ``True`` if successful, otherwise ``False``
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 __utils__['auditpol.set_setting']( name=defaults['Auditpol Name'], value=auditpol_values[value])
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: .. code-block:: bash salt myminion inspector.export salt myminion inspector.export format=iso path=/opt/builds/
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").Inspector().reuse_snapshot().export(description, local=local, path=path, format=format) except InspectorKiwiProcessorException as ex: raise CommandExecutionError(ex) except Exception as ex: log.error(_get_error_message(ex)) raise Exception(ex)
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 Example: ..code-block:: yaml salt-proxy-configure: salt_proxy.configure_proxy: - proxyname: p8000 - start: True
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 packages? Returns: dict: A dictionary containing the results of the installation CLI Example: .. code-block:: bash salt '*' macpackage.install test.pkg
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' if allow_untrusted: cmd += ' -allowUntrusted' # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True return __salt__['cmd.run_all'](cmd, python_shell=python_shell)
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 CLI Example: .. code-block:: bash salt '*' macpackage.install_app /tmp/tmp.app /Applications/
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 += '/' cmd = 'rsync -a --delete "{0}" "{1}"'.format(app, target) return __salt__['cmd.run'](cmd)
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-block:: bash salt '*' macpackage.mount /tmp/software.dmg
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, output_loglevel='quiet') files = out.split('\n') if 'Error opening' not in out: # Extract the PackageInfo files cmd = 'xar -x -f {0} {1}'.format(pkg, ' '.join(files)) __salt__['cmd.run'](cmd, cwd=temp_dir, output_loglevel='quiet') # Find our identifiers for f in files: i = _get_pkg_id_from_pkginfo(os.path.join(temp_dir, f)) if i: package_ids.extend(i) else: package_ids = _get_pkg_id_dir(pkg) finally: # Clean up __salt__['file.remove'](temp_dir) return package_ids
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: package_infos.extend(get_pkg_id(p)) return package_infos
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, but are not specified in this dictionary are not touched. record: The name of the record (optional). Replaces name if specified.
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 messages comment_changes = 'Columns have been updated.' comment_no_changes = 'All columns are already up to date.' comment_error = 'Error while updating column {0}: {1}' # Dry run, test=true mode if __opts__['test']: for column in data: if data[column] != current_data[column]: ret['changes'][column] = {'old': current_data[column], 'new': data[column]} if ret['changes']: ret['result'] = None ret['comment'] = comment_changes else: ret['result'] = True ret['comment'] = comment_no_changes return ret for column in data: if data[column] != current_data[column]: result = __salt__['openvswitch.db_set'](table, record, column, data[column]) if result is not None: ret['comment'] = comment_error.format(column, result) ret['result'] = False return ret ret['changes'][column] = {'old': current_data[column], 'new': data[column]} ret['result'] = True ret['comment'] = comment_no_changes return ret
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:: bash salt '*' cimc.create_user 11 username=admin password=foobar priv=admin
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 salt.exceptions.CommandExecutionError("The password must be specified.") if not priv: raise salt.exceptions.CommandExecutionError("The privilege level must be specified.") dn = "sys/user-ext/user-{0}".format(uid) inconfig = .format(uid, username, priv, password) ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False) return ret
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['outConfig']['mgmtIf'][0]['status'] == 'modified': return True else: return False except Exception as err: return False
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 for the local device. CLI Example: .. code-block:: bash salt '*' cimc.set_logging_levels remote=error local=notice
def set_logging_levels(remote=None, local=None): logging_options = ['emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'informational', 'debug'] query = "" if remote: if remote in logging_options: query += ' remoteSeverity="{0}"'.format(remote) else: raise salt.exceptions.CommandExecutionError("Remote Severity option is not valid.") if local: if local in logging_options: query += ' localSeverity="{0}"'.format(local) else: raise salt.exceptions.CommandExecutionError("Local Severity option is not valid.") dn = "sys/svc-ext/syslog" inconfig = .format(query) ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False) return ret
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 salt '*' cimc.set_syslog_server foo.bar.com primary salt '*' cimc.set_syslog_server foo.bar.com secondary
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 = "sys/svc-ext/syslog/client-secondary" inconfig = .format(server) else: raise salt.exceptions.CommandExecutionError("The SYSLOG type must be either primary or secondary.") ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False) return ret
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. status(str): The account status of the user. CLI Example: .. code-block:: bash salt '*' cimc.set_user 11 username=admin password=foobar priv=admin active
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}"'.format(username) if priv: conf += ' priv="{0}"'.format(priv) if password: conf += ' pwd="{0}"'.format(password) dn = "sys/user-ext/user-{0}".format(uid) inconfig = .format(uid, conf) ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False) return ret
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" inconfig = .format(server, path) ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False) return ret
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 = 'Failed to create group {0}. {1}'.format( name, win32api.FormatMessage(exc.excepinfo[5])) log.error(msg) return False else: log.warning('The group %s already exists.', name) return False return True
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( name, win32api.FormatMessage(exc.excepinfo[5])) log.error(msg) return False else: log.warning('The group %s does not exists.', name) return False return True
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[5])) log.debug(msg) return False if not gr_name: return False return {'name': gr_name, 'passwd': None, 'gid': None, 'members': gr_mem}
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 Returns: A list of groups and their information CLI Example: .. code-block:: bash salt '*' group.getent
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 x in result.members()], 'name': result.Name, 'passwd': 'x'} ret.append(group) __context__['group.getent'] = ret return ret
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.adduser foo username
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 = [_get_username(x) for x in group_obj.members()] username = salt.utils.win_functions.get_sam_name(username) try: if username not in existing_members: group_obj.Add('WinNT://' + username.replace('\\', '/')) log.info('Added user %s', username) else: log.warning('User %s is already a member of %s', username, name) return False except pywintypes.com_error as exc: msg = 'Failed to add {0} to group {1}. {2}'.format( username, name, win32api.FormatMessage(exc.excepinfo[5])) log.error(msg) return False return True
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: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' group.members foo 'user1,user2,user3'
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 pywintypes.com_error as exc: # Group probably doesn't exist, but we'll log the error msg = 'Failed to access group {0}. {1}'.format( name, win32api.FormatMessage(exc.excepinfo[5])) log.error(msg) return False existing_members = [_get_username(x) for x in obj_group.members()] existing_members.sort() members_list.sort() if existing_members == members_list: log.info('%s membership is correct', name) return True # add users success = True for member in members_list: if member not in existing_members: try: obj_group.Add('WinNT://' + member.replace('\\', '/')) log.info('User added: %s', member) except pywintypes.com_error as exc: msg = 'Failed to add {0} to {1}. {2}'.format( member, name, win32api.FormatMessage(exc.excepinfo[5])) log.error(msg) success = False # remove users not in members_list for member in existing_members: if member not in members_list: try: obj_group.Remove('WinNT://' + member.replace('\\', '/')) log.info('User removed: %s', member) except pywintypes.com_error as exc: msg = 'Failed to remove {0} from {1}. {2}'.format( member, name, win32api.FormatMessage(exc.excepinfo[5])) log.error(msg) success = False return success
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 Returns: list: A list of groups on the machine CLI Example: .. code-block:: bash salt '*' group.list_groups
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): return [_convert_json(elem) for elem in second] elif first == 'map' and isinstance(second, list): for elem in second: if not isinstance(elem, list) or len(elem) != 2: return obj return {elem[0]: _convert_json(elem[1]) for elem in second} else: return obj elif isinstance(obj, list): return [_convert_json(elem) for elem in obj] else: return obj
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 salt '*' openvswitch.bridge_delete br0
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 salt '*' openvswitch.bridge_to_parent br0
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_parent br0
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 interface if one does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_add br0 8080
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) retcode = result['retcode'] return _retcode_to_bool(retcode)
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, else False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_remove br0 8080
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'](cmd) retcode = result['retcode'] return _retcode_to_bool(retcode)
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 False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_create_vlan br0 tap0 100
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): cmd = 'ovs-vsctl set port {0} tag={1}'.format(port, id) if internal: cmd += ' -- set interface {0} type=internal'.format(port) result = __salt__['cmd.run_all'](cmd) return _retcode_to_bool(result['retcode']) else: cmd = 'ovs-vsctl add-port {0} {1} tag={2}'.format(br, port, id) if internal: cmd += ' -- set interface {0} type=internal'.format(port) result = __salt__['cmd.run_all'](cmd) return _retcode_to_bool(result['retcode'])
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 False. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' openvswitch.port_create_gre br0 gre1 5001 192.168.1.10
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={1} options:key={2}'.format(port, remote, id) result = __salt__['cmd.run_all'](cmd) return _retcode_to_bool(result['retcode']) else: cmd = 'ovs-vsctl add-port {0} {1} -- set interface {1} type=gre options:remote_ip={2} ' \ 'options:key={3}'.format(br, port, remote, id) result = __salt__['cmd.run_all'](cmd) return _retcode_to_bool(result['retcode'])
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. Returns: The column's value. CLI Example: .. code-block:: bash salt '*' openvswitch.db_get Port br0 vlan_mode
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 CommandExecutionError(result['stderr']) output = _stdout_parse_json(result['stdout']) if output['data'] and output['data'][0]: return output['data'][0][0] else: return None
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 '*' panos.download_software_file PanOS_5000-8.0.0 True
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', 'cmd': '<request><system><software><download>' '<file>{0}</file></download></software></system></request>'.format(filename)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<file>{0}</file></download></software></system></request>'.format(filename)} return _get_job_results(query)
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.download_software_version 8.0.0 True
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', 'cmd': '<request><system><software><download>' '<version>{0}</version></download></software></system></request>'.format(version)} else: query = {'type': 'op', 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>' '<version>{0}</version></download></software></system></request>'.format(version)} return _get_job_results(query)
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 change. .. code-block:: bash salt '*' panos.set_authentication_profile foo salt '*' panos.set_authentication_profile foo deploy=True
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\']/deviceconfig/system/' 'authentication-profile', 'element': '<authentication-profile>{0}</authentication-profile>'.format(profile)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
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 salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True
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', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
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-block:: bash salt '*' panos.set_management_icmp salt '*' panos.set_management_icmp enabled=False deploy=True
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': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system/service', 'element': '<disable-icmp>{0}</disable-icmp>'.format(value)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
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:: bash salt '*' panos.set_permitted_ip 10.0.0.1 salt '*' panos.set_permitted_ip 10.0.0.0/24 salt '*' panos.set_permitted_ip 10.0.0.1 deploy=True
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/system/permitted-ip', 'element': '<entry name=\'{0}\'></entry>'.format(address)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
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 salt '*' panos.set_timezone UTC salt '*' panos.set_timezone UTC deploy=True
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/timezone', 'element': '<timezone>{0}</timezone>'.format(tz)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
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 list of rejected variables or an empty list if the correlation has not been computed.
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', encoding='utf8') as self.file: self.file.write(templates.template('wrapper').render(content=self.html))
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 session using the sts assumed role credentials Notes: We have to poke at botocore internals a few times
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: parameters['ExternalId'] = external_id credentials = retry( session.client('sts').assume_role, **parameters)['Credentials'] return dict( access_key=credentials['AccessKeyId'], secret_key=credentials['SecretAccessKey'], token=credentials['SessionToken'], # Silly that we basically stringify so it can be parsed again expiry_time=credentials['Expiration'].isoformat()) session_credentials = RefreshableCredentials.create_from_metadata( metadata=refresh(), refresh_using=refresh, method='sts-assume-role') # so dirty.. it hurts, no clean way to set this outside of the # internals poke. There's some work upstream on making this nicer # but its pretty baroque as well with upstream support. # https://github.com/boto/boto3/issues/443 # https://github.com/boto/botocore/issues/761 s = get_session() s._credentials = session_credentials if region is None: region = s.get_config_variable('region') or 'us-east-1' s.set_config_variable('region', region) return Session(botocore_session=s)
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. - aliases: additional names this type maybe called - required: list of required properties, by default 'type' is required - props: additional key value properties
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']['type'] = {'enum': type_names} else: s = { 'type': 'object', 'properties': { 'type': {'enum': type_names}}} # Ref based inheritance and additional properties don't mix well. # https://stackoverflow.com/questions/22689900/json-schema-allof-with-additionalproperties if not inherits: s['additionalProperties'] = False s['properties'].update(props) if not required: required = [] if isinstance(required, list): required.append('type') s['required'] = required if inherits: extended = s s = {'allOf': [{'$ref': i} for i in inherits]} s['allOf'].append(extended) return s
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()) return ServiceClient( gcp_service=service, component=component, credentials=self._credentials, rate_limiter=self._rate_limiter, use_cached_http=self._use_cached_http, http=self._http)
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 keys to strings, # even though the variable in question is of type str. method_args = {str(k): v for k, v in verb_arguments.items()} return method(**method_args)
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: PaginationNotSupportedError: When an API does not support paging.
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 None: response = self._execute(request) number_of_pages_processed += 1 log.debug('Executing paged request #%s', number_of_pages_processed) request = self._build_next_request(verb, request, response) yield response
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 = verb_arguments.get('body', dict()) if next_page_token: req_body['pageToken'] = next_page_token request = self._build_request(verb, verb_arguments) response = self._execute(request) number_of_pages_processed += 1 log.debug('Executing paged request #%s', number_of_pages_processed) next_page_token = response.get('nextPageToken') yield response if not next_page_token: break
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: return request.execute(http=self.http, num_retries=self._num_retries) return request.execute(http=self.http, num_retries=self._num_retries)
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: IndexTableError: If the column headers has illegal column labels.
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 = copy.deepcopy(self.index) for row in self.compiled: for col in row.header: if precompile: row[col] = precompile(col, row[col]) if row[col]: row[col] = copyable_regex_object.CopyableRegexObject(row[col])
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(index_file)
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) self.INDEX[fullpath] = self.index else: self.index = self.INDEX[fullpath] # Does the IndexTable have the right columns. if "Template" not in self.index.index.header: # pylint: disable=E1103 raise CliTableError("Index file does not have 'Template' column.")
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 matching template. templates: String list of templates to parse with. If None, uses index Raises: CliTableError: A template was not found for the given command.
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: templates = self.index.index[row_idx]["Template"] else: raise CliTableError( 'No template found for attributes: "%s"' % attributes ) template_files = self._TemplateNamesToFiles(templates) try: # Re-initialise the table. self.Reset() self._keys = set() self.table = self._ParseCmdItem(self.raw, template_file=template_files[0]) # Add additional columns from any additional tables. for tmplt in template_files[1:]: self.extend( self._ParseCmdItem(self.raw, template_file=tmplt), set(self._keys) ) finally: for f in template_files: f.close()
86,089