code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
with SMCSocketProtocol(self, **self.sockopt) as protocol: for result in protocol.receive(): yield result
def execute(self)
Execute the query with optional timeout. The response to the execute query is the raw payload received from the websocket and will contain multiple dict keys and values. It is more common to call query.fetch_XXX which will filter the return result based on the method. Each result set wil...
26.806875
34.29237
0.781715
self.sockopt.update(kw) with SMCSocketProtocol(self, **self.sockopt) as protocol: for result in protocol.receive(): if 'records' in result and result['records'].get('added'): yield result['records']['added']
def fetch_raw(self, **kw)
Fetch the records for this query. This fetch type will return the results in raw dict format. It is possible to limit the number of receives on the socket that return results before exiting by providing max_recv. This fetch should be used if you want to return only the result re...
9.939092
9.659316
1.028964
fmt = formatter(self) if 'max_recv' not in kw: kw.update(max_recv=1) for result in self.fetch_raw(**kw): yield fmt.formatted(result)
def fetch_batch(self, formatter=TableFormat, **kw)
Fetch and return in the specified format. Output format is a formatter class in :py:mod:`smc_monitoring.models.formatters`. This fetch type will be a single shot fetch unless providing max_recv keyword with a value greater than the default of 1. Keyword arguments available are kw in :met...
5.684731
3.814032
1.490478
fmt = formatter(self) for results in self.execute(): if 'records' in results and results['records'].get('added'): yield fmt.formatted(results['records']['added'])
def fetch_live(self, formatter=TableFormat)
Fetch a live stream query. This is the equivalent of selecting the "Play" option for monitoring fields within the SMC UI. Data will be streamed back in real time. :param formatter: Formatter type for data representation. Any type in :py:mod:`smc_monitoring.models.formatters`...
8.564425
9.604783
0.891683
result = SMCRequest( params={'filter': name, 'filter_context': filter_context, 'exact_match': exact_match}).read() if not result.json: result.json = [] return result
def fetch_meta_by_name(name, filter_context=None, exact_match=True)
Find the element based on name and optional filters. By default, the name provided uses the standard filter query. Additional filters can be used based on supported collections in the SMC API. :method: GET :param str name: element name, can use * as wildcard :param str filter_context: further filte...
6.67332
6.466664
1.031957
self.make_request( method='create', resource='blacklist', json=prepare_blacklist(src, dst, duration, **kw))
def blacklist(self, src, dst, duration=3600, **kw)
Add blacklist to all defined engines. Use the cidr netmask at the end of src and dst, such as: 1.1.1.1/32, etc. :param src: source of the entry :param dst: destination of blacklist entry :raises ActionCommandFailed: blacklist apply failed with reason :return: None ...
6.465611
6.042508
1.070021
self.make_request( method='update', resource='license_install', files={ 'license_file': open(license_file, 'rb') })
def license_install(self, license_file)
Install a new license. :param str license_file: fully qualified path to the license jar file. :raises: ActionCommandFailed :return: None
5.299394
4.868353
1.088539
raise ResourceNotFound('This entry point is only supported on SMC >= 6.5') return self.make_request(resource='visible_security_group_mapping', params={'filter': filter})
def visible_security_group_mapping(self, filter=None): # @ReservedAssignment if 'visible_security_group_mapping' not in self.data.links
Return all security groups assigned to VSS container types. This is only available on SMC >= 6.5. :param str filter: filter for searching by name :raises ActionCommandFailed: element not found on this version of SMC :raises ResourceNotFound: unsupported method on SMC < 6.5 ...
10.955284
6.269019
1.747528
result = self.make_request( method='create', resource='references_by_element', json={ 'value': element_href}) return result
def references_by_element(self, element_href)
Return all references to element specified. :param str element_href: element reference :return: list of references where element is used :rtype: list(dict)
6.47339
6.703116
0.965728
valid_types = ['all', 'nw', 'ips', 'sv', 'rb', 'al', 'vpn'] if typeof not in valid_types: typeof = 'all' return Task.download(self, 'export_elements', filename, params={'recursive': True, 'type': typeof})
def export_elements(self, filename='export_elements.zip', typeof='all')
Export elements from SMC. Valid types are: all (All Elements)|nw (Network Elements)|ips (IPS Elements)| sv (Services)|rb (Security Policies)|al (Alerts)| vpn (VPN Elements) :param type: type of element :param filename: Name of file for export :raises TaskRunFail...
8.86869
3.856533
2.299654
self.make_request( method='create', resource='import_elements', files={ 'import_file': open(import_file, 'rb') })
def import_elements(self, import_file)
Import elements into SMC. Specify the fully qualified path to the import file. :param str import_file: system level path to file :raises: ActionCommandFailed :return: None
5.186384
4.981968
1.041031
if not protocol_agent: for pa in ('paValues', 'protocol_agent_ref'): self.data.pop(pa, None) else: self.data.update(protocol_agent_ref=element_resolver(protocol_agent))
def update_protocol_agent(self, protocol_agent)
Update this service to use the specified protocol agent. After adding the protocol agent to the service you must call `update` on the element to commit. :param str,ProtocolAgent protocol_agent: protocol agent element or href :return: None
7.529466
6.916197
1.088671
for param in self.data.get('paParameters', []): for _pa_parameter, values in param.items(): if values.get('name') == name: return values
def _get_param_values(self, name)
Return the parameter by name as stored on the protocol agent payload. This loads the data from the local cache versus having to query the SMC for each parameter. :param str name: name of param :rtype: dict
7.405771
7.025875
1.054071
return [type('ProtocolParameter', (SubElement,), { 'data': ElementCache(data=self._get_param_values(param.get('name')))} )(**param) for param in self.make_request(resource='pa_parameters')]
def parameters(self)
Protocol agent parameters are settings specific to the protocol agent type. Each protocol agent will have parameter settings that are configurable when a service uses a given protocol agent. Parameters on the protocol agent are templates that define settings exposed in the service. These...
21.570082
22.235847
0.970059
for parameter in self.protocol_agent.parameters: if parameter.href in self.protocol_agent_values.get('parameter_ref', []): return parameter
def protocol_parameter(self)
The protocol parameter defined from the base protocol agent. This is a read-only element that provides some additional context to the parameter setting. :rtype: ProtocolParameter
9.703174
9.526896
1.018503
if 'value' in kwargs and self.protocol_agent_values.get('value') != \ kwargs.get('value'): self.protocol_agent_values.update(value=kwargs['value']) return True return False
def _update(self, **kwargs)
Update the mutable field `value`. :rtype: bool
5.894449
5.310826
1.109893
# TODO: Workaround for SMC 6.4.3 which only provides the inspected service # reference. We need to find the Proxy Server from this ref. if self._inspected_service_ref: for proxy in ProxyServer.objects.all(): if self._inspected_service_ref.startswith(proxy.hre...
def proxy_server(self)
The ProxyServer element referenced in this protocol parameter, if any. :return: The proxy server element or None if one is not assigned :rtype: ProxyServer
10.198952
9.77869
1.042977
updated = False if 'proxy_server' in kwargs: proxy_server = kwargs.get('proxy_server') if not proxy_server and self._inspected_service_ref: self.protocol_agent_values.pop('inspected_service_ref', None) updated = True elif isins...
def _update(self, **kwargs)
Internal method to update the parameter dict stored in attribute protocol_agent_values. Allows masking of real attribute names to something more sane. :rtype: bool
3.845655
3.360615
1.14433
for value in self.items: if value.name == name: return value._update(**kwargs) return False
def update(self, name, **kwargs)
Update protocol agent parameters based on the parameter name. Provide the relevant keyword pairs based on the parameter type. When update is called, a boolean is returned indicating whether the field was successfully updated or not. You should check the return value and call `update` on ...
6.093664
8.982135
0.67842
self.conditions.append( dict(access_list_ref=accesslist.href, type='element', rank=rank))
def add_access_list(self, accesslist, rank=None)
Add an access list to the match condition. Valid access list types are IPAccessList (v4 and v6), IPPrefixList (v4 and v6), AS Path, CommunityAccessList, ExtendedCommunityAccessList.
11.276411
9.784709
1.152452
self.conditions.append( dict(metric=value, type='metric', rank=rank))
def add_metric(self, value, rank=None)
Add a metric to this match condition :param int value: metric value
10.459177
8.915485
1.173147
self.conditions.append(dict( next_hop_ref=access_or_prefix_list.href, type='next_hop', rank=rank))
def add_next_hop(self, access_or_prefix_list, rank=None)
Add a next hop condition. Next hop elements must be of type IPAccessList or IPPrefixList. :raises ElementNotFound: If element specified does not exist
5.615561
6.095601
0.921248
if ext_bgp_peer_or_fw.typeof == 'external_bgp_peer': ref = 'external_bgp_peer_address_ref' else: # engine ref = 'fwcluster_peer_address_ref' self.conditions.append( {ref: ext_bgp_peer_or_fw.href, 'rank': rank, 'type': 'peer_a...
def add_peer_address(self, ext_bgp_peer_or_fw, rank=None)
Add a peer address. Peer address types are ExternalBGPPeer or Engine. :raises ElementNotFound: If element specified does not exist
4.571346
4.500282
1.015791
self.conditions[:] = [r for r in self.conditions if r.get('rank') != rank]
def remove_condition(self, rank)
Remove a condition element using it's rank. You can find the rank and element for a match condition by iterating the match condition:: >>> rule1 = rm.route_map_rules.get(0) >>> for condition in rule1.match_condition: ... condition ... ...
6.418482
10.15598
0.63199
json = {'name': name, 'action': action, 'finish': finish, 'goto': goto.href if goto else None, 'call_route_map_ref': None if not call else call.href, 'comment': comment} if not match_condition: ...
def create(self, name, action='permit', goto=None, finish=False, call=None, comment=None, add_pos=None, after=None, before=None, **match_condition)
Create a route map rule. You can provide match conditions by using keyword arguments specifying the required types. You can also create the route map rule and add match conditions after. :param str name: name for this rule :param str action: permit or deny :param...
2.715156
2.328798
1.165904
return [RouteMapRule(**rule) for rule in self.make_request( resource='search_rule', params={'filter': search})]
def search_rule(self, search)
Search the RouteMap policy using a search string :param str search: search string for a contains match against the rule name and comments field :rtype: list(RouteMapRule)
14.852732
12.863061
1.154681
json = {'name': name, 'certificate': certificate} return ElementCreator(cls, json)
def create(cls, name, certificate)
Create a new external VPN CA for signing internal gateway certificates. :param str name: Name of VPN CA :param str certificate: file name, path or certificate string. :raises CreateElementFailed: Failed creating cert with reason :rtype: VPNCertificateCA
8.216983
11.526536
0.712875
if signing_ca is None: signing_ca = VPNCertificateCA.objects.filter('Internal RSA').first() cert_auth = element_resolver(signing_ca) return ElementCreator( GatewayCertificate, exception=CertificateError, href=self.interna...
def _create(self, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=2048, signing_ca=None)
Internal method called as a reference from the engine.vpn node
6.796684
6.569147
1.034637
max_dst_port = max_dst_port if max_dst_port is not None else '' json = {'name': name, 'min_dst_port': min_dst_port, 'max_dst_port': max_dst_port, 'min_src_port': min_src_port, 'max_src_port': max_src_port, 'protocol...
def create(cls, name, min_dst_port, max_dst_port=None, min_src_port=None, max_src_port=None, protocol_agent=None, comment=None)
Create the TCP service :param str name: name of tcp service :param int min_dst_port: minimum destination port value :param int max_dst_port: maximum destination port value :param int min_src_port: minimum source port value :param int max_src_port: maximum source port value ...
2.263448
2.399539
0.943285
json = {'name': name, 'protocol_number': protocol_number, 'protocol_agent_ref': element_resolver(protocol_agent) or None, 'comment': comment} return ElementCreator(cls, json)
def create(cls, name, protocol_number, protocol_agent=None, comment=None)
Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment :raises CreateElementFailed: ...
4.726557
4.648872
1.01671
json = {'frame_type': frame_type, 'name': name, 'value1': int(value1, 16), 'comment': comment} return ElementCreator(cls, json)
def create(cls, name, frame_type='eth2', value1=None, comment=None)
Create an ethernet service :param str name: name of service :param str frame_type: ethernet frame type, eth2 :param str value1: hex code representing ethertype field :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :r...
4.27527
3.945465
1.083591
if end_time is None: end_time = current_millis() self.data.update( start_ms=start_time, end_ms=end_time) return self
def custom_range(self, start_time, end_time=None)
Provide a custom range for the search query. Start time and end time are expected to be naive ``datetime`` objects converted to milliseconds. When submitting the query, it is strongly recommended to set the timezone matching the local client making the query. Example of finding...
4.472429
5.295318
0.844601
if hasattr(cert, 'read'): # File object - return as is return cert cert = cert.encode('utf-8') if isinstance(cert, unicode) else cert if re.match(_PEM_RE, cert): return True return False
def pem_as_string(cert)
Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context.
5.646027
4.663248
1.21075
if hasattr(chain_file, 'read'): cert_chain = chain_file.read() else: with open(chain_file, 'rb') as f: cert_chain = f.read() if not cert_chain: raise ValueError('Certificate chain file is empty!') cert_type_matches = [] for match in _PEM_RE.find...
def load_cert_chain(chain_file)
Load the certificates from the chain file. :raises IOError: Failure to read specified file :raises ValueError: Format issues with chain file or missing entries :return: list of cert type matches
2.738575
2.585635
1.05915
multi_part = 'signed_certificate' if self.typeof == 'tls_server_credentials'\ else 'certificate' self.make_request( CertificateImportError, method='create', resource='certificate_import', headers = {'content-type': 'multipart/form-data...
def import_certificate(self, certificate)
Import a valid certificate. Certificate can be either a file path or a string of the certificate. If string certificate, it must include the -----BEGIN CERTIFICATE----- string. :param str certificate_file: fully qualified path to certificate file :raises CertificateImportError: ...
9.767591
10.026522
0.974175
self.make_request( CertificateImportError, method='create', resource='intermediate_certificate_import', headers = {'content-type': 'multipart/form-data'}, files={ 'signed_certificate': open(certificate, 'rb') if not \ ...
def import_intermediate_certificate(self, certificate)
Import a valid certificate. Certificate can be either a file path or a string of the certificate. If string certificate, it must include the -----BEGIN CERTIFICATE----- string. :param str certificate: fully qualified path or string :raises CertificateImportError: failure to imp...
8.265738
7.578393
1.090698
result = self.make_request( CertificateExportError, raw_result=True, resource='intermediate_certificate_export') if filename is not None: save_to_file(filename, result.content) return return result.content
def export_intermediate_certificate(self, filename=None)
Export the intermediate certificate. Returned certificate will be in string format. If filename is provided, the certificate will also be saved to the file specified. :raises CertificateExportError: error exporting certificate, can occur if no intermediate certificate is ava...
7.235163
6.402612
1.130033
self.make_request( CertificateImportError, method='create', resource='private_key_import', headers = {'content-type': 'multipart/form-data'}, files={ 'private_key': open(private_key, 'rb') if not \ pem_as_...
def import_private_key(self, private_key)
Import a private key. The private key can be a path to a file or the key in string format. If in string format, the key must start with -----BEGIN. Key types supported are PRIVATE RSA KEY and PRIVATE KEY. :param str private_key: fully qualified path to private key file :...
7.14781
6.166614
1.159114
for link in self._entry_points: if link.get('rel') == rel: return link.get('href') raise UnsupportedEntryPoint( "The specified entry point '{}' was not found in this " "version of the SMC API. Check the element documentation " "to ...
def get(self, rel)
Get the resource by rel name :param str rel_name: name of rel :raises UnsupportedEntryPoint: entry point not found in this version of the API
8.565539
6.400105
1.338343
def event_loop(): logger.debug(pformat(self.query.request)) self.send(json.dumps(self.query.request)) while not self.event.is_set(): #print('Waiting around on the socket: %s' % self.gettimeout()) self.event.wait(self.gettimeout()) ...
def on_open(self)
Once the connection is made, start the query off and start an event loop to wait for a signal to stop. Results are yielded within receive().
4.667718
4.109441
1.135852
if self.connected: self.send( json.dumps(message.request))
def send_message(self, message)
Send a message down the socket. The message is expected to have a `request` attribute that holds the message to be serialized and sent.
13.428102
7.327896
1.832464
try: itr = 0 while self.connected: r, w, e = select.select( (self.sock, ), (), (), 10.0) if r: message = json.loads(self.recv()) if ...
def receive(self)
Generator yielding results from the web socket. Results will come as they are received. Even though socket select has a timeout, the SMC will not reply with a message more than every two minutes.
3.795636
3.689598
1.02874
request = SMCRequest(href=href) request.exception = FetchElementFailed result = request.read() if only_etag: return result.etag return ElementCache( result.json, etag=result.etag)
def LoadElement(href, only_etag=False)
Return an instance of a element as a ElementCache dict used as a cache. :rtype ElementCache
9.366921
9.984167
0.938178
if 'exception' not in kwargs: kwargs.update(exception=CreateElementFailed) href = kwargs.pop('href') if 'href' in kwargs else cls.href result = SMCRequest( href=href, json=json, **kwargs).create() element = cls( name=json.get('name'), type=c...
def ElementCreator(cls, json, **kwargs)
Helper method for creating elements. If the created element type is a SubElement class type, provide href value as kwargs since that class type does not have a direct entry point. This is a lazy load that will provide only the meta for the element. Additional attribute access will load the full data. ...
6.096377
5.497931
1.108849
if smcresult is None: smcresult = SMCRequest(href=href).read() if smcresult.json: cache = ElementCache(smcresult.json, etag=smcresult.etag) typeof = lookup_class(cache.type) instance = typeof( name=cache.get('name'), href=href, type=cache....
def ElementFactory(href, smcresult=None, raise_exc=None)
Factory returns an object of type Element when only the href is provided. :param str href: string href to fetch :param SMCResult smcresult: optional SMCResult. If provided, the request fetch will be skipped :param Exception raise_exc: exception to raise if fetch failed
3.896618
4.170967
0.934224
if self and self._etag is None: self._etag = LoadElement(href, only_etag=True) return self._etag
def etag(self, href)
ETag can be None if a subset of element json is using this container, such as the case with Routing.
8.465014
7.101
1.192088
if rel in self.links: return self.links[rel] raise ResourceNotFound('Resource requested: %r is not available ' 'on this element.' % rel)
def get_link(self, rel)
Return link for specified resource
7.139053
6.569509
1.086695
element = cls.objects.filter(name, exact_match=True).first() if \ name is not None else None if not element and raise_exc: raise ElementNotFound('Cannot find specified element: %s, type: ' '%s' % (name, cls.__name__)) return element
def get(cls, name, raise_exc=True)
Get the element by name. Does an exact match by element type. :param str name: name of element :param bool raise_exc: optionally disable exception. :raises ElementNotFound: if element does not exist :rtype: Element
5.004188
5.488149
0.911817
was_created = False if 'name' not in kwargs: raise ElementNotFound('Name field is a required parameter ' 'for all create or update_or_create type operations on an element') if filter_key: elements = cls.objects.filter(**filter_key) el...
def get_or_create(cls, filter_key=None, with_status=False, **kwargs)
Convenience method to retrieve an Element or create if it does not exist. If an element does not have a `create` classmethod, then it is considered read-only and the request will be redirected to :meth:`~get`. Any keyword arguments passed except the optional filter_key will be used in a ...
3.558915
3.306058
1.076483
assert isinstance(category, list), 'Category input was expecting list.' from smc.elements.other import Category for tag in category: category = Category(tag) try: category.add_element(self.href) except ElementNotFound: ...
def add_category(self, category)
Category Tags are used to characterize an element by a type identifier. They can then be searched and returned as a group of elements. If the category tag specified does not exist, it will be created. This change will take effect immediately. :param list tags: list of category tag names...
6.68702
4.886428
1.368488
from smc.administration.tasks import Task return Task.download(self, 'export', filename)
def export(self, filename='element.zip')
Export this element. Usage:: engine = Engine('myfirewall') extask = engine.export(filename='fooexport.zip') while not extask.done(): extask.wait(3) print("Finished download task: %s" % extask.message()) print("File downloaded to: %s" ...
19.529268
28.019415
0.696991
href = fetch_entry_point('references_by_element') return [Element.from_meta(**ref) for ref in self.make_request( method='create', href=href, json={'value': self.href})]
def referenced_by(self)
Show all references for this element. A reference means that this element is being used, for example, in a policy rule, as a member of a group, etc. :return: list referenced elements :rtype: list(Element)
15.188015
14.527356
1.045477
from smc.core.resource import History return History(**self.make_request(resource='history'))
def history(self)
.. versionadded:: 0.5.7 Requires SMC version >= 6.3.2 Obtain the history of this element. This will not chronicle every modification made over time, but instead a current snapshot with historical information such as when the element was created, by whom, when it was ...
15.007173
11.882375
1.262978
dup = self.make_request( method='update', raw_result=True, resource='duplicate', params={'name': name}) return type(self)(name=name, href=dup.href, type=type(self).typeof)
def duplicate(self, name)
.. versionadded:: 0.5.8 Requires SMC version >= 6.3.2 Duplicate this element. This is a shortcut method that will make a direct copy of the element under the new name and type. :param str name: name for the duplicated element :raises ActionCommandFailed: fai...
9.476814
11.255654
0.84196
location_ref = location_helper(location_name, search_only=True) if location_ref: for location in self: if location.location_ref == location_ref: return location
def get(self, location_name)
Get a contact address by location name :param str location_name: name of location :return: return contact address element or None :rtype: ContactAddress
5.095011
6.50925
0.782734
updated, created = False, False location_ref = location_helper(location) if location_ref in self: for loc in self: if loc.location_ref == location_ref: if overwrite_existing: loc['addresses'][:] = contact_addresses ...
def update_or_create(self, location, contact_addresses, with_status=False, overwrite_existing=False, **kw)
Update or create a contact address and location pair. If the location does not exist it will be automatically created. If the server already has a location assigned with the same name, the contact address specified will be added if it doesn't already exist (Management and Log Server can ...
2.966693
2.988738
0.992624
return MultiContactAddress( href=self.get_relation('contact_addresses'), type=self.typeof, name=self.name)
def contact_addresses(self)
Provides a reference to contact addresses used by this server. Obtain a reference to manipulate or iterate existing contact addresses:: >>> from smc.elements.servers import ManagementServer >>> mgt_server = ManagementServer.objects.first() >>> for co...
13.23588
12.057944
1.09769
json = { 'name': name, 'address': address, 'comment': comment, 'http_proxy_port': proxy_port, 'http_proxy_username': username if username else '', 'http_proxy_password': password if password else '', 'secondary': second...
def create(cls, name, address, proxy_port=8080, username=None, password=None, secondary=None, comment=None)
Create a new HTTP Proxy service. Proxy must define at least one primary address but can optionally also define a list of secondary addresses. :param str name: Name of the proxy element :param str address: Primary address for proxy :param int proxy_port: proxy port (defau...
2.673613
3.200206
0.83545
json = { 'name': name, 'address': address, 'comment': comment, 'time_to_live': time_to_live, 'update_interval': update_interval, 'secondary': secondary if secondary else []} return ElementCreator(cls, json)
def create(cls, name, address, time_to_live=20, update_interval=10, secondary=None, comment=None)
Create a DNS Server element. :param str name: Name of DNS Server :param str address: IP address for DNS Server element :param int time_to_live: Defines how long a DNS entry can be cached before querying the DNS server again (default: 20) :param int update_interval: D...
2.709092
3.148328
0.860486
json = {'name': name, 'comment': comment, 'secondary': secondary or [], 'http_proxy': proxy_service, 'balancing_mode': balancing_mode, 'inspected_service': inspected_service, 'trust_host_header': trust_...
def create(cls, name, address, inspected_service, secondary=None, balancing_mode='ha', proxy_service='generic', location=None, comment=None, add_x_forwarded_for=False, trust_host_header=False, **kw)
Create a Proxy Server element :param str name: name of proxy server element :param str address: address of element. Can be a single FQDN or comma separated list of IP addresses :param list secondary: list of secondary IP addresses :param str balancing_mode: how to ba...
4.104974
2.915664
1.407904
if node._parent is None: node._del_cache() return node._del_cache() flush_parent_cache(node._parent)
def flush_parent_cache(node)
Flush parent cache will recurse back up the tree and wipe the cache from each parent node reference on the given element. This allows the objects to be reused and a clean way to force the object to update itself if attributes or methods are referenced after update.
3.63266
3.880399
0.936156
# Version SMC < 6.4 if 'related_element_type' not in node.data: return Element.from_href( node.data.get('href')) # SMC Version >= 6.4 - more efficient because it builds the # element by meta versus requiring a query return Element.from_meta( name=node.data.get('...
def from_meta(node)
Helper method that reolves a routing node to element. Rather than doing a lookup and fetch, the routing node provides the information to build the element from meta alone. :rtype: Element
8.446011
7.208531
1.171669
def recurse(nodes): for node in nodes: if node.level == level: routing_node.append(node) else: recurse(node) routing_node = [] recurse(root) return routing_node
def route_level(root, level)
Helper method to recurse the current node and return the specified routing node level.
3.443526
3.397039
1.013685
for gw in gateways: yield gw else: for node in gateways: #TODO: Change to type == node.related_element_type when # only supporting SMC >= 6.4 if type == node.routing_node_element.typeof: # If the parent is level interface, this is a tun...
def gateway_by_type(self, type=None, on_network=None): # @ReservedAssignment gateways = route_level(self, 'gateway') if not type
Return gateways for the specified node. You can also specify type to find only gateways of a specific type. Valid types are: bgp_peering, netlink, ospfv2_area. :param RoutingNode self: the routing node to check :param str type: bgp_peering, netlink, ospfv2_area :param str on_network: if network...
7.927551
7.422834
1.067995
try: if element.typeof in ('host', 'router'): return getattr(element, 'address', False), getattr(element, 'ipv6_address', False) elif element.typeof == 'netlink': gateway = element.gateway if gateway.typeof == 'router': return getattr(gateway,...
def _which_ip_protocol(element)
Validate the protocol addresses for the element. Most elements can have an IPv4 or IPv6 address assigned on the same element. This allows elements to be validated and placed on the right network. :return: boolean tuple :rtype: tuple(ipv4, ipv6)
6.192775
5.599424
1.105967
nicids = map(str, nicids) for interface in engine.routing: if interface.nicid in nicids: if getattr(interface, 'to_delete', False): # Delete the invalid interface interface.delete() continue for network in interface: if getattr(network...
def del_invalid_routes(engine, nicids)
Helper method to run through and delete any routes that are tagged as invalid or to_delete by a list of nicids. Since we could have a list of routes, iterate from top level engine routing node to avoid fetch exceptions. Route list should be a list of nicids as str. :param list nicids: list of nicid...
4.460145
4.058095
1.099074
if 'related_element_type' in self.data: return self.data.get('related_element_type') return None if self.dynamic_nicid or (self.nicid and '.' in self.nicid) else \ Element.from_href(self.data.get('href')).typeof
def related_element_type(self)
.. versionadded:: 0.6.0 Requires SMC version >= 6.4 Related element type defines the 'type' of element at this routing or antispoofing node level. :rtype: str
7.748991
7.927117
0.977529
ret = '--' * level + repr(self) + '\n' for routing_node in self: ret += routing_node.as_tree(level+1) return ret
def as_tree(self, level=0)
Display the routing tree representation in string format :rtype: str
4.54585
3.888112
1.169166
for interface in self: if interface.nicid == str(interface_id) or \ interface.dynamic_nicid == str(interface_id): return interface raise InterfaceNotFound('Specified interface {} does not exist on ' 'this engine.'.format(interface_id))
def get(self, interface_id)
Obtain routing configuration for a specific interface by ID. .. note:: If interface is a VLAN, you must use a str to specify the interface id, such as '3.13' (interface 3, VLAN 13) :param str,int interface_id: interface identifier :raises InterfaceNotFound: inva...
5.756896
5.223929
1.102024
routing_node_gateway = RoutingNodeGateway(netlink, destinations=[] if not netlink_gw else netlink_gw) return self._add_gateway_node('netlink', routing_node_gateway, network)
def add_traffic_handler(self, netlink, netlink_gw=None, network=None)
Add a traffic handler to a routing node. A traffic handler can be either a static netlink or a multilink traffic handler. If ``network`` is not specified and the interface has multiple IP addresses, the traffic handler will be added to all ipv4 addresses. Add a pre-defined netl...
7.525085
7.238089
1.039651
communication_mode = communication_mode.upper() destinations=[] if not ospf_interface_setting else [ospf_interface_setting] if communication_mode == 'UNICAST' and unicast_ref: destinations.append(unicast_ref) routing_node_gateway = RoutingNodeGateway( osp...
def add_ospf_area(self, ospf_area, ospf_interface_setting=None, network=None, communication_mode='NOT_FORCED', unicast_ref=None)
Add OSPF Area to this routing node. Communication mode specifies how the interface will interact with the adjacent OSPF environment. Please see SMC API documentation for more in depth information on each option. If the interface has multiple networks nested below, all networks ...
3.54575
3.752874
0.944809
destination = [external_bgp_peer] if external_bgp_peer else [] routing_node_gateway = RoutingNodeGateway(bgp_peering, destinations=destination) return self._add_gateway_node('bgp_peering', routing_node_gateway, network)
def add_bgp_peering(self, bgp_peering, external_bgp_peer=None, network=None)
Add a BGP configuration to this routing interface. If the interface has multiple ip addresses, all networks will receive the BGP peering by default unless the ``network`` parameter is specified. Example of adding BGP to an interface by ID:: interface = engine.routi...
4.933632
5.938455
0.830794
routing_node_gateway = RoutingNodeGateway(gateway, destinations=destination) return self._add_gateway_node('router', routing_node_gateway, network)
def add_static_route(self, gateway, destination, network=None)
Add a static route to this route table. Destination can be any element type supported in the routing table such as a Group of network members. Since a static route gateway needs to be on the same network as the interface, provide a value for `network` if an interface has multiple address...
9.881247
18.973684
0.520787
routing_node_gateway = RoutingNodeGateway(dynamic_classid='gateway', destinations=networks or []) return self._add_gateway_node('dynamic_netlink', routing_node_gateway)
def add_dynamic_gateway(self, networks)
A dynamic gateway object creates a router object that is attached to a DHCP interface. You can associate networks with this gateway address to identify networks for routing on this interface. :: route = engine.routing.get(0) route.add_dynamic_gateway([Ne...
15.62866
22.129623
0.706233
modified = False peering = [next_hop for next_hop in self if next_hop.routing_node_element == routing_node_gateway.routing_node_element] if not peering: self.data.setdefault('routing_node', []).append( routing_node_gateway) modified =...
def _add_gateway_node_on_tunnel(self, routing_node_gateway)
Add a gateway node on a tunnel interface. Tunnel interface elements are attached to the interface level and not directly nested under the networks node. :param RouteNodeGateway routing_node_gateway: routing node gateway instance :return: Whether a change was made or not ...
4.320149
4.448255
0.971201
if self.level != 'interface': raise ModificationAborted('You must make this change from the ' 'interface routing level. Current node: {}'.format(self)) if self.related_element_type == 'tunnel_interface': return self._add_gateway_node_on_tunnel(ro...
def _add_gateway_node(self, gw_type, routing_node_gateway, network=None)
Add a gateway node to existing routing tree. Gateways are only added if they do not already exist. If they do exist, check the destinations of the existing gateway and add destinations that are not already there. A current limitation is that if a gateway doesn't exist and the destination...
4.359675
4.149641
1.050615
if self.level not in ('interface',): raise ModificationAborted('You must make this change from the ' 'interface routing level. Current node: {}'.format(self)) node_changed = False element = element_resolver(element) for network in self: ...
def remove_route_gateway(self, element, network=None)
Remove a route element by href or Element. Use this if you want to remove a netlink or a routing element such as BGP or OSPF. Removing is done from within the routing interface context. :: interface0 = engine.routing.get(0) interface0.remove_route_gateway(StaticN...
7.013574
5.823218
1.204415
if self.level == 'interface': for network in self: if from_meta(network) == element: return False self.data['antispoofing_node'].append({ 'antispoofing_node': [], 'auto_generated': 'false', ...
def add(self, element)
Add an entry to this antispoofing node level. Entry can be either href or network elements specified in :py:class:`smc.elements.network` :: if0 = engine.antispoofing.get(0) if0.add(Network('foonet')) :param Element element: entry to add, i.e. Network('mynetwork'...
8.538225
6.400393
1.334016
if self.level == 'interface': len_before_change = len(self) _nodes = [] for network in self: if from_meta(network) != element: _nodes.append(network.data) else: if network.autogenerated: # Make s...
def remove(self, element)
Remove a specific user added element from the antispoofing tables of a given interface. This will not remove autogenerated or system level entries. :param Element element: element to remove :return: remove element if it exists and return bool :rtype: bool
7.043989
5.925538
1.188751
self.items.append(dict( source=source, destination=destination, gateway_ip=gateway_ip, comment=comment))
def create(self, source, destination, gateway_ip, comment=None)
Add a new policy route to the engine. :param str source: network address with /cidr :param str destination: network address with /cidr :param str gateway: IP address, must be on source network :param str comment: optional comment
3.75988
5.042758
0.7456
delete_by = [] for field, val in kw.items(): if val is not None: delete_by.append(field) self.items[:] = [route for route in self.items if not all(route.get(field) == kw.get(field) for fiel...
def delete(self, **kw)
Delete a policy route from the engine. You can delete using a single field or multiple fields for a more exact match. Use a keyword argument to delete a route by any valid attribute. :param kw: use valid Route keyword values to delete by exact match
4.472884
4.085483
1.094824
address = address if address else None ipv6_address = ipv6_address if ipv6_address else None secondaries = [] if secondary is None else secondary json = {'name': name, 'address': address, 'ipv6_address': ipv6_address, 'secondary': ...
def create(cls, name, address=None, ipv6_address=None, secondary=None, comment=None)
Create the host element :param str name: Name of element :param str address: ipv4 address of host object (optional if ipv6) :param str ipv6_address: ipv6 address (optional if ipv4) :param list secondary: secondary ip addresses (optional) :param str comment: comment (optional) ...
2.280542
2.810745
0.811366
self.update( secondary=address, append_lists=append_lists)
def add_secondary(self, address, append_lists=False)
Add secondary IP addresses to this host element. If append_list is True, then add to existing list. Otherwise overwrite. :param list address: ip addresses to add in IPv4 or IPv6 format :param bool append_list: add to existing or overwrite (default: append) :return: None
7.610134
8.383814
0.907717
json = {'name': name, 'ip_range': ip_range, 'comment': comment} return ElementCreator(cls, json)
def create(cls, name, ip_range, comment=None)
Create an AddressRange element :param str name: Name of element :param str iprange: iprange of element :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: AddressRange
4.141319
5.561388
0.744656
ipv4_network = ipv4_network if ipv4_network else None ipv6_network = ipv6_network if ipv6_network else None json = {'name': name, 'ipv4_network': ipv4_network, 'ipv6_network': ipv6_network, 'comment': comment} return ElementCreato...
def create(cls, name, ipv4_network=None, ipv6_network=None, comment=None)
Create the network element :param str name: Name of element :param str ipv4_network: network cidr (optional if ipv6) :param str ipv6_network: network cidr (optional if ipv4) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason ...
2.035228
2.645192
0.769406
ne_ref = [] if ne_ref is None else ne_ref json = {'name': name, 'ne_ref': ne_ref, 'operator': operator} return json
def build_sub_expression(name, ne_ref=None, operator='union')
Static method to build and return the proper json for a sub-expression. A sub-expression would be the grouping of network elements used as a target match. For example, (network A or network B) would be considered a sub-expression. This can be used to compound sub-expressions before calli...
3.037498
3.641143
0.834216
sub_expression = [] if sub_expression is None else [sub_expression] json = {'name': name, 'operator': operator, 'ne_ref': ne_ref, 'sub_expression': sub_expression, 'comment': comment} return ElementCreator(cls, json)
def create(cls, name, ne_ref=None, operator='exclusion', sub_expression=None, comment=None)
Create the expression :param str name: name of expression :param list ne_ref: network element references for expression :param str operator: 'exclusion' (negation), 'union', 'intersection' (default: exclusion) :param dict sub_expression: sub expression used :param...
2.602231
3.430566
0.758543
headers = None if as_type in ['zip', 'txt', 'json']: if as_type == 'zip': if filename is None: raise MissingRequiredInput('Filename must be specified when ' 'downloading IPList as a zip file.') ...
def download(self, filename=None, as_type='zip')
Download the IPList. List format can be either zip, text or json. For large lists, it is recommended to use zip encoding. Filename is required for zip downloads. :param str filename: Name of file to save to (required for zip) :param str as_type: type of format to download in: txt,json,z...
4.109925
3.825024
1.074483
headers = {'content-type': 'multipart/form-data'} params = None files = None if filename: files = {'ip_addresses': open(filename, 'rb')} if as_type == 'json': headers = {'accept': 'application/json', 'content-type': 'applica...
def upload(self, filename=None, json=None, as_type='zip')
Upload an IPList to the SMC. The contents of the upload are not incremental to what is in the existing IPList. So if the intent is to add new entries, you should first retrieve the existing and append to the content, then upload. The only upload type that can be done without loading a fi...
3.640785
3.056862
1.19102
was_created, was_modified = False, False element = None try: element = cls.get(kwargs.get('name')) if append_lists: iplist = element.iplist diff = [i for i in kwargs.get('iplist', []) if i not in iplist] if diff:...
def update_or_create(cls, append_lists=True, with_status=False, **kwargs)
Update or create an IPList. :param bool append_lists: append to existing IP List :param dict kwargs: provide at minimum the name attribute and optionally match the create constructor values :raises FetchElementFailed: Reason for retrieval failure
3.48282
3.24644
1.072812
json = {'name': name, 'comment': comment} result = ElementCreator(cls, json) if result and iplist is not None: element = IPList(name) element.make_request( CreateElementFailed, method='create', resource='ip_address...
def create(cls, name, iplist=None, comment=None)
Create an IP List. It is also possible to add entries by supplying a list of IPs/networks, although this is optional. You can also use upload/download to add to the iplist. :param str name: name of ip list :param list iplist: list of ipaddress :param str comment: optional commen...
8.412846
8.43026
0.997934
updated, created = False, False alias = cls.get(name, raise_exc=False) if not alias: alias = cls.create(name) created = True elements = element_resolver(translation_values) if translation_values \ else [] if not creat...
def update_or_create(cls, name, engine, translation_values=None, with_status=False)
Update or create an Alias and it's mappings. :param str name: name of alias :param Engine engine: engine to modify alias translation values :param list(str,Element) translation_values: translation values as elements. Can be None if you want to unset any existing values ...
3.909569
3.724669
1.049642
for alias in alias_list: href = data.get('alias_ref') if alias.href == href: _alias = Alias(alias.name, href=href) _alias.resolved_value = data.get('resolved_value') _alias.typeof = alias._meta.type return _alias
def _from_engine(cls, data, alias_list)
Return an alias for the engine. The data is dict provided when calling engine.alias_resolving(). The alias list is the list of aliases pre-fetched from Alias.objects.all(). This will return an Alias element by taking the alias_ref and finding the name in the alias list. ...
6.211116
5.327877
1.165777
if not self.resolved_value: result = self.make_request( ElementNotFound, href=self.get_relation('resolve'), params={'for': engine}) self.resolved_value = result.get('resolved_value') return self.resolved_value
def resolve(self, engine)
Resolve this Alias to a specific value. Specify the engine by name to find it's value. :: alias = Alias('$$ Interface ID 0.ip') alias.resolve('smcpython-fw') :param str engine: name of engine to resolve value :raises ElementNotFound: if alias not found on engin...
8.505788
6.804433
1.250036
clone = self.copy() # Replace all filters with a combined filter bldata = TextFormat(field_format='name') # Preserve resolving fields for new filter if 'resolving' in self.format.data: bldata.set_resolving(**self.format.data['resolving']) # Resolve th...
def fetch_as_element(self, **kw)
Fetch the blacklist and return as an instance of Element. :return: generator returning element instances :rtype: BlacklistEntry
10.909658
10.089853
1.08125
start_port = self.blacklist.get('BlacklistEntrySourcePort') if start_port is not None: return '{}-{}'.format( start_port, self.blacklist.get('BlacklistEntrySourcePortRange')) return 'ANY'
def source_ports(self)
Source ports for this blacklist entry. If no ports are specified (i.e. ALL ports), 'ANY' is returned. :rtype: str
5.565017
4.845118
1.148582
start_port = self.blacklist.get('BlacklistEntryDestinationPort') if start_port is not None: return '{}-{}'.format( start_port, self.blacklist.get('BlacklistEntryDestinationPortRange')) return 'ANY'
def dest_ports(self)
Destination ports for this blacklist entry. If no ports are specified, 'ANY' is returned. :rtype: str
5.718526
4.737047
1.207192
return self._meta.name if self._meta.name else \ 'Rule @%s' % self.tag
def name(self)
Name attribute of rule element
16.298676
10.055939
1.620801
self.make_request( CreateRuleFailed, href=other_rule.get_relation('add_after'), method='create', json=self) self.delete()
def move_rule_after(self, other_rule)
Add this rule after another. This process will make a copy of the existing rule and add after the specified rule. If this raises an exception, processing is stopped. Otherwise the original rule is then deleted. You must re-retrieve the new element after running this operation as ...
17.244543
13.812578
1.248467
href = self.href params = None if add_pos is not None: href = self.add_at_position(add_pos) elif before or after: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=Cre...
def create_rule_section(self, name, add_pos=None, after=None, before=None)
Create a rule section in a Firewall Policy. To specify a specific numbering position for the rule section, use the `add_pos` field. If no position or before/after is specified, the rule section will be placed at the top which will encapsulate all rules below. Create a rule section for th...
6.488471
7.014072
0.925065