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 + '.'
if any([r.startswith(look) for r in retn]):
continue
retn.append(tag)
return retn
| 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 `#`, this is removed prior to checking.
Returns:
bool: True if the tag is present. False otherwise.
|
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 type was extended from.
self.opts = dict(self._opt_defs)
self.opts.update(opts)
self._type_norms = {} # python type to norm function map str: _norm_str
self._cmpr_ctors = {} # cmpr string to filter function constructor map
self._cmpr_ctor_lift = {} # if set, create a cmpr which is passed along with indx ops
self.indxcmpr = {
'=': self.indxByEq,
'*in=': self.indxByIn,
'*range=': self.indxByRange,
}
self.setCmprCtor('=', self._ctorCmprEq)
self.setCmprCtor('!=', self._ctorCmprNe)
self.setCmprCtor('~=', self._ctorCmprRe)
self.setCmprCtor('^=', self._ctorCmprPref)
self.setCmprCtor('*in=', self._ctorCmprIn)
self.setCmprCtor('*range=', self._ctorCmprRange)
self.setNormFunc(s_node.Node, self._normStormNode)
self.postTypeInit()
| 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 name: valu entries.
|
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.')
sortval = False
if isinstance(val1, str):
if val1.startswith(('+-', '-+')):
sortval = True
delt = s_time.delta(val1[2:])
# order matters
_tock = _tick + delt
_tick = _tick - delt
elif val1.startswith('-'):
sortval = True
_tock = self._getLiftValu(val1, relto=_tick)
else:
_tock = self._getLiftValu(val1, relto=_tick)
else:
_tock = self._getLiftValu(val1, relto=_tick)
if sortval and _tick >= _tock:
tick = min(_tick, _tock)
tock = max(_tick, _tock)
return tick, tock
return _tick, _tock
| 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 character
# checking in C without using regex
s_common.uhex(text)
except (binascii.Error, ValueError) as e:
raise s_exc.BadTypeValu(valu=text, name='hexstr', mesg=str(e))
return text
| 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)
proplayr.update({k: layr for k in layerprops})
node = s_node.Node(self, buid, props.items(), proplayr=proplayr)
# Give other tasks a chance to run
await asyncio.sleep(0)
if node.ndef is None:
return None
# Add node to my buidcache
self.buidcache.append(node)
self.livenodes[buid] = node
return node
| 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):
yield node
return
if full.startswith('#'):
async for node in self._getNodesByTag(full, valu=valu, cmpr=cmpr):
yield node
return
fields = full.split('#', 1)
if len(fields) > 1:
form, tag = fields
async for node in self._getNodesByFormTag(form, tag, valu=valu, cmpr=cmpr):
yield node
return
async for node in self._getNodesByProp(full, valu=valu, cmpr=cmpr):
yield node
| 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 adding node: {name} {valu!r} {props!r}'
logger.exception(mesg)
if self.strict:
raise
return None
| 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() generator.
|
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 nodedef tuples.
Returns:
(list): A list of xact messages.
|
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(formname, formvalu, props=props)
if node is not None:
tags = forminfo.get('tags')
if tags is not None:
for tag, asof in tags.items():
await node.addTag(tag, valu=asof)
yield node
| 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(onfini)
return prox
| 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 Cortex.
Returns:
CmdrCore: A CmdrCore instance.
|
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 type
Returns:
dict: An opts dictionary.
|
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 if not synt[0].startswith('-')])
switches = {synt[0]: synt for synt in self._cmd_syntax if synt[0].startswith('-')}
# populate defaults and lists
for synt in self._cmd_syntax:
snam = synt[0].strip('-')
defval = synt[1].get('defval')
if defval is not None:
opts[snam] = defval
if synt[1].get('type') in ('list', 'kwlist'):
opts[snam] = []
def atswitch(t, o):
# check if we are at a recognized switch. if not
# assume the data is part of regular arguments.
if not text.startswith('-', o):
return None, o
name, x = s_syntax.meh(t, o, s_syntax.whites)
swit = switches.get(name)
if swit is None:
return None, o
return swit, x
while off < len(text):
_, off = s_syntax.nom(text, off, s_syntax.whites)
swit, off = atswitch(text, off)
if swit is not None:
styp = swit[1].get('type', 'flag')
snam = swit[0].strip('-')
if styp == 'valu':
valu, off = s_syntax.parse_cmd_string(text, off)
opts[snam] = valu
elif styp == 'list':
valu, off = s_syntax.parse_cmd_string(text, off)
if not isinstance(valu, list):
valu = valu.split(',')
opts[snam].extend(valu)
elif styp == 'enum':
vals = swit[1].get('enum:vals')
valu, off = s_syntax.parse_cmd_string(text, off)
if valu not in vals:
raise s_exc.BadSyntax(mesg='%s (%s)' % (swit[0], '|'.join(vals)),
text=text)
opts[snam] = valu
else:
opts[snam] = True
continue
if not args:
raise s_exc.BadSyntax(mesg='trailing text: [%s]' % (text[off:],),
text=text)
synt = args.popleft()
styp = synt[1].get('type', 'valu')
# a glob type eats the remainder of the string
if styp == 'glob':
opts[synt[0]] = text[off:]
break
# eat the remainder of the string as separate vals
if styp == 'list':
valu = []
while off < len(text):
item, off = s_syntax.parse_cmd_string(text, off)
valu.append(item)
opts[synt[0]] = valu
break
if styp == 'kwlist':
kwlist, off = s_syntax.parse_cmd_kwlist(text, off)
opts[snam] = kwlist
break
valu, off = s_syntax.parse_cmd_string(text, off)
opts[synt[0]] = valu
return opts
| 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,))
return
try:
ret = await cmdo.runCmdLine(line)
except s_exc.CliFini:
await self.fini()
except asyncio.CancelledError:
self.printf('Cmd cancelled')
except Exception as e:
exctxt = traceback.format_exc()
self.printf(exctxt)
self.printf('error: %s' % e)
return ret
| 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.genCaCert('myca')
Returns:
((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the private key and certificate objects.
|
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:
self.selfSignCert(cert, pkey)
if save:
keypath = self._savePkeyTo(pkey, 'cas', '%s.key' % name)
if outp is not None:
outp.printf('key saved: %s' % (keypath,))
crtpath = self._saveCertTo(cert, 'cas', '%s.crt' % name)
if outp is not None:
outp.printf('cert saved: %s' % (crtpath,))
return pkey, cert
| 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":
myuserpkcs12 = cdir.genClientCert('myuser')
Returns:
OpenSSL.crypto.PKCS12: The PKCS #12 archive.
|
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 = self.getUserKey(name)
if not ukey:
raise s_exc.NoSuchFile('missing User private key')
ccert = crypto.PKCS12()
ccert.set_friendlyname(name.encode('utf-8'))
ccert.set_ca_certificates([cacert])
ccert.set_certificate(ucert)
ccert.set_privatekey(ukey)
crtpath = self._saveP12To(ccert, 'users', '%s.p12' % name)
if outp is not None:
outp.printf('client cert saved: %s' % (crtpath,))
| 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.
Returns:
OpenSSL.crypto.X509: The certificate, if it is 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(store, cert)
ctx.verify_certificate() # raises X509StoreContextError if unable to verify
return cert
| 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:
str: The path if exists.
|
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:
str: The path if exists.
|
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.getUserForHost('myuser', 'cool.vertex.link')
Returns:
str: The cert name, if exists.
|
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.
certdir.importFile('mycoolca.crt', 'cas')
Notes:
importFile does not perform any validation on the files it imports.
Returns:
None
|
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', 'key', 'p12'):
mesg = 'importFile only supports .crt, .key, .p12 extensions'
raise s_exc.BadFileExt(mesg=mesg, ext=ext)
newpath = s_common.genpath(self.certdir, mode, fname)
if os.path.isfile(newpath):
raise s_exc.FileExists('File already exists')
shutil.copy(path, newpath)
if outp is not None:
outp.printf('copied %s to %s' % (path, newpath))
| 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 present, False otherwise.
|
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')
Returns:
None
|
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)
cert.set_issuer(cacert.get_subject())
cert.sign(cakey, self.signing_digest)
| 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, myotherprivatekey)
Returns:
None
|
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')
Returns:
((OpenSSL.crypto.PKey, OpenSSL.crypto.X509)): Tuple containing the public key and certificate objects.
|
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 .crt for %s' % hostname)
keyfile = self.getHostKeyPath(hostname)
if keyfile is None:
raise s_exc.NoCertKey('Missing .key for %s' % hostname)
sslctx.load_cert_chain(certfile, keyfile)
return sslctx
| 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,
c_ec.ECDSA(c_utils.Prehashed(chosen_hash))
)
return True
except InvalidSignature:
logger.exception('Error in publ.verify')
return False
| 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:
int, dict: The system normalized version integer and a subs dictionary.
|
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 = s_version.parseVersionParts(valu)
if subs is None:
raise s_exc.BadTypeValu(valu=valu, name='bruteVersionStr',
mesg='Unable to brute force version parts out of the string')
if subs:
valu = s_version.packVersion(subs.get('major'),
subs.get('minor', 0),
subs.get('patch', 0))
return valu, 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, byts))
self.slab.putmulti(rows, append=True, db=self.db)
took = s_common.now() - tick
origindx = self.indx
self.indx = indx
return {'indx': indx, 'size': size, 'count': len(items), 'time': tick, 'took': took}
return origindx
| 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.asin(math.sqrt(a))
return c * r
| 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.degrees(lonr + lond)
return (latmin, latmax, lonmin, lonmax)
| 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)
write(train_file, content)
if model_filename:
self.estimator = fasttext.supervised(train_file, model_filename)
else:
self.estimator = fasttext.supervised(train_file)
os.remove(train_file)
| 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_query_batch_results(
batch_id,
result_id,
job_id=job_id,
chunk_size=chunk_size
)
| 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 ip routing vrf %s' % value)
if config:
response['ipv4_routing'] = False
else:
response['ipv4_routing'] = True
config = self.get_block('no ipv6 unicast-routing vrf %s' % value)
if config:
response['ipv6_routing'] = False
else:
response['ipv6_routing'] = True
return response
| 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: resource dict attribute
|
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:
dict: resource dict attribute
|
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
Returns:
True if the operation was successful otherwise False
|
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:
True if the operation was successful otherwise False
|
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 configurations are defined or
if the interface is not configured.
|
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
config = self.get_block('interface %s' % interface)
if config is None:
return config
# Find all occurrences of vrids in this interface and make
# a set of the unique vrid numbers
match = set(re.findall(r'^\s+(?:no |)vrrp (\d+)', config, re.M))
if not match:
return None
# Initialize the result dict
result = dict()
for vrid in match:
subd = dict()
# Parse the vrrp configuration for the vrid(s) in the list
subd.update(self._parse_delay_reload(config, vrid))
subd.update(self._parse_description(config, vrid))
subd.update(self._parse_enable(config, vrid))
subd.update(self._parse_ip_version(config, vrid))
subd.update(self._parse_mac_addr_adv_interval(config, vrid))
subd.update(self._parse_preempt(config, vrid))
subd.update(self._parse_preempt_delay_min(config, vrid))
subd.update(self._parse_preempt_delay_reload(config, vrid))
subd.update(self._parse_primary_ip(config, vrid))
subd.update(self._parse_priority(config, vrid))
subd.update(self._parse_secondary_ip(config, vrid))
subd.update(self._parse_timers_advertise(config, vrid))
subd.update(self._parse_track(config, vrid))
subd.update(self._parse_bfd_ip(config, vrid))
result.update({int(vrid): subd})
# If result dict is empty, return None, otherwise return result
return result if result else None
| 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 commands complete successfully
|
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:
bool: Returns True if the commands complete successfully
|
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:
bool: Returns True if the commands complete successfully
|
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: Returns True if the commands complete successfully
|
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
disable (bool): Negates shutdown using the no keyword
Returns:
bool: Returns True if the commands complete successfully
|
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 (str)
|
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))
return dict(networks=networks)
| 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 bgp'
protocol = ospf_redist[1]
redistributions.append(dict(protocol=protocol))
if len(ospf_redist) == 4:
# complex redist eg 'redistribute bgp route-map NYSE-RP-MAP'
protocol = ospf_redist[1]
route_map_name = ospf_redist[3]
redistributions.append(dict(protocol=protocol,
route_map=route_map_name))
return dict(redistributions=redistributions)
| 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:
ValueError: If the ospf_process_id passed in less
than 0 or greater than 65536
|
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
return self.configure(command)
| 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 are completed successfully
|
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
Exception:
ValueError: This will be raised if the protocol pass is not one
of the following: [rip, bgp, static, connected]
|
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 None:
cmd = 'redistribute {}'.format(protocol)
else:
cmd = 'redistribute {} route-map {}'.format(protocol,
route_map_name)
return self.configure_ospf(cmd)
| 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
Exception:
ValueError: This will be raised if the protocol pass is not one
of the following: [rip, bgp, static, connected]
|
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(protocol)
return self.configure_ospf(cmd)
| 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
key/value pairs.
|
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(config))
return response
| 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 running
configuration
Returns:
dict: resource dict attribute
|
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 the nodes
running configuration
Returns:
dict: resource dict attribute
|
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 configuration block form the node's
running configuration
Returns:
dict: resource dict attribute
|
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:
True if the operation was successful otherwise False
|
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
Returns:
True if the operation was successful otherwise False
|
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 clear text to use to authenticate
the eAPI connection with
|
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 = _auth_bin.decode()
_auth = _auth.replace('\n', '')
self._auth = _auth
else:
# For Python 2.7
_auth = base64.encodestring(_auth_text)
self._auth = str(_auth).replace('\n', '')
_LOGGER.debug('Autentication string is: {}:***'.format(username))
| 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:
A string object that represents the block from the config. If
the parent string is not found, then this method will
return None.
|
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 commands are completed successfully
|
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): Controls the use of the no keyword
Returns:
bool: True if the commands completed successfully otherwise False
|
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:
bool: True if the commands completed successfully otherwise False
|
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=default, disable=disable)
return self.configure(cmd)
else:
if not value.endswith("\n"):
value = value + "\n"
command_input = dict(cmd=command_string, input=value)
return self.configure([command_input])
| 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): The interface configuration block to parse
Return:
dict: A dict object intended to be merged into the resource dict
|
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 (str): The interface configuration block to parse
Return:
dict: A dict object intended to be merged into the resource dict
|
def _parse_mtu(self, config):
match = re.search(r'mtu (\d+)', config)
return dict(mtu=int(match.group(1)))
| 266,370 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.