desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return if the database is closed. :return:'
def is_closed(self):
return (not self._opened)
'Create a table from the object. NOTE: This method doesn\'t stores anything. :param obj: :return:'
def create_table_from_object(self, obj):
get_type = (lambda item: str(type(item)).split("'")[1]) if (not os.path.exists(os.path.join(self.db_path, obj._TABLE))): with gzip.open(os.path.join(self.db_path, obj._TABLE), 'wb') as table_file: csv.writer(table_file).writerow(['{col}:{type}'.format(col=elm[0], type=get_type(elm[1])) for elm in tuple(obj.__dict__.items())]) self._tables[obj._TABLE] = self._load_table(obj._TABLE)
'Store an object in the table. :param obj: An object to store :param distinct: Store object only if there is none identical of such. If at least one field is different, store it. :return:'
def store(self, obj, distinct=False):
if distinct: fields = dict(zip(self._tables[obj._TABLE].keys(), obj._serialize(self._tables[obj._TABLE]))) db_obj = self.get(obj.__class__, eq=fields) if (db_obj and distinct): raise Exception('Object already in the database.') with gzip.open(os.path.join(self.db_path, obj._TABLE), 'a') as table: csv.writer(table).writerow(self._validate_object(obj))
'Update object(s) in the database. :param obj: :param matches: :param mt: :param lt: :param eq: :return:'
def update(self, obj, matches=None, mt=None, lt=None, eq=None):
updated = False objects = list() for _obj in self.get(obj.__class__): if self.__criteria(_obj, matches=matches, mt=mt, lt=lt, eq=eq): objects.append(obj) updated = True else: objects.append(_obj) self.flush(obj._TABLE) self.create_table_from_object(obj) for obj in objects: self.store(obj) return updated
'Delete object from the database. :param obj: :param matches: :param mt: :param lt: :param eq: :return:'
def delete(self, obj, matches=None, mt=None, lt=None, eq=None):
deleted = False objects = list() for _obj in self.get(obj): if (not self.__criteria(_obj, matches=matches, mt=mt, lt=lt, eq=eq)): objects.append(_obj) else: deleted = True self.flush(obj._TABLE) self.create_table_from_object(obj()) for _obj in objects: self.store(_obj) return deleted
'Returns True if object is aligned to the criteria. :param obj: :param matches: :param mt: :param lt: :param eq: :return: Boolean'
def __criteria(self, obj, matches=None, mt=None, lt=None, eq=None):
for (field, value) in (mt or {}).items(): if (getattr(obj, field) <= value): return False for (field, value) in (lt or {}).items(): if (getattr(obj, field) >= value): return False for (field, value) in (eq or {}).items(): if (getattr(obj, field) != value): return False for (field, value) in (matches or {}).items(): if (not re.search(value, str(getattr(obj, field)))): return False return True
'Get objects from the table. :param table_name: :param matches: Regexp. :param mt: More than. :param lt: Less than. :param eq: Equals. :return:'
def get(self, obj, matches=None, mt=None, lt=None, eq=None):
objects = [] with gzip.open(os.path.join(self.db_path, obj._TABLE), 'rb') as table: header = None for data in csv.reader(table): if (not header): header = data continue _obj = obj() for (t_attr, t_data) in zip(header, data): (t_attr, t_type) = t_attr.split(':') setattr(_obj, t_attr, self._to_type(t_data, t_type)) if self.__criteria(_obj, matches=matches, mt=mt, lt=lt, eq=eq): objects.append(_obj) return objects
'Open new snapshot. :return:'
def create_snapshot(self):
self.db.open(new=True) return self
'Open an existing, latest snapshot. :return:'
def reuse_snapshot(self):
self.db.open() return self
'Call an external system command.'
def _syscall(self, command, input=None, env=None, *params):
return Popen(([command] + list(params)), stdout=PIPE, stdin=PIPE, stderr=STDOUT, env=(env or os.environ)).communicate(input=input)
'Package scanner switcher between the platforms. :return:'
def _get_cfg_pkgs(self):
if (self.grains_core.os_data().get('os_family') == 'Debian'): return self.__get_cfg_pkgs_dpkg() elif (self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']): return self.__get_cfg_pkgs_rpm() else: return dict()
'Get packages with configuration files on Dpkg systems. :return:'
def __get_cfg_pkgs_dpkg(self):
data = dict() for pkg_name in salt.utils.stringutils.to_str(self._syscall('dpkg-query', None, None, '-Wf', '${binary:Package}\\n')[0]).split(os.linesep): pkg_name = pkg_name.strip() if (not pkg_name): continue data[pkg_name] = list() for pkg_cfg_item in salt.utils.stringutils.to_str(self._syscall('dpkg-query', None, None, '-Wf', '${Conffiles}\\n', pkg_name)[0]).split(os.linesep): pkg_cfg_item = pkg_cfg_item.strip() if (not pkg_cfg_item): continue (pkg_cfg_file, pkg_cfg_sum) = pkg_cfg_item.strip().split(' ', 1) data[pkg_name].append(pkg_cfg_file) if (not data[pkg_name]): data.pop(pkg_name) return data
'Get packages with configuration files on RPM systems.'
def __get_cfg_pkgs_rpm(self):
(out, err) = self._syscall('rpm', None, None, '-qa', '--configfiles', '--queryformat', '%{name}-%{version}-%{release}\\n') data = dict() pkg_name = None pkg_configs = [] out = salt.utils.stringutils.to_str(out) for line in out.split(os.linesep): line = line.strip() if (not line): continue if (not line.startswith('/')): if (pkg_name and pkg_configs): data[pkg_name] = pkg_configs pkg_name = line pkg_configs = [] else: pkg_configs.append(line) if (pkg_name and pkg_configs): data[pkg_name] = pkg_configs return data
'Filter out unchanged packages on the Debian or RPM systems. :param data: Structure {package-name -> [ file .. file1 ]} :return: Same structure as data, except only files that were changed.'
def _get_changed_cfg_pkgs(self, data):
f_data = dict() for (pkg_name, pkg_files) in data.items(): cfgs = list() cfg_data = list() if (self.grains_core.os_data().get('os_family') == 'Debian'): cfg_data = salt.utils.stringutils.to_str(self._syscall('dpkg', None, None, '--verify', pkg_name)[0]).split(os.linesep) elif (self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']): cfg_data = salt.utils.stringutils.to_str(self._syscall('rpm', None, None, '-V', '--nodeps', '--nodigest', '--nosignature', '--nomtime', '--nolinkto', pkg_name)[0]).split(os.linesep) for line in cfg_data: line = line.strip() if ((not line) or (line.find(' c ') < 0) or (line.split(' ')[0].find('5') < 0)): continue cfg_file = line.split(' ')[(-1)] if (cfg_file in pkg_files): cfgs.append(cfg_file) if cfgs: f_data[pkg_name] = cfgs return f_data
'Save configuration packages. (NG) :param data: :return:'
def _save_cfg_packages(self, data):
pkg_id = 0 pkg_cfg_id = 0 for (pkg_name, pkg_configs) in data.items(): pkg = Package() pkg.id = pkg_id pkg.name = pkg_name self.db.store(pkg) for pkg_config in pkg_configs: cfg = PackageCfgFile() cfg.id = pkg_cfg_id cfg.pkgid = pkg_id cfg.path = pkg_config self.db.store(cfg) pkg_cfg_id += 1 pkg_id += 1
'Save payload (unmanaged files) :param files: :param directories: :param links: :return:'
def _save_payload(self, files, directories, links):
idx = 0 for (p_type, p_list) in (('f', files), ('d', directories), ('l', links)): for p_obj in p_list: stats = os.stat(p_obj) payload = PayloadFile() payload.id = idx payload.path = p_obj payload.p_type = p_type payload.mode = stats.st_mode payload.uid = stats.st_uid payload.gid = stats.st_gid payload.p_size = stats.st_size payload.atime = stats.st_atime payload.mtime = stats.st_mtime payload.ctime = stats.st_ctime idx += 1 self.db.store(payload)
'Build a in-memory data of all managed files.'
def _get_managed_files(self):
if (self.grains_core.os_data().get('os_family') == 'Debian'): return self.__get_managed_files_dpkg() elif (self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']): return self.__get_managed_files_rpm() return (list(), list(), list())
'Get a list of all system files, belonging to the Debian package manager.'
def __get_managed_files_dpkg(self):
dirs = set() links = set() files = set() for pkg_name in salt.utils.stringutils.to_str(self._syscall('dpkg-query', None, None, '-Wf', '${binary:Package}\\n')[0]).split(os.linesep): pkg_name = pkg_name.strip() if (not pkg_name): continue for resource in salt.utils.stringutils.to_str(self._syscall('dpkg', None, None, '-L', pkg_name)[0]).split(os.linesep): resource = resource.strip() if ((not resource) or (resource in ['/', './', '.'])): continue if os.path.isdir(resource): dirs.add(resource) elif os.path.islink(resource): links.add(resource) elif os.path.isfile(resource): files.add(resource) return (sorted(files), sorted(dirs), sorted(links))
'Get a list of all system files, belonging to the RedHat package manager.'
def __get_managed_files_rpm(self):
dirs = set() links = set() files = set() for line in salt.utils.stringutils.to_str(self._syscall('rpm', None, None, '-qlav')[0]).split(os.linesep): line = line.strip() if (not line): continue line = line.replace(' DCTB ', ' ').split(' ') if (line[0][0] == 'd'): dirs.add(line[(-1)]) elif (line[0][0] == 'l'): links.add(line[(-1)]) elif (line[0][0] == '-'): files.add(line[(-1)]) return (sorted(files), sorted(dirs), sorted(links))
'Walk implementation. Version in python 2.x and 3.x works differently.'
def _get_all_files(self, path, *exclude):
files = list() dirs = list() links = list() if os.access(path, os.R_OK): for obj in os.listdir(path): obj = os.path.join(path, obj) valid = True for ex_obj in exclude: if obj.startswith(str(ex_obj)): valid = False continue if ((not valid) or (not os.path.exists(obj)) or (not os.access(obj, os.R_OK))): continue if os.path.islink(obj): links.append(obj) elif os.path.isdir(obj): dirs.append(obj) (f_obj, d_obj, l_obj) = self._get_all_files(obj, *exclude) files.extend(f_obj) dirs.extend(d_obj) links.extend(l_obj) elif os.path.isfile(obj): files.append(obj) return (sorted(files), sorted(dirs), sorted(links))
'Get the intersection between all files and managed files.'
def _get_unmanaged_files(self, managed, system_all):
(m_files, m_dirs, m_links) = managed (s_files, s_dirs, s_links) = system_all return (sorted(list(set(s_files).difference(m_files))), sorted(list(set(s_dirs).difference(m_dirs))), sorted(list(set(s_links).difference(m_links))))
'Scan the system.'
def _scan_payload(self):
allowed = list() for allowed_dir in self.db.get(AllowedDir): if os.path.exists(allowed_dir.path): allowed.append(allowed_dir.path) ignored = list() if (not allowed): for ignored_dir in self.db.get(IgnoredDir): if os.path.exists(ignored_dir.path): ignored.append(ignored_dir.path) all_files = list() all_dirs = list() all_links = list() for entry_path in [pth for pth in (allowed or os.listdir('/')) if pth]: if (entry_path[0] != '/'): entry_path = '/{0}'.format(entry_path) if ((entry_path in ignored) or os.path.islink(entry_path)): continue (e_files, e_dirs, e_links) = self._get_all_files(entry_path, *ignored) all_files.extend(e_files) all_dirs.extend(e_dirs) all_links.extend(e_links) return self._get_unmanaged_files(self._get_managed_files(), (all_files, all_dirs, all_links))
'Prepare full system scan by setting up the database etc.'
def _prepare_full_scan(self, **kwargs):
self.db.open(new=True) ignored_fs = set() ignored_fs |= set(self.IGNORE_PATHS) mounts = salt.utils.fsutils._get_mounts() for (device, data) in mounts.items(): if (device in self.IGNORE_MOUNTS): for mpt in data: ignored_fs.add(mpt['mount_point']) continue for mpt in data: if (mpt['type'] in self.IGNORE_FS_TYPES): ignored_fs.add(mpt['mount_point']) ignored_all = list() for entry in sorted(list(ignored_fs)): valid = True for e_entry in ignored_all: if entry.startswith(e_entry): valid = False break if valid: ignored_all.append(entry) for ignored_dir in ignored_all: dir_obj = IgnoredDir() dir_obj.path = ignored_dir self.db.store(dir_obj) allowed = [elm for elm in kwargs.get('filter', '').split(',') if elm] for allowed_dir in allowed: dir_obj = AllowedDir() dir_obj.path = allowed_dir self.db.store(dir_obj) return ignored_all
'Initialize some Salt environment.'
def _init_env(self):
from salt.config import minion_config from salt.grains import core as g_core g_core.__opts__ = minion_config(self.DEFAULT_MINION_CONFIG_PATH) self.grains_core = g_core
'Take a snapshot of the system.'
def snapshot(self, mode):
self._init_env() self._save_cfg_packages(self._get_changed_cfg_pkgs(self._get_cfg_pkgs())) self._save_payload(*self._scan_payload())
'Take a snapshot of the system.'
def request_snapshot(self, mode, priority=19, **kwargs):
if (mode not in self.MODE): raise InspectorSnapshotException("Unknown mode: '{0}'".format(mode)) if is_alive(self.pidfile): raise CommandExecutionError('Inspection already in progress.') self._prepare_full_scan(**kwargs) os.system('nice -{0} python {1} {2} {3} {4} & > /dev/null'.format(priority, __file__, os.path.dirname(self.pidfile), os.path.dirname(self.dbfile), mode))
'Export description for Kiwi. :param local: :param path: :return:'
def export(self, description, local=False, path='/tmp', format='qcow2'):
kiwiproc.__salt__ = __salt__ return kiwiproc.KiwiExporter(grains=__grains__, format=format).load(**description).export('something')
'Build an image using Kiwi. :param format: :param path: :return:'
def build(self, format='qcow2', path='/tmp'):
if (kiwi is None): msg = 'Unable to build the image due to the missing dependencies: Kiwi module is not available.' log.error(msg) raise CommandExecutionError(msg) raise CommandExecutionError('Build is not yet implemented')
'returns the bit value of the string object type'
def getObjectTypeBit(self, t):
if isinstance(t, string_types): t = t.upper() try: return self.objectType[t] except KeyError: raise CommandExecutionError('Invalid object type "{0}". It should be one of the following: {1}'.format(t, ', '.join(self.objectType))) else: return t
'returns the necessary string value for an HKEY for the win32security module'
def getSecurityHkey(self, s):
try: return self.hkeys_security[s] except KeyError: raise CommandExecutionError('No HKEY named "{0}". It should be one of the following: {1}'.format(s, ', '.join(self.hkeys_security)))
'returns a permission bit of the string permission value for the specified object type'
def getPermissionBit(self, t, m):
try: if isinstance(m, string_types): return self.rights[t][m]['BITS'] else: return m except KeyError: raise CommandExecutionError('No right "{0}". It should be one of the following: {1}'.format(m, ', '.join(self.rights[t])))
'returns the permission textual representation of a specified permission bit/object type'
def getPermissionText(self, t, m):
try: return self.rights[t][m]['TEXT'] except KeyError: raise CommandExecutionError('No right "{0}". It should be one of the following: {1}'.format(m, ', '.join(self.rights[t])))
'returns the acetype bit of a text value'
def getAceTypeBit(self, t):
try: return self.validAceTypes[t]['BITS'] except KeyError: raise CommandExecutionError('No ACE type "{0}". It should be one of the following: {1}'.format(t, ', '.join(self.validAceTypes)))
'returns the textual representation of a acetype bit'
def getAceTypeText(self, t):
try: return self.validAceTypes[t]['TEXT'] except KeyError: raise CommandExecutionError('No ACE type "{0}". It should be one of the following: {1}'.format(t, ', '.join(self.validAceTypes)))
'returns the propagation bit of a text value'
def getPropagationBit(self, t, p):
try: return self.validPropagations[t][p]['BITS'] except KeyError: raise CommandExecutionError('No propagation type of "{0}". It should be one of the following: {1}'.format(p, ', '.join(self.validPropagations[t])))
'returns the textual representation of a propagation bit'
def getPropagationText(self, t, p):
try: return self.validPropagations[t][p]['TEXT'] except KeyError: raise CommandExecutionError('No propagation type of "{0}". It should be one of the following: {1}'.format(p, ', '.join(self.validPropagations[t])))
'processes a path/object type combo and returns: registry types with the correct HKEY text representation files/directories with environment variables expanded'
def processPath(self, path, objectType):
if (objectType == win32security.SE_REGISTRY_KEY): splt = path.split('\\') hive = self.getSecurityHkey(splt.pop(0).upper()) splt.insert(0, hive) path = '\\\\'.join(splt) else: path = os.path.expandvars(path) return path
'Removes parameters which match the pattern from the config data'
def _filter_data(self, pattern):
removed = [] filtered = [] for param in self.data: if (not param[0].startswith(pattern)): filtered.append(param) else: removed.append(param) self.data = filtered return removed
'Bind to an LDAP directory using passed credentials.'
def __init__(self, uri, server, port, tls, no_verify, binddn, bindpw, anonymous):
self.uri = uri self.server = server self.port = port self.tls = tls self.binddn = binddn self.bindpw = bindpw if (self.uri == ''): self.uri = 'ldap://{0}:{1}'.format(self.server, self.port) try: if no_verify: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) self.ldap = ldap.initialize('{0}'.format(self.uri)) self.ldap.protocol_version = 3 self.ldap.set_option(ldap.OPT_REFERRALS, 0) if self.tls: self.ldap.start_tls_s() if (not anonymous): self.ldap.simple_bind_s(self.binddn, self.bindpw) except Exception as ldap_error: raise CommandExecutionError('Failed to bind to LDAP server {0} as {1}: {2}'.format(self.uri, self.binddn, ldap_error))
'Setup a puppet instance, based on the premis that default usage is to run \'puppet agent --test\'. Configuration and run states are stored in the default locations.'
def __init__(self):
self.subcmd = 'agent' self.subcmd_args = [] self.kwargs = {'color': 'false'} self.args = [] if salt.utils.platform.is_windows(): self.vardir = 'C:\\ProgramData\\PuppetLabs\\puppet\\var' self.rundir = 'C:\\ProgramData\\PuppetLabs\\puppet\\run' self.confdir = 'C:\\ProgramData\\PuppetLabs\\puppet\\etc' self.useshell = True else: self.useshell = False self.puppet_version = __salt__['cmd.run']('puppet --version') if ('Enterprise' in self.puppet_version): self.vardir = '/var/opt/lib/pe-puppet' self.rundir = '/var/opt/run/pe-puppet' self.confdir = '/etc/puppetlabs/puppet' elif ((self.puppet_version != []) and (version.StrictVersion(self.puppet_version) >= version.StrictVersion('4.0.0'))): self.vardir = '/opt/puppetlabs/puppet/cache' self.rundir = '/var/run/puppetlabs' self.confdir = '/etc/puppetlabs/puppet' else: self.vardir = '/var/lib/puppet' self.rundir = '/var/run/puppet' self.confdir = '/etc/puppet' self.disabled_lockfile = (self.vardir + '/state/agent_disabled.lock') self.run_lockfile = (self.vardir + '/state/agent_catalog_run.lock') self.agent_pidfile = (self.rundir + '/agent.pid') self.lastrunfile = (self.vardir + '/state/last_run_summary.yaml')
'Format the command string to executed using cmd.run_all.'
def __repr__(self):
cmd = 'puppet {subcmd} --vardir {vardir} --confdir {confdir}'.format(**self.__dict__) args = ' '.join(self.subcmd_args) args += ''.join([' --{0}'.format(k) for k in self.args]) args += ''.join([' --{0} {1}'.format(k, v) for (k, v) in six.iteritems(self.kwargs)]) return '{0} {1}'.format(cmd, args)
'Read in arguments for the current subcommand. These are added to the cmd line without \'--\' appended. Any others are redirected as standard options with the double hyphen prefixed.'
def arguments(self, args=None):
args = ((args and list(args)) or []) if (self.subcmd == 'apply'): self.subcmd_args = [args[0]] del args[0] if (self.subcmd == 'agent'): args.extend(['test']) self.args = args
'ensures a value is not empty'
@classmethod def _notEmpty(cls, val, **kwargs):
if val: return True else: return False
'converts a number of seconds to days'
@classmethod def _seconds_to_days(cls, val, **kwargs):
if (val is not None): return (val / 86400) else: return 'Not Defined'
'converts a number of days to seconds'
@classmethod def _days_to_seconds(cls, val, **kwargs):
if (val is not None): return (val * 86400) else: return 'Not Defined'
'converts a number of seconds to minutes'
@classmethod def _seconds_to_minutes(cls, val, **kwargs):
if (val is not None): return (val / 60) else: return 'Not Defined'
'converts number of minutes to seconds'
@classmethod def _minutes_to_seconds(cls, val, **kwargs):
if (val is not None): return (val * 60) else: return 'Not Defined'
'strips quotes from a string'
@classmethod def _strip_quotes(cls, val, **kwargs):
return val.replace('"', '')
'add quotes around the string'
@classmethod def _add_quotes(cls, val, **kwargs):
return '"{0}"'.format(val)
'converts a binary 0/1 to Disabled/Enabled'
@classmethod def _binary_enable_zero_disable_one_conversion(cls, val, **kwargs):
if (val is not None): if (ord(val) == 0): return 'Disabled' elif (ord(val) == 1): return 'Enabled' else: return 'Invalid Value' else: return 'Not Defined'
'converts Enabled/Disabled to unicode char to write to a REG_BINARY value'
@classmethod def _binary_enable_zero_disable_one_reverse_conversion(cls, val, **kwargs):
if (val is not None): if (val.upper() == 'DISABLED'): return chr(0) elif (val.upper() == 'ENABLED'): return chr(1) else: return None else: return None
'converts 0/1/2 for dasd reg key'
@classmethod def _dasd_conversion(cls, val, **kwargs):
if (val is not None): if ((val == '0') or (val == 0) or (val == '')): return 'Administrators' elif ((val == '1') or (val == 1)): return 'Administrators and Power Users' elif ((val == '2') or (val == 2)): return 'Administrators and Interactive Users' else: return 'Not Defined' else: return 'Not Defined'
'converts DASD String values to the reg_sz value'
@classmethod def _dasd_reverse_conversion(cls, val, **kwargs):
if (val is not None): if (val.upper() == 'ADMINISTRATORS'): return '0' elif (val.upper() == 'ADMINISTRATORS AND POWER USERS'): return '1' elif (val.upper() == 'ADMINISTRATORS AND INTERACTIVE USERS'): return '2' elif (val.upper() == 'NOT DEFINED'): return '9999' else: return 'Invalid Value' else: return 'Not Defined'
'checks that a value is in an inclusive range'
@classmethod def _in_range_inclusive(cls, val, **kwargs):
minimum = 0 maximum = 1 if isinstance(val, six.string_types): if (val.lower() == 'not defined'): return True else: try: val = int(val) except ValueError: return False if ('min' in kwargs): minimum = kwargs['min'] if ('max' in kwargs): maximum = kwargs['max'] if (val is not None): if ((val >= minimum) and (val <= maximum)): return True else: return False else: return False
'converts the binary value in the registry for driver signing into the correct string representation'
@classmethod def _driver_signing_reg_conversion(cls, val, **kwargs):
log.debug('we have {0} for the driver signing value'.format(val)) if (val is not None): _val = val.split(',') if (len(_val) == 2): if (_val[1] == '0'): return 'Silently Succeed' elif (_val[1] == '1'): return 'Warn but allow installation' elif (_val[1] == '2'): return 'Do not allow installation' elif (_val[1] == 'Not Defined'): return 'Not Defined' else: return 'Invalid Value' else: return 'Not Defined' else: return 'Not Defined'
'converts the string value seen in the GUI to the correct registry value for secedit'
@classmethod def _driver_signing_reg_reverse_conversion(cls, val, **kwargs):
if (val is not None): if (val.upper() == 'SILENTLY SUCCEED'): return ','.join(['3', '0']) elif (val.upper() == 'WARN BUT ALLOW INSTALLATION'): return ','.join(['3', chr(1)]) elif (val.upper() == 'DO NOT ALLOW INSTALLATION'): return ','.join(['3', chr(2)]) else: return 'Invalid Value' else: return 'Not Defined'
'converts a list of pysid objects to string representations'
@classmethod def _sidConversion(cls, val, **kwargs):
if isinstance(val, six.string_types): val = val.split(',') usernames = [] for _sid in val: try: userSid = win32security.LookupAccountSid('', _sid) if userSid[1]: userSid = '{1}\\{0}'.format(userSid[0], userSid[1]) else: userSid = '{0}'.format(userSid[0]) except Exception: userSid = win32security.ConvertSidToStringSid(_sid) usernames.append(userSid) return usernames
'converts a list of usernames to sid objects'
@classmethod def _usernamesToSidObjects(cls, val, **kwargs):
if (not val): return val if isinstance(val, six.string_types): val = val.split(',') sids = [] for _user in val: try: sid = win32security.LookupAccountName('', _user)[0] sids.append(sid) except Exception as e: raise CommandExecutionError('There was an error obtaining the SID of user "{0}". Error returned: {1}'.format(_user, e)) return sids
'converts true/false/None to the GUI representation of the powershell startup/shutdown script order'
@classmethod def _powershell_script_order_conversion(cls, val, **kwargs):
log.debug('script order value = {0}'.format(val)) if ((val is None) or (val == 'None')): return 'Not Configured' elif (val == 'true'): return 'Run Windows PowerShell scripts first' elif (val == 'false'): return 'Run Windows PowerShell scripts last' else: return 'Invalid Value'
'converts powershell script GUI strings representations to True/False/None'
@classmethod def _powershell_script_order_reverse_conversion(cls, val, **kwargs):
if (val.upper() == 'Run Windows PowerShell scripts first'.upper()): return 'true' elif (val.upper() == 'Run Windows PowerShell scripts last'.upper()): return 'false' elif (val is 'Not Configured'): return None else: return 'Invalid Value'
'Retrieves the key or value from a dict based on the item kwarg lookup dict to search for item kwarg value_lookup bool to determine if item should be compared to keys or values'
@classmethod def _dict_lookup(cls, item, **kwargs):
log.debug('item == {0}'.format(item)) value_lookup = False if ('value_lookup' in kwargs): value_lookup = kwargs['value_lookup'] else: value_lookup = False if ('lookup' in kwargs): for (k, v) in six.iteritems(kwargs['lookup']): if value_lookup: if (str(v).lower() == str(item).lower()): log.debug('returning key {0}'.format(k)) return k elif (str(k).lower() == str(item).lower()): log.debug('returning value {0}'.format(v)) return v return 'Invalid Value'
'Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451)'
def is_package(self, fullname):
return hasattr(self.__get_module(fullname), '__path__')
'Return None Required, if is_package is implemented'
def get_code(self, fullname):
self.__get_module(fullname) return None
'Return the longhand version of the IP address as a string.'
@property def exploded(self):
return self._explode_shorthand_ip_string()
'Return the shorthand version of the IP address as a string.'
@property def compressed(self):
return str(self)
'The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer \'1.0.0.127.in-addr.arpa\' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer \'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa\''
@property def reverse_pointer(self):
return self._reverse_pointer()
'Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer.'
def _ip_int_from_prefix(self, prefixlen):
return (self._ALL_ONES ^ (self._ALL_ONES >> prefixlen))
'Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones'
def _prefix_from_ip_int(self, ip_int):
trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = (self._max_prefixlen - trailing_zeroes) leading_ones = (ip_int >> trailing_zeroes) all_ones = ((1 << prefixlen) - 1) if (leading_ones != all_ones): byteslen = (self._max_prefixlen // 8) details = _int_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError((msg % details)) return prefixlen
'Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask'
def _prefix_from_prefix_string(self, prefixlen_str):
if (not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str)): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if (not (0 <= prefixlen <= self._max_prefixlen)): self._report_invalid_netmask(prefixlen_str) return prefixlen
'Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask'
def _prefix_from_ip_string(self, ip_str):
try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) try: return self._prefix_from_ip_int(ip_int) except ValueError: pass ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str)
'Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn\'t return the network or broadcast addresses.'
def hosts(self):
network = int(self.network_address) broadcast = int(self.broadcast_address) for x in long_range((network + 1), broadcast): (yield self._address_class(x))
'Tell if self is partly contained in other.'
def overlaps(self, other):
return ((self.network_address in other) or ((self.broadcast_address in other) or ((other.network_address in self) or (other.broadcast_address in self))))
'Number of hosts in the current subnet.'
@property def num_addresses(self):
return ((int(self.broadcast_address) - int(self.network_address)) + 1)
'Remove an address from a larger block. For example: addr1 = ip_network(\'192.0.2.0/28\') addr2 = ip_network(\'192.0.2.1/32\') addr1.address_exclude(addr2) = [IPv4Network(\'192.0.2.0/32\'), IPv4Network(\'192.0.2.2/31\'), IPv4Network(\'192.0.2.4/30\'), IPv4Network(\'192.0.2.8/29\')] or IPv6: addr1 = ip_network(\'2001:db8::1/32\') addr2 = ip_network(\'2001:db8::1/128\') addr1.address_exclude(addr2) = [ip_network(\'2001:db8::1/128\'), ip_network(\'2001:db8::2/127\'), ip_network(\'2001:db8::4/126\'), ip_network(\'2001:db8::8/125\'), ip_network(\'2001:db8:8000::/33\')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self.'
def address_exclude(self, other):
if (not (self._version == other._version)): raise TypeError(('%s and %s are not of the same version' % (self, other))) if (not isinstance(other, _BaseNetwork)): raise TypeError(('%s is not a network object' % other)) if (not ((other.network_address >= self.network_address) and (other.broadcast_address <= self.broadcast_address))): raise ValueError(('%s not contained in %s' % (other, self))) if (other == self): raise StopIteration other = other.__class__(('%s/%s' % (other.network_address, other.prefixlen))) (s1, s2) = self.subnets() while ((s1 != other) and (s2 != other)): if ((other.network_address >= s1.network_address) and (other.broadcast_address <= s1.broadcast_address)): (yield s2) (s1, s2) = s1.subnets() elif ((other.network_address >= s2.network_address) and (other.broadcast_address <= s2.broadcast_address)): (yield s1) (s1, s2) = s2.subnets() else: raise AssertionError(('Error performing exclusion: s1: %s s2: %s other: %s' % (s1, s2, other))) if (s1 == other): (yield s2) elif (s2 == other): (yield s1) else: raise AssertionError(('Error performing exclusion: s1: %s s2: %s other: %s' % (s1, s2, other)))
'Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren\'t considered at all in this method. If you want to compare host bits, you can easily enough do a \'HostA._ip < HostB._ip\' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network(\'192.0.2.0/25\') < IPv4Network(\'192.0.2.128/25\') IPv6Network(\'2001:db8::1000/124\') < IPv6Network(\'2001:db8::2000/124\') 0 if self == other eg: IPv4Network(\'192.0.2.0/24\') == IPv4Network(\'192.0.2.0/24\') IPv6Network(\'2001:db8::1000/124\') == IPv6Network(\'2001:db8::1000/124\') 1 if self > other eg: IPv4Network(\'192.0.2.128/25\') > IPv4Network(\'192.0.2.0/25\') IPv6Network(\'2001:db8::2000/124\') > IPv6Network(\'2001:db8::1000/124\') Raises: TypeError if the IP versions are different.'
def compare_networks(self, other):
if (self._version != other._version): raise TypeError(('%s and %s are not of the same type' % (self, other))) if (self.network_address < other.network_address): return (-1) if (self.network_address > other.network_address): return 1 if (self.netmask < other.netmask): return (-1) if (self.netmask > other.netmask): return 1 return 0
'Network-only key function. Returns an object that identifies this address\' network and netmask. This function is a suitable "key" argument for sorted() and list.sort().'
def _get_networks_key(self):
return (self._version, self.network_address, self.netmask)
'The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network)'
def subnets(self, prefixlen_diff=1, new_prefix=None):
if (self._prefixlen == self._max_prefixlen): (yield self) return if (new_prefix is not None): if (new_prefix < self._prefixlen): raise ValueError('new prefix must be longer') if (prefixlen_diff != 1): raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = (new_prefix - self._prefixlen) if (prefixlen_diff < 0): raise ValueError('prefix length diff must be > 0') new_prefixlen = (self._prefixlen + prefixlen_diff) if (new_prefixlen > self._max_prefixlen): raise ValueError(('prefix length diff %d is invalid for netblock %s' % (new_prefixlen, self))) first = self.__class__(('%s/%s' % (self.network_address, (self._prefixlen + prefixlen_diff)))) (yield first) current = first while True: broadcast = current.broadcast_address if (broadcast == self.broadcast_address): return new_addr = self._address_class((int(broadcast) + 1)) current = self.__class__(('%s/%s' % (new_addr, new_prefixlen))) (yield current)
'The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network)'
def supernet(self, prefixlen_diff=1, new_prefix=None):
if (self._prefixlen == 0): return self if (new_prefix is not None): if (new_prefix > self._prefixlen): raise ValueError('new prefix must be shorter') if (prefixlen_diff != 1): raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = (self._prefixlen - new_prefix) if ((self.prefixlen - prefixlen_diff) < 0): raise ValueError(('current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff))) t = self.__class__(('%s/%d' % (self.network_address, (self.prefixlen - prefixlen_diff))), strict=False) return t.__class__(('%s/%d' % (t.network_address, t.prefixlen)))
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details.'
@property def is_multicast(self):
return (self.network_address.is_multicast and self.broadcast_address.is_multicast)
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges.'
@property def is_reserved(self):
return (self.network_address.is_reserved and self.broadcast_address.is_reserved)
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291.'
@property def is_link_local(self):
return (self.network_address.is_link_local and self.broadcast_address.is_link_local)
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry.'
@property def is_private(self):
return (self.network_address.is_private and self.broadcast_address.is_private)
'Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry.'
@property def is_global(self):
return (not self.is_private)
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2.'
@property def is_unspecified(self):
return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified)
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3.'
@property def is_loopback(self):
return (self.network_address.is_loopback and self.broadcast_address.is_loopback)
'Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn\'t a valid IPv4 Address.'
def _ip_int_from_string(self, ip_str):
if (not ip_str): raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if (len(octets) != 4): raise AddressValueError(('Expected 4 octets in %r' % ip_str)) try: return _int_from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError(('%s in %r' % (exc, ip_str)))
'Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn\'t strictly a decimal from [0..255].'
def _parse_octet(self, octet_str):
if (not octet_str): raise ValueError('Empty octet not permitted') if (not self._DECIMAL_DIGITS.issuperset(octet_str)): msg = 'Only decimal digits permitted in %r' raise ValueError((msg % octet_str)) if (len(octet_str) > 3): msg = 'At most 3 characters permitted in %r' raise ValueError((msg % octet_str)) octet_int = int(octet_str, 10) if ((octet_int > 7) and (octet_str[0] == '0')): msg = 'Ambiguous (octal/decimal) value in %r not permitted' raise ValueError((msg % octet_str)) if (octet_int > 255): raise ValueError(('Octet %d (> 255) not permitted' % octet_int)) return octet_int
'Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation.'
def _string_from_ip_int(self, ip_int):
return '.'.join(map(str, _int_to_bytes(ip_int, 4, 'big')))
'Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask.'
def _is_valid_netmask(self, netmask):
mask = netmask.split('.') if (len(mask) == 4): try: for x in mask: if (int(x) not in self._valid_mask_octets): return False except ValueError: return False for (idx, y) in enumerate(mask): if ((idx > 0) and (y > mask[(idx - 1)])): return False return True try: netmask = int(netmask) except ValueError: return False return (0 <= netmask <= self._max_prefixlen)
'Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask.'
def _is_hostmask(self, ip_str):
bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if (x in self._valid_mask_octets)] except ValueError: return False if (len(parts) != len(bits)): return False if (parts[0] < parts[(-1)]): return True return False
'Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5.'
def _reverse_pointer(self):
reverse_octets = str(self).split('.')[::(-1)] return ('.'.join(reverse_octets) + '.in-addr.arpa')
'Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address(\'192.0.2.1\') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address(\'192.0.2.1\'))) == IPv4Address(\'192.0.2.1\') Raises: AddressValueError: If ipaddress isn\'t a valid IPv4 address.'
def __init__(self, address):
_BaseAddress.__init__(self, address) _BaseV4.__init__(self, address) if isinstance(address, int): self._check_int_address(address) self._ip = address return if isinstance(address, bytes): self._check_packed_address(address, 4) self._ip = _int_from_bytes(address, 'big') return addr_str = str(address) self._ip = self._ip_int_from_string(addr_str)
'The binary representation of this address.'
@property def packed(self):
return v4_int_to_packed(self._ip)
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range.'
@property def is_reserved(self):
reserved_network = IPv4Network('240.0.0.0/4') return (self in reserved_network)
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry.'
@property def is_private(self):
return ((self in IPv4Network('0.0.0.0/8')) or (self in IPv4Network('10.0.0.0/8')) or (self in IPv4Network('127.0.0.0/8')) or (self in IPv4Network('169.254.0.0/16')) or (self in IPv4Network('172.16.0.0/12')) or (self in IPv4Network('192.0.0.0/29')) or (self in IPv4Network('192.0.0.170/31')) or (self in IPv4Network('192.0.2.0/24')) or (self in IPv4Network('192.168.0.0/16')) or (self in IPv4Network('198.18.0.0/15')) or (self in IPv4Network('198.51.100.0/24')) or (self in IPv4Network('203.0.113.0/24')) or (self in IPv4Network('240.0.0.0/4')) or (self in IPv4Network('255.255.255.255/32')))
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details.'
@property def is_multicast(self):
multicast_network = IPv4Network('224.0.0.0/4') return (self in multicast_network)
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3.'
@property def is_unspecified(self):
unspecified_address = IPv4Address('0.0.0.0') return (self == unspecified_address)
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330.'
@property def is_loopback(self):
loopback_network = IPv4Network('127.0.0.0/8') return (self in loopback_network)
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927.'
@property def is_link_local(self):
linklocal_network = IPv4Network('169.254.0.0/16') return (self in linklocal_network)
'Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. \'192.0.2.0/24\' \'192.0.2.0/255.255.255.0\' \'192.0.0.2/0.0.0.255\' are all functionally the same in IPv4. Similarly, \'192.0.2.1\' \'192.0.2.1/255.255.255.255\' \'192.0.2.1/32\' are also functionally equivalent. That is to say, failing to provide a subnetmask will create an object with a mask of /32. If the mask (portion after the / in the argument) is given in dotted quad form, it is treated as a netmask if it starts with a non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it starts with a zero field (e.g. 0.255.255.255 == /8), with the single exception of an all-zero mask which is treated as a netmask == /0. If no mask is given, a default of /32 is used. Additionally, an integer can be passed, so IPv4Network(\'192.0.2.1\') == IPv4Network(3221225985) or, more generally IPv4Interface(int(IPv4Interface(\'192.0.2.1\'))) == IPv4Interface(\'192.0.2.1\') Raises: AddressValueError: If ipaddress isn\'t a valid IPv4 address. NetmaskValueError: If the netmask isn\'t valid for an IPv4 address. ValueError: If strict is True and a network address is not supplied.'
def __init__(self, address, strict=True):
_BaseV4.__init__(self, address) _BaseNetwork.__init__(self, address) if isinstance(address, bytes): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) return if isinstance(address, int): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) return addr = _split_optional_netmask(address) self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) if (len(addr) == 2): try: self._prefixlen = self._prefix_from_prefix_string(addr[1]) except NetmaskValueError: self._prefixlen = self._prefix_from_ip_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv4Address((int(self.network_address) & int(self.netmask))) != self.network_address): raise ValueError(('%s has host bits set' % self)) self.network_address = IPv4Address((int(self.network_address) & int(self.netmask))) if (self._prefixlen == (self._max_prefixlen - 1)): self.hosts = self.__iter__