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 e...
'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_...
'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...
'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: ...
'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): ...
'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): ...
'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.str...
'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):...
'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) ...
'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_...
'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...
'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.stri...
'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] =...
'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 ...
'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): i...
'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']) contin...
'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} {...
'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.objectTyp...
'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.O...
'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\\...
'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...
'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 Interactiv...
'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() =...
'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['mi...
'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 ...
'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 ','...
'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: user...
'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...
'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 ...
'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: ...
'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 = _i...
'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_invali...
'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) exc...
'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:db...
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 >= s...
'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...
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 < othe...
'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_pr...
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 prefixle...
'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.prefixl...
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') ...
'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 V...
'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 ch...
'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...
'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, '...
'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('...
'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...
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): sel...