docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Return the valu of a given property on the node. Args: pode (tuple): A packed node. prop (str): Property to retrieve. Notes: The prop argument may be the full property name (foo:bar:baz), relative property name (:baz) , or the unadorned property name (baz). Returns:
def prop(pode, prop): form = pode[0][0] if prop.startswith(form): prop = prop[len(form):] if prop[0] == ':': prop = prop[1:] return pode[1]['props'].get(prop)
264,873
Get all the tags for a given node. Args: pode (tuple): A packed node. leaf (bool): If True, only return the full tags. Returns: list: A list of tag strings.
def tags(pode, leaf=False): fulltags = [tag for tag in pode[1]['tags']] if not leaf: return fulltags # longest first retn = [] # brute force rather than build a tree. faster in small sets. for size, tag in sorted([(len(t), t) for t in fulltags], reverse=True): look = tag ...
264,874
Check if a packed node has a given tag. Args: pode (tuple): A packed node. tag (str): The tag to check. Examples: Check if a node is tagged with "woot" and dostuff if it is. if s_node.tagged(node,'woot'): dostuff() Notes: If the tag starts with...
def tagged(pode, tag): if tag.startswith('#'): tag = tag[1:] return pode[1]['tags'].get(tag) is not None
264,875
Set a property on the node. Args: name (str): The name of the property. valu (obj): The value of the property. init (bool): Set to True to disable read-only enforcement Returns: (bool): True if the property was changed.
async def set(self, name, valu, init=False): with s_editatom.EditAtom(self.snap.core.bldgbuids) as editatom: retn = await self._setops(name, valu, editatom, init) if not retn: return False await editatom.commit(self.snap) return True
264,883
Return a secondary property value from the Node. Args: name (str): The name of a secondary property. Returns: (obj): The secondary property value or None.
def get(self, name): if name.startswith('#'): return self.tags.get(name[1:]) return self.props.get(name)
264,885
Construct a new Type object. Args: modl (synpase.datamodel.DataModel): The data model instance. name (str): The name of the type. info (dict): The type info (docs etc). opts (dict): Options that are specific to the type.
def __init__(self, modl, name, info, opts): # these fields may be referenced by callers self.modl = modl self.name = name self.info = info self.form = None # this will reference a Form() if the type is a form self.subof = None # This references the name that a t...
264,912
Normalize the value for a given type. Args: valu (obj): The value to normalize. Returns: ((obj,dict)): The normalized valu, info tuple. Notes: The info dictionary uses the following key conventions: subs (dict): The normalized sub-fields as ...
def norm(self, valu): func = self._type_norms.get(type(valu)) if func is None: raise s_exc.NoSuchFunc(name=self.name, mesg='no norm for type: %r' % (type(valu),)) return func(valu)
264,925
Extend this type to construct a sub-type. Args: name (str): The name of the new sub-type. opts (dict): The type options for the sub-type. info (dict): The type info for the sub-type. Returns: (synapse.types.Type): A new sub-type instance.
def extend(self, name, opts, info): tifo = self.info.copy() tifo.update(info) topt = self.opts.copy() topt.update(opts) tobj = self.__class__(self.modl, name, tifo, topt) tobj.subof = self.name return tobj
264,927
Create a new instance of this type with the specified options. Args: opts (dict): The type specific options for the new instance.
def clone(self, opts): topt = self.opts.copy() topt.update(opts) return self.__class__(self.modl, self.name, self.info, topt)
264,928
Get a tick, tock time pair. Args: vals (list): A pair of values to norm. Returns: (int, int): A ordered pair of integers.
def getTickTock(self, vals): val0, val1 = vals try: _tick = self._getLiftValu(val0) except ValueError as e: raise s_exc.BadTypeValu(name=self.name, valu=val0, mesg='Unable to process the value for val0 in getTickTock.') ...
264,997
Ensure a string is valid hex. Args: text (str): String to normalize. Examples: Norm a few strings: hexstr('0xff00') hexstr('ff00') Notes: Will accept strings prefixed by '0x' or '0X' and remove them. Returns: str: Normalized hex string.
def hexstr(text): text = text.strip().lower() if text.startswith(('0x', '0X')): text = text[2:] if not text: raise s_exc.BadTypeValu(valu=text, name='hexstr', mesg='No string left after stripping') try: # checks for valid hex width and does ...
265,091
Retrieve a node tuple by binary id. Args: buid (bytes): The binary ID for the node. Returns: Optional[s_node.Node]: The node object or None.
async def getNodeByBuid(self, buid): node = self.livenodes.get(buid) if node is not None: return node props = {} proplayr = {} for layr in self.layers: layerprops = await layr.getBuidProps(buid) props.update(layerprops) pr...
265,129
Return a single Node by (form,valu) tuple. Args: ndef ((str,obj)): A (form,valu) ndef tuple. valu must be normalized. Returns: (synapse.lib.node.Node): The Node or None.
async def getNodeByNdef(self, ndef): buid = s_common.buid(ndef) return await self.getNodeByBuid(buid)
265,130
The main function for retrieving nodes by prop. Args: full (str): The property/tag name. valu (obj): A lift compatible value for the type. cmpr (str): An optional alternate comparator. Yields: (synapse.lib.node.Node): Node instances.
async def getNodesBy(self, full, valu=None, cmpr='='): if self.debug: await self.printf(f'get nodes by: {full} {cmpr} {valu!r}') # special handling for by type (*type=) here... if cmpr == '*type=': async for node in self._getNodesByType(full, valu=valu): ...
265,133
Add a node by form name and value with optional props. Args: name (str): The form of node to add. valu (obj): The value for the node. props (dict): Optional secondary properties for the node.
async def addNode(self, name, valu, props=None): try: fnib = self._getNodeFnib(name, valu) retn = await self._addNodeFnib(fnib, props=props) return retn except asyncio.CancelledError: raise except Exception: mesg = f'Error...
265,136
Call a feed function and return what it returns (typically yields Node()s). Args: name (str): The name of the feed record type. items (list): A list of records of the given feed type. Returns: (object): The return value from the feed function. Typically Node() gener...
async def addFeedNodes(self, name, items): func = self.core.getFeedFunc(name) if func is None: raise s_exc.NoSuchName(name=name) logger.info(f'adding feed nodes ({name}): {len(items)}') async for node in func(self, items): yield node
265,137
Add/merge nodes in bulk. The addNodes API is designed for bulk adds which will also set properties and add tags to existing nodes. Nodes are specified as a list of the following tuples: ( (form, valu), {'props':{}, 'tags':{}}) Args: nodedefs (list): A list of n...
async def addNodes(self, nodedefs): for (formname, formvalu), forminfo in nodedefs: props = forminfo.get('props') # remove any universal created props... if props is not None: props.pop('.created', None) node = await self.addNode(formn...
265,143
Yield row tuples from a series of lift operations. Row tuples only requirement is that the first element be the binary id of a node. Args: lops (list): A list of lift operations. Yields: (tuple): (layer_indx, (buid, ...)) rows.
async def getLiftRows(self, lops): for layeridx, layr in enumerate(self.layers): async for x in layr.getLiftRows(lops): yield layeridx, x
265,147
Construct a path relative to this module's working directory. Args: *paths: A list of path strings Notes: This creates the module specific directory if it does not exist. Returns: (str): The full path (or None if no cortex dir is configured).
def getModPath(self, *paths): dirn = self.getModDir() return s_common.genpath(dirn, *paths)
265,151
Get a Telepath Proxt to a Cortex instance which is backed by a temporary Cortex. Args: mods (list): A list of additional CoreModules to load in the Cortex. Notes: The Proxy returned by this should be fini()'d to tear down the temporary Cortex. Returns: s_telepath.Proxy
async def getTempCoreProx(mods=None): acm = genTempCoreProxy(mods) prox = await acm.__aenter__() # Use object.__setattr__ to hulk smash and avoid proxy getattr magick object.__setattr__(prox, '_acm', acm) async def onfini(): await prox._acm.__aexit__(None, None, None) prox.onfini(on...
265,187
Get a CmdrCore instance which is backed by a temporary Cortex. Args: mods (list): A list of additional CoreModules to load in the Cortex. outp: A output helper. Will be used for the Cmdr instance. Notes: The CmdrCore returned by this should be fini()'d to tear down the temporary Corte...
async def getTempCoreCmdr(mods=None, outp=None): acm = genTempCoreProxy(mods) prox = await acm.__aenter__() cmdrcore = await CmdrCore.anit(prox, outp=outp) cmdrcore.acm = acm return cmdrcore
265,188
Run a line of command input for this command. Args: line (str): Line to execute Examples: Run the foo command with some arguments: await foo.runCmdLine('foo --opt baz woot.com')
async def runCmdLine(self, line): opts = self.getCmdOpts(line) return await self.runCmdOpts(opts)
265,198
Use the _cmd_syntax def to split/parse/normalize the cmd line. Args: text (str): Command to process. Notes: This is implemented independent of argparse (et al) due to the need for syntax aware argument splitting. Also, allows different split per command ...
def getCmdOpts(self, text): off = 0 _, off = s_syntax.nom(text, off, s_syntax.whites) name, off = s_syntax.meh(text, off, s_syntax.whites) _, off = s_syntax.nom(text, off, s_syntax.whites) opts = {} args = collections.deque([synt for synt in self._cmd_syntax...
265,199
Run a single command line. Args: line (str): Line to execute. Examples: Execute the 'woot' command with the 'help' switch: await cli.runCmdLine('woot --help') Returns: object: Arbitrary data from the cmd class.
async def runCmdLine(self, line): if self.echoline: self.outp.printf(f'{self.cmdprompt}{line}') ret = None name = line.split(None, 1)[0] cmdo = self.getCmdByName(name) if cmdo is None: self.printf('cmd not found: %s' % (name,)) retu...
265,207
Generates a CA keypair. Args: name (str): The name of the CA keypair. signas (str): The CA keypair to sign the new CA with. outp (synapse.lib.output.Output): The output buffer. Examples: Make a CA named "myca": mycakey, mycacert = cdir.g...
def genCaCert(self, name, signas=None, outp=None, save=True): pkey, cert = self._genBasePkeyCert(name) ext0 = crypto.X509Extension(b'basicConstraints', False, b'CA:TRUE') cert.add_extensions([ext0]) if signas is not None: self.signCertAs(cert, signas) else: ...
265,243
Generates a user PKCS #12 archive. Please note that the resulting file will contain private key material. Args: name (str): The name of the user keypair. outp (synapse.lib.output.Output): The output buffer. Examples: Make the PKC12 object for user "myuser": ...
def genClientCert(self, name, outp=None): ucert = self.getUserCert(name) if not ucert: raise s_exc.NoSuchFile('missing User cert') cacert = self._loadCertPath(self._getCaPath(ucert)) if not cacert: raise s_exc.NoSuchFile('missing CA cert') ukey ...
265,246
Validate the PEM encoded x509 user certificate bytes and return it. Args: byts (bytes): The bytes for the User Certificate. cacerts (tuple): A tuple of OpenSSL.crypto.X509 CA Certificates. Raises: OpenSSL.crypto.X509StoreContextError: If the certificate is not valid...
def valUserCert(self, byts, cacerts=None): cert = crypto.load_certificate(crypto.FILETYPE_PEM, byts) if cacerts is None: cacerts = self.getCaCerts() store = crypto.X509Store() [store.add_cert(cacert) for cacert in cacerts] ctx = crypto.X509StoreContext(sto...
265,247
Gets the path to the CA certificate that issued a given host keypair. Args: name (str): The name of the host keypair. Examples: Get the path to the CA cert which issue the cert for "myhost": mypath = cdir.getHostCaPath('myhost') Returns: st...
def getHostCaPath(self, name): cert = self.getHostCert(name) if cert is None: return None return self._getCaPath(cert)
265,249
Gets the path to a host certificate. Args: name (str): The name of the host keypair. Examples: Get the path to the host certificate for the host "myhost": mypath = cdir.getHostCertPath('myhost') Returns: str: The path if exists.
def getHostCertPath(self, name): path = s_common.genpath(self.certdir, 'hosts', '%s.crt' % name) if not os.path.isfile(path): return None return path
265,250
Gets the path to the CA certificate that issued a given user keypair. Args: name (str): The name of the user keypair. Examples: Get the path to the CA cert which issue the cert for "myuser": mypath = cdir.getUserCaPath('myuser') Returns: st...
def getUserCaPath(self, name): cert = self.getUserCert(name) if cert is None: return None return self._getCaPath(cert)
265,251
Gets the name of the first existing user cert for a given user and host. Args: user (str): The name of the user. host (str): The name of the host. Examples: Get the name for the "myuser" user cert at "cool.vertex.link": usercertname = cdir.getUserFo...
def getUserForHost(self, user, host): for name in iterFqdnUp(host): usercert = '%s@%s' % (user, name) if self.isUserCert(usercert): return usercert
265,252
Imports certs and keys into the Synapse cert directory Args: path (str): The path of the file to be imported. mode (str): The certdir subdirectory to import the file into. Examples: Import CA certifciate 'mycoolca.crt' to the 'cas' directory. certdi...
def importFile(self, path, mode, outp=None): if not os.path.isfile(path): raise s_exc.NoSuchFile('File does not exist') fname = os.path.split(path)[1] parts = fname.rsplit('.', 1) ext = parts[1] if len(parts) is 2 else None if not ext or ext not in ('crt', ...
265,253
Checks if a CA certificate exists. Args: name (str): The name of the CA keypair. Examples: Check if the CA certificate for "myca" exists: exists = cdir.isCaCert('myca') Returns: bool: True if the certificate is present, False otherwise.
def isCaCert(self, name): crtpath = self._getPathJoin('cas', '%s.crt' % name) return os.path.isfile(crtpath)
265,254
Checks if a user client certificate (PKCS12) exists. Args: name (str): The name of the user keypair. Examples: Check if the client certificate "myuser" exists: exists = cdir.isClientCert('myuser') Returns: bool: True if the certificate is p...
def isClientCert(self, name): crtpath = self._getPathJoin('users', '%s.p12' % name) return os.path.isfile(crtpath)
265,255
Checks if a host certificate exists. Args: name (str): The name of the host keypair. Examples: Check if the host cert "myhost" exists: exists = cdir.isUserCert('myhost') Returns: bool: True if the certificate is present, False otherwise.
def isHostCert(self, name): crtpath = self._getPathJoin('hosts', '%s.crt' % name) return os.path.isfile(crtpath)
265,256
Checks if a user certificate exists. Args: name (str): The name of the user keypair. Examples: Check if the user cert "myuser" exists: exists = cdir.isUserCert('myuser') Returns: bool: True if the certificate is present, False otherwise.
def isUserCert(self, name): crtpath = self._getPathJoin('users', '%s.crt' % name) return os.path.isfile(crtpath)
265,257
Signs a certificate with a CA keypair. Args: cert (OpenSSL.crypto.X509): The certificate to sign. signas (str): The CA keypair name to sign the new keypair with. Examples: Sign a certificate with the CA "myca": cdir.signCertAs(mycert, 'myca') ...
def signCertAs(self, cert, signas): cakey = self.getCaKey(signas) if cakey is None: raise s_exc.NoCertKey('Missing .key for %s' % signas) cacert = self.getCaCert(signas) if cacert is None: raise s_exc.NoCertKey('Missing .crt for %s' % signas) cer...
265,258
Self-sign a certificate. Args: cert (OpenSSL.crypto.X509): The certificate to sign. pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate. Examples: Sign a given certificate with a given private key: cdir.selfSignCert(mycert, myoth...
def selfSignCert(self, cert, pkey): cert.set_issuer(cert.get_subject()) cert.sign(pkey, self.signing_digest)
265,260
Signs a user CSR with a CA keypair. Args: cert (OpenSSL.crypto.X509Req): The certificate signing request. signas (str): The CA keypair name to sign the CSR with. outp (synapse.lib.output.Output): The output buffer. Examples: cdir.signUserCsr(mycsr, 'myca...
def signUserCsr(self, xcsr, signas, outp=None): pkey = xcsr.get_pubkey() name = xcsr.get_subject().CN return self.genUserCert(name, csr=pkey, signas=signas, outp=outp)
265,261
Returns an ssl.SSLContext appropriate to listen on a socket Args: hostname: if None, the value from socket.gethostname is used to find the key in the servers directory. This name should match the not-suffixed part of two files ending in .key and .crt in the hosts subdirectory
def getServerSSLContext(self, hostname=None): sslctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) if hostname is None: hostname = socket.gethostname() certfile = self.getHostCertPath(hostname) if certfile is None: raise s_exc.NoCertKey('Missing ....
265,264
Compute the ECC signature for the given bytestream. Args: byts (bytes): The bytes to sign. Returns: bytes: The RSA Signature bytes.
def sign(self, byts): chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend()) hasher.update(byts) digest = hasher.finalize() return self.priv.sign(digest, c_ec.ECDSA(c_utils.Prehashed(chosen_hash)) ...
265,280
Perform a ECDH key exchange with a public key. Args: pubkey (PubKey): A PubKey to perform the ECDH with. Returns: bytes: The ECDH bytes. This is deterministic for a given pubkey and private key.
def exchange(self, pubkey): try: return self.priv.exchange(c_ec.ECDH(), pubkey.publ) except ValueError as e: raise s_exc.BadEccExchange(mesg=str(e))
265,281
Verify the signature for the given bytes using the ECC public key. Args: byts (bytes): The data bytes. sign (bytes): The signature bytes. Returns: bool: True if the data was verified, False otherwise.
def verify(self, byts, sign): try: chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend()) hasher.update(byts) digest = hasher.finalize() self.publ.verify(sign, digest, ...
265,284
Brute force the version out of a string. Args: valu (str): String to attempt to get version information for. Notes: This first attempts to parse strings using the it:semver normalization before attempting to extract version parts out of the string. Returns:...
def bruteVersionStr(self, valu): try: valu, info = self.core.model.type('it:semver').norm(valu) subs = info.get('subs') return valu, subs except s_exc.BadTypeValu: # Try doing version part extraction by noming through the string subs =...
265,303
Save a series of items to a sequence. Args: items (tuple): The series of items to save into the sequence. Returns: The index of the first item
def save(self, items): rows = [] indx = self.indx size = 0 tick = s_common.now() for item in items: byts = s_msgpack.en(item) size += len(byts) lkey = s_common.int64en(indx) indx += 1 rows.append((lkey, by...
265,331
Iterate over items in a sequence from a given offset. Args: offs (int): The offset to begin iterating from. Yields: (indx, valu): The index and valu of the item.
def iter(self, offs): startkey = s_common.int64en(offs) for lkey, lval in self.slab.scanByRange(startkey, db=self.db): indx = s_common.int64un(lkey) valu = s_msgpack.un(lval) yield indx, valu
265,334
Chop a latlong string and return (float,float). Does not perform validation on the coordinates. Args: text (str): A longitude,latitude string. Returns: (float,float): A longitude, latitude float tuple.
def latlong(text): nlat, nlon = text.split(',') return (float(nlat), float(nlon))
265,337
Determine if the given point is within dist of any of points. Args: point ((float,float)): A latitude, longitude float tuple. dist (int): A distance in mm ( base units ) points (list): A list of latitude, longitude float tuples to compare against.
def near(point, dist, points): for cmpt in points: if haversine(point, cmpt) <= dist: return True return False
265,338
Calculate the haversine distance between two points defined by (lat,lon) tuples. Args: px ((float,float)): lat/long position 1 py ((float,float)): lat/long position 2 r (float): Radius of sphere Returns: (int): Distance in mm.
def haversine(px, py, r=r_mm): lat1, lon1 = px lat2, lon2 = py dlat = math.radians(lat2 - lat1) dlon = math.radians(lon2 - lon1) lat1 = math.radians(lat1) lat2 = math.radians(lat2) a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2 c = 2 * math...
265,339
Calculate a min/max bounding box for the circle defined by lalo/dist. Args: lat (float): The latitude in degrees lon (float): The longitude in degrees dist (int): A distance in geo:dist base units (mm) Returns: (float,float,float,float): (latmin, latmax, lonmin, lonmax)
def bbox(lat, lon, dist): latr = math.radians(lat) lonr = math.radians(lon) rad = r_mm prad = rad * math.cos(latr) latd = dist / rad lond = dist / prad latmin = math.degrees(latr - latd) latmax = math.degrees(latr + latd) lonmin = math.degrees(lonr - lond) lonmax = math.d...
265,340
Fit FastText according to X, y Parameters: ---------- X : list of text each item is a text y: list each item is either a label (in multi class problem) or list of labels (in multi label problem)
def fit(self, X, y, model_filename=None): train_file = "temp.train" X = [x.replace("\n", " ") for x in X] y = [item[0] for item in y] y = [_.replace(" ", "-") for _ in y] lines = ["__label__{} , {}".format(j, i) for i, j in zip(X, y)] content = "\n".join(lines) ...
265,689
Gets result ids and generates each result set from the batch and returns it as an generator fetching the next result set when needed Args: batch_id: id of batch job_id: id of job, if not provided, it will be looked up
def get_all_results_for_query_batch(self, batch_id, job_id=None, chunk_size=2048): result_ids = self.get_query_batch_result_ids(batch_id, job_id=job_id) if not result_ids: raise RuntimeError('Batch is not complete') for result_id in result_ids: yield self.get_que...
265,965
Returns the VRF configuration as a resource dict. Args: value (string): The vrf name to retrieve from the running configuration. Returns: A Python dict object containing the VRF attributes as key/value pairs.
def get(self, value): config = self.get_block('vrf definition %s' % value) if not config: return None response = dict(vrf_name=value) response.update(self._parse_rd(config)) response.update(self._parse_description(config)) config = self.get_block('no ...
266,191
_parse_rd scans the provided configuration block and extracts the vrf rd. The return dict is intended to be merged into the response dict. Args: config (str): The vrf configuration block from the nodes running configuration Returns: dict: resourc...
def _parse_rd(self, config): match = RD_RE.search(config) if match: value = match.group('value') else: value = match return dict(rd=value)
266,192
_parse_description scans the provided configuration block and extracts the vrf description value. The return dict is intended to be merged into the response dict. Args: config (str): The vrf configuration block from the nodes running configuration Returns: ...
def _parse_description(self, config): value = DESCRIPTION_RE.search(config).group('value') return dict(description=value)
266,193
Configures the specified VRF using commands Args: vrf_name (str): The VRF name to configure commands: The list of commands to configure Returns: True if the commands completed successfully
def configure_vrf(self, vrf_name, commands): commands = make_iterable(commands) commands.insert(0, 'vrf definition %s' % vrf_name) return self.configure(commands)
266,196
Configures the VRF description Args: vrf_name (str): The VRF name to configure description(str): The string to set the vrf description to default (bool): Configures the vrf description to its default value disable (bool): Negates the vrf description Retu...
def set_description(self, vrf_name, description=None, default=False, disable=False): cmds = self.command_builder('description', value=description, default=default, disable=disable) return self.configure_vrf(vrf_name, cmds)
266,198
Configures ipv4 routing for the vrf Args: vrf_name (str): The VRF name to configure default (bool): Configures ipv4 routing for the vrf value to default if this value is true disable (bool): Negates the ipv4 routing for the vrf if set to true Returns...
def set_ipv4_routing(self, vrf_name, default=False, disable=False): cmd = 'ip routing vrf %s' % vrf_name if default: cmd = 'default %s' % cmd elif disable: cmd = 'no %s' % cmd cmd = make_iterable(cmd) return self.configure(cmd)
266,199
Get the vrrp configurations for a single node interface Args: name (string): The name of the interface for which vrrp configurations will be retrieved. Returns: A dictionary containing the vrrp configurations on the interface. Returns None if no vrrp...
def get(self, name): # Validate the interface and vrid are specified interface = name if not interface: raise ValueError("Vrrp.get(): interface must contain a value.") # Get the config for the interface. Return None if the # interface is not defined ...
266,201
Converts a prefix length to a dotted decimal subnet mask Args: prefixlen (str): The prefix length value to convert Returns: str: The subt mask as a dotted decimal string
def prefixlen_to_mask(prefixlen): prefixlen = prefixlen or '32' addr = '0.0.0.0/%s' % prefixlen return str(netaddr.IPNetwork(addr).netmask)
266,229
Scans the config block and parses the domain-id value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict
def _parse_domain_id(self, config): match = re.search(r'domain-id (.+)$', config) value = match.group(1) if match else None return dict(domain_id=value)
266,244
Scans the config block and parses the local-interface value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict
def _parse_local_interface(self, config): match = re.search(r'local-interface (\w+)', config) value = match.group(1) if match else None return dict(local_interface=value)
266,245
Scans the config block and parses the peer-address value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict
def _parse_peer_address(self, config): match = re.search(r'peer-address ([^\s]+)', config) value = match.group(1) if match else None return dict(peer_address=value)
266,246
Scans the config block and parses the peer-link value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict
def _parse_peer_link(self, config): match = re.search(r'peer-link (\S+)', config) value = match.group(1) if match else None return dict(peer_link=value)
266,247
Configures the mlag domain-id value Args: value (str): The value to configure the domain-id default (bool): Configures the domain-id using the default keyword disable (bool): Negates the domain-id using the no keyword Returns: bool: Returns True if the c...
def set_domain_id(self, value=None, default=False, disable=False): return self._configure_mlag('domain-id', value, default, disable)
266,250
Configures the mlag local-interface value Args: value (str): The value to configure the local-interface default (bool): Configures the local-interface using the default keyword disable (bool): Negates the local-interface using the no keyword Returns:...
def set_local_interface(self, value=None, default=False, disable=False): return self._configure_mlag('local-interface', value, default, disable)
266,251
Configures the mlag peer-address value Args: value (str): The value to configure the peer-address default (bool): Configures the peer-address using the default keyword disable (bool): Negates the peer-address using the no keyword Returns: ...
def set_peer_address(self, value=None, default=False, disable=False): return self._configure_mlag('peer-address', value, default, disable)
266,252
Configures the mlag peer-link value Args: value (str): The value to configure the peer-link default (bool): Configures the peer-link using the default keyword disable (bool): Negates the peer-link using the no keyword Returns: bool: Retur...
def set_peer_link(self, value=None, default=False, disable=False): return self._configure_mlag('peer-link', value, default, disable)
266,253
Configures the mlag shutdown value Default setting for set_shutdown is disable=True, meaning 'no shutdown'. Setting both default and disable to False will effectively enable shutdown. Args: default (bool): Configures the shutdown using the default keyword ...
def set_shutdown(self, default=False, disable=True): return self._configure_mlag('shutdown', True, default, disable)
266,254
Parses config file for the OSPF proc ID Args: config(str): Running configuration Returns: dict: key: ospf_process_id (int)
def _parse_ospf_process_id(self, config): match = re.search(r'^router ospf (\d+)', config) return dict(ospf_process_id=int(match.group(1)))
266,289
Parses config file for the OSPF vrf name Args: config(str): Running configuration Returns: dict: key: ospf_vrf (str)
def _parse_vrf(self, config): match = re.search(r'^router ospf \d+ vrf (\w+)', config) if match: return dict(vrf=match.group(1)) return dict(vrf='default')
266,290
Parses config file for the networks advertised by the OSPF process Args: config(str): Running configuration Returns: list: dict: keys: network (str) netmask (str) area ...
def _parse_networks(self, config): networks = list() regexp = r'network (.+)/(\d+) area (\d+\.\d+\.\d+\.\d+)' matches = re.findall(regexp, config) for (network, netmask, area) in matches: networks.append(dict(network=network, netmask=netmask, area=area)) ret...
266,291
Parses config file for the OSPF router ID Args: config (str): Running configuration Returns: list: dict: keys: protocol (str) route-map (optional) (str)
def _parse_redistribution(self, config): redistributions = list() regexp = r'redistribute .*' matches = re.findall(regexp, config) for line in matches: ospf_redist = line.split() if len(ospf_redist) == 2: # simple redist: eg 'redistribute ...
266,292
Removes the entire ospf process from the running configuration Args: None Returns: bool: True if the command completed succssfully
def delete(self): config = self.get() if not config: return True command = 'no router ospf {}'.format(config['ospf_process_id']) return self.configure(command)
266,293
Creates a OSPF process in the specified VRF or the default VRF. Args: ospf_process_id (str): The OSPF process Id value vrf (str): The VRF to apply this OSPF process to Returns: bool: True if the command completed successfully Exception: ...
def create(self, ospf_process_id, vrf=None): value = int(ospf_process_id) if not 0 < value < 65536: raise ValueError('ospf as must be between 1 and 65535') command = 'router ospf {}'.format(ospf_process_id) if vrf: command += ' vrf %s' % vrf retur...
266,294
Allows for a list of OSPF subcommands to be configured" Args: cmd: (list or str): Subcommand to be entered Returns: bool: True if all the commands completed successfully
def configure_ospf(self, cmd): config = self.get() cmds = ['router ospf {}'.format(config['ospf_process_id'])] cmds.extend(make_iterable(cmd)) return super(Ospf, self).configure(cmds)
266,295
Controls the router id property for the OSPF Proccess Args: value (str): The router-id value default (bool): Controls the use of the default keyword disable (bool): Controls the use of the no keyword Returns: bool: True if the commands a...
def set_router_id(self, value=None, default=False, disable=False): cmd = self.command_builder('router-id', value=value, default=default, disable=disable) return self.configure_ospf(cmd)
266,296
Adds a protocol redistribution to OSPF Args: protocol (str): protocol to redistribute route_map_name (str): route-map to be used to filter the protocols Returns: bool: True if the command completes successfully ...
def add_redistribution(self, protocol, route_map_name=None): protocols = ['bgp', 'rip', 'static', 'connected'] if protocol not in protocols: raise ValueError('redistributed protocol must be' 'bgp, connected, rip or static') if route_map_name is N...
266,298
Removes a protocol redistribution to OSPF Args: protocol (str): protocol to redistribute route_map_name (str): route-map to be used to filter the protocols Returns: bool: True if the command completes successfully ...
def remove_redistribution(self, protocol): protocols = ['bgp', 'rip', 'static', 'connected'] if protocol not in protocols: raise ValueError('redistributed protocol must be' 'bgp, connected, rip or static') cmd = 'no redistribute {}'.format(proto...
266,299
Returns the VLAN configuration as a resource dict. Args: vid (string): The vlan identifier to retrieve from the running configuration. Valid values are in the range of 1 to 4095 Returns: A Python dict object containing the VLAN attributes as ...
def get(self, value): config = self.get_block('vlan %s' % value) if not config: return None response = dict(vlan_id=value) response.update(self._parse_name(config)) response.update(self._parse_state(config)) response.update(self._parse_trunk_groups(c...
266,308
_parse_name scans the provided configuration block and extracts the vlan name. The config block is expected to always return the vlan name. The return dict is intended to be merged into the response dict. Args: config (str): The vlan configuration block from the nodes runn...
def _parse_name(self, config): value = NAME_RE.search(config).group('value') return dict(name=value)
266,309
_parse_state scans the provided configuration block and extracts the vlan state value. The config block is expected to always return the vlan state config. The return dict is inteded to be merged into the response dict. Args: config (str): The vlan configuration block from...
def _parse_state(self, config): value = STATE_RE.search(config).group('value') return dict(state=value)
266,310
_parse_trunk_groups scans the provided configuration block and extracts all the vlan trunk groups. If no trunk groups are configured an empty List is returned as the vlaue. The return dict is intended to be merged into the response dict. Args: config (str): The vlan config...
def _parse_trunk_groups(self, config): values = TRUNK_GROUP_RE.findall(config) return dict(trunk_groups=values)
266,311
Creates a new VLAN resource Args: vid (str): The VLAN ID to create Returns: True if create was successful otherwise False
def create(self, vid): command = 'vlan %s' % vid return self.configure(command) if isvlan(vid) else False
266,313
Deletes a VLAN from the running configuration Args: vid (str): The VLAN ID to delete Returns: True if the operation was successful otherwise False
def delete(self, vid): command = 'no vlan %s' % vid return self.configure(command) if isvlan(vid) else False
266,314
Defaults the VLAN configuration .. code-block:: none default vlan <vlanid> Args: vid (str): The VLAN ID to default Returns: True if the operation was successful otherwise False
def default(self, vid): command = 'default vlan %s' % vid return self.configure(command) if isvlan(vid) else False
266,315
Configures the specified Vlan using commands Args: vid (str): The VLAN ID to configure commands: The list of commands to configure Returns: True if the commands completed successfully
def configure_vlan(self, vid, commands): commands = make_iterable(commands) commands.insert(0, 'vlan %s' % vid) return self.configure(commands)
266,316
Configures the VLAN name EosVersion: 4.13.7M Args: vid (str): The VLAN ID to Configures name (str): The value to configure the vlan name default (bool): Defaults the VLAN ID name disable (bool): Negates the VLAN ID name Returns: ...
def set_name(self, vid, name=None, default=False, disable=False): cmds = self.command_builder('name', value=name, default=default, disable=disable) return self.configure_vlan(vid, cmds)
266,317
Configures the VLAN state EosVersion: 4.13.7M Args: vid (str): The VLAN ID to configure value (str): The value to set the vlan state to default (bool): Configures the vlan state to its default value disable (bool): Negates the vlan state ...
def set_state(self, vid, value=None, default=False, disable=False): cmds = self.command_builder('state', value=value, default=default, disable=disable) return self.configure_vlan(vid, cmds)
266,318
Configures the user authentication for eAPI This method configures the username and password combination to use for authenticating to eAPI. Args: username (str): The username to use to authenticate the eAPI connection with password (str): The password in...
def authentication(self, username, password): _auth_text = '{}:{}'.format(username, password) # Work around for Python 2.7/3.x compatibility if int(sys.version[0]) > 2: # For Python 3.x _auth_bin = base64.encodebytes(_auth_text.encode()) _auth = _aut...
266,329
Scans the config and returns a block of code Args: parent (str): The parent string to search the config for and return the block config (str): A text config string to be searched. Default is to search the running-config of the Node. Returns: ...
def get_block(self, parent, config='running_config'): try: parent = r'^%s$' % parent return self.node.section(parent, config=config) except TypeError: return None
266,348
Configures the specified interface with the commands Args: name (str): The interface name to configure commands: The commands to configure in the interface Returns: True if the commands completed successfully
def configure_interface(self, name, commands): commands = make_iterable(commands) commands.insert(0, 'interface %s' % name) return self.configure(commands)
266,351
Assign the NTP source on the node Args: name (string): The interface port that specifies the NTP source. Returns: True if the operation succeeds, otherwise False.
def set_source_interface(self, name): cmd = self.command_builder('ntp source', value=name) return self.configure(cmd)
266,358
Add or update an NTP server entry to the node config Args: name (string): The IP address or FQDN of the NTP server. prefer (bool): Sets the NTP server entry as preferred if True. Returns: True if the operation succeeds, otherwise False.
def add_server(self, name, prefer=False): if not name or re.match(r'^[\s]+$', name): raise ValueError('ntp server name must be specified') if prefer: name = '%s prefer' % name cmd = self.command_builder('ntp server', value=name) return self.configure(cmd)
266,359
Remove an NTP server entry from the node config Args: name (string): The IP address or FQDN of the NTP server. Returns: True if the operation succeeds, otherwise False.
def remove_server(self, name): cmd = self.command_builder('no ntp server', value=name) return self.configure(cmd)
266,360
Configures the global system hostname setting EosVersion: 4.13.7M Args: value (str): The hostname value default (bool): Controls use of the default keyword disable (bool): Controls the use of the no keyword Returns: bool: True if the...
def set_hostname(self, value=None, default=False, disable=False): cmd = self.command_builder('hostname', value=value, default=default, disable=disable) return self.configure(cmd)
266,365
Configures the state of global ip routing EosVersion: 4.13.7M Args: value(bool): True if ip routing should be enabled or False if ip routing should be disabled default (bool): Controls the use of the default keyword disable (bool): Contro...
def set_iprouting(self, value=None, default=False, disable=False): if value is False: disable = True cmd = self.command_builder('ip routing', value=value, default=default, disable=disable) return self.configure(cmd)
266,366
Configures system banners Args: banner_type(str): banner to be changed (likely login or motd) value(str): value to set for the banner default (bool): Controls the use of the default keyword disable (bool): Controls the use of the no keyword` Returns: ...
def set_banner(self, banner_type, value=None, default=False, disable=False): command_string = "banner %s" % banner_type if default is True or disable is True: cmd = self.command_builder(command_string, value=None, default=de...
266,367
Parses the config block and returns the ip address value The provided configuration block is scaned and the configured value for the IP address is returned as a dict object. If the IP address value is not configured, then None is returned for the value Args: config (str): ...
def _parse_address(self, config): match = re.search(r'ip address ([^\s]+)', config) value = match.group(1) if match else None return dict(address=value)
266,369
Parses the config block and returns the configured IP MTU value The provided configuration block is scanned and the configured value for the IP MTU is returned as a dict object. The IP MTU value is expected to always be present in the provided config block Args: config (st...
def _parse_mtu(self, config): match = re.search(r'mtu (\d+)', config) return dict(mtu=int(match.group(1)))
266,370