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
will have a max batch size of 200 records. This method will also
continuously return results until terminated. To make a single bounded
fetch, call :meth:`.fetch_batch` or :meth:`.fetch_raw`.
:param int sock_timeout: event loop interval
:return: raw dict returned from query
:rtype: dict(list) | 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 records
returned from the query in raw dict format. Any other dict key/values
from the raw query are ignored.
:param int max_recv: max number of socket receive calls before
returning from this query. If you want to wait longer for
results before returning, increase max_iterations (default: 0)
:return: list of query results
:rtype: list(dict) | 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
:meth:`.fetch_raw`.
:param formatter: Formatter type for data representation. Any type
in :py:mod:`smc_monitoring.models.formatters`.
:return: generator returning data in specified format
.. note:: You can provide your own formatter class,
see :py:mod:`smc_monitoring.models.formatters` for more info. | 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`.
:return: generator yielding results in specified format | 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 filter request, i.e. 'host', 'group',
'single_fw', 'network_elements', 'services',
'services_and_applications'
:param bool exact_match: Do an exact match by name, note this still can
return multiple entries
:rtype: SMCResult | 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
.. seealso:: :class:`smc.core.engine.Engine.blacklist`. Applying
a blacklist at the system level will be a global blacklist entry
versus an engine specific entry.
.. note:: If more advanced blacklist is required using source/destination
ports and protocols (udp/tcp), use kw to provide these arguments. See
:py:func:`smc.elements.other.prepare_blacklist` for more details. | 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
:return: dict | 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 TaskRunFailed: failure during export with reason
:rtype: DownloadTask | 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 are read-only attributes.
:rtype: list(ProtocolParameter) | 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.href):
return proxy | 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 isinstance(proxy_server, ProxyServer):
# Need the inspected service reference for the protocol
enabled_services = {svc.name:svc.href for svc in proxy_server.inspected_services}
if self.protocol_agent.name not in enabled_services:
raise MissingDependency('The specified ProxyServer %r does not enable '
'the required protocol %s' % (proxy_server.name, self.protocol_agent.name))
if self._inspected_service_ref != enabled_services.get(self.protocol_agent.name):
self.protocol_agent_values['inspected_service_ref'] = enabled_services.get(
self.protocol_agent.name)
updated = True
return updated | 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 the service to commit to SMC.
Example of updating a TCP Service using the HTTPS Protocol Agent
to set an HTTPS Inspection Exception::
>>> service = TCPService('httpsservice')
>>> service.protocol_agent
ProtocolAgent(name=HTTPS)
>>> for parameter in service.protocol_agent_values:
... parameter
...
ProxyServiceValue(name=redir_cis,description=Redirect connections to Proxy Server,proxy_server=None)
BooleanValue(name=http_enforce_safe_search,description=Enforce SafeSearch,value=0)
StringValue(name=http_server_stream_by_user_agent,description=Optimized server stream fingerprinting,value=Yes)
StringValue(name=http_url_logging,description=Logging of accessed URLs,value=Yes)
TlsInspectionPolicyValue(name=tls_policy,description=HTTPS Inspection Exceptions,tls_policy=None)
StringValue(name=tls_inspection,description=HTTPS decryption and inspection,value=No)
...
>>> service.protocol_agent_values.update(name='tls_policy', tls_policy=HTTPSInspectionExceptions('myexceptions'))
True
:param str name: The name of the parameter to update
:param dict kwargs: The keyword args to perform the update
:raises ElementNotFound: Can be thrown when an element reference
was passed but the element does not exist
:raises MissingDependency: A dependency was missing preventing the
update. This can happen when adding a ProxyServer for a protocol
that isn't enabled | 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_address'}) | 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
...
Condition(rank=1, element=ExternalBGPPeer(name=bgppeer))
Condition(rank=2, element=IPAccessList(name=myacl))
Condition(rank=3, element=Metric(value=20))
Then delete by rank. Call update on the rule after making the
modification.
:param int rank: rank of the condition to remove
:raises UpdateElementFailed: failed to update rule
:return: None | 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:
json.update(match_condition=[])
else:
if 'match_condition' in match_condition:
conditions = match_condition.pop('match_condition')
else:
conditions = MatchCondition()
if 'peer_address' in match_condition:
conditions.add_peer_address(
match_condition.pop('peer_address'))
if 'next_hop' in match_condition:
conditions.add_next_hop(
match_condition.pop('next_hop'))
if 'metric' in match_condition:
conditions.add_metric(
match_condition.pop('metric'))
if 'access_list' in match_condition:
conditions.add_access_list(
match_condition.pop('access_list'))
json.update(match_condition=conditions.conditions)
params = None
href = self.href
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=CreateRuleFailed,
href=href,
params=params,
json=json) | 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 str goto: specify a rule section to goto after if there
is a match condition. This will override the finish parameter
:param bool finish: finish stops the processing after a match condition.
If finish is False, processing will continue to the next rule.
:param RouteMap call: call another route map after matching.
:param str comment: optional comment for the rule
:param int add_pos: position to insert the rule, starting with position 1. If
the position value is greater than the number of rules, the rule is inserted at
the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually
exclusive with ``after`` and ``before`` params.
:param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos``
and ``before`` params.
:param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos``
and ``after`` params.
:param match_condition: keyword values identifying initial
values for the match condition. Valid keyword arguments
are 'access_list', 'next_hop', 'metric' and 'peer_address'.
You can also optionally pass the keyword 'match_condition'
with an instance of MatchCondition.
:raises CreateRuleFailed: failure to insert rule with reason
:raises ElementNotFound: if references elements in a match condition
this can be raised when the element specified is not found.
.. seealso:: :class:`~MatchCondition` for valid elements and
expected values for each type. | 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.internal_gateway.get_relation('generate_certificate'),
json={
'common_name': common_name,
'public_key_algorithm': public_key_algorithm,
'signature_algorithm': signature_algorithm,
'public_key_length': key_length,
'certificate_authority_href': cert_auth}) | 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_agent_ref': element_resolver(protocol_agent) or None,
'comment': comment}
return ElementCreator(cls, json) | 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
:param str,ProtocolAgent protocol_agent: optional protocol agent for
this service
:param str comment: optional comment for service
:raises CreateElementFailed: failure creating element with reason
:return: instance with meta
:rtype: TCPService | 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: failure creating element with reason
:return: instance with meta
:rtype: IPService | 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
:return: instance with meta
:rtype: EthernetService | 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 all records on 9/2/2017 from 06:25:30 to 06:26:30
in the local time zone CST::
dt_start = datetime(2017, 9, 2, 6, 25, 30, 0)
dt_end = datetime(2017, 9, 2, 6, 26, 30, 0)
query = LogQuery()
query.format.timezone('CST')
query.time_range.custom_range(
datetime_to_ms(dt_start),
datetime_to_ms(dt_end))
for record in query.fetch_batch():
print(record)
Last two minutes from current (py2)::
now = datetime.now()
start_time = int((now - timedelta(minutes=2)).strftime('%s'))*1000
Specific start time (py2)::
p2time = datetime.strptime("1.8.2017 08:26:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s')
p2time = int(s)*1000
Specific start time (py3)::
p3time = datetime.strptime("1.8.2017 08:40:42,76", "%d.%m.%Y %H:%M:%S,%f")
p3time.timestamp() * 1000
:param int start_time: search start time in milliseconds. Start time
represents the oldest timestamp.
:param int end_time: search end time in milliseconds. End time
represents the newest timestamp. | 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.finditer(cert_chain):
cert_type_matches.append((match.group(1), match.group(0)))
if not cert_type_matches:
raise ValueError('No certificate types were found. Valid types '
'are: {}'.format(CERT_TYPES))
return cert_type_matches | 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'},
files={
multi_part: open(certificate, 'rb') if not \
pem_as_string(certificate) else certificate
}) | 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: failure to import cert with reason
:raises IOError: file not found, permissions, etc.
:return: None | 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 \
pem_as_string(certificate) else certificate
}) | 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 import cert with reason
:raises IOError: file not found, permissions, etc.
:return: None | 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 available.
:rtype: str or None | 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_string(private_key) else private_key
}) | 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
:raises CertificateImportError: failure to import cert with reason
:raises IOError: file not found, permissions, etc.
:return: None | 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 determine the correct version and specify the api_version "
"parameter during session.login() if necessary.".format(rel)) | 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())
logger.debug('Event loop terminating.')
self.thread = threading.Thread(
target=event_loop)
self.thread.setDaemon(True)
self.thread.start() | 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 'fetch' in message:
self.fetch_id = message['fetch']
if 'failure' in message:
raise InvalidFetch(message['failure'])
if 'records' in message:
if 'added' in message['records']:
num = len(message['records']['added'])
else:
num = len(message['records'])
logger.debug('Query returned %s records.', num)
if self.max_recv:
itr += 1
if 'end' in message:
logger.debug('Received end message: %s' % message['end'])
yield message
break
yield message
if self.max_recv and self.max_recv <= itr:
break
except (Exception, KeyboardInterrupt, SystemExit, FetchAborted) as e:
logger.info('Caught exception in receive: %s -> %s', type(e), str(e))
if isinstance(e, (SystemExit, InvalidFetch)):
# propagate SystemExit, InvalidFetch
raise
finally:
if self.connected:
if self.fetch_id:
self.send(json.dumps({'abort': self.fetch_id}))
self.close()
if self.thread:
self.event.set()
while self.thread.isAlive():
self.event.wait(1)
logger.info('Closed web socket connection normally.') | 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=cls.typeof,
href=result.href)
if result.user_session.in_atomic_block:
result.user_session.transactions.append(element)
return element | 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.
:param Element,SubElement cls: class for creating
:param dict json: json payload
:param SMCException exception: exception class to override
:return: instance of type Element with meta
:rtype: Element | 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.type)
instance.data = cache
return instance
if raise_exc and smcresult.msg:
raise raise_exc(smcresult.msg) | 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)
element = elements.first() if elements.exists() else None
else:
try:
element = cls.get(kwargs.get('name'))
except ElementNotFound:
if not hasattr(cls, 'create'):
raise CreateElementFailed('%s: %r not found and this element '
'type does not have a create method.' %
(cls.__name__, kwargs['name']))
element = None
if not element:
params = {k: v() if callable(v) else v
for k, v in kwargs.items()}
try:
element = cls.create(**params)
was_created = True
except TypeError:
raise CreateElementFailed('%s: %r not found and missing '
'constructor arguments to properly create.' %
(cls.__name__, kwargs['name']))
if with_status:
return element, was_created
return element | 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 create() call. If filter_key is provided, this
should define an attribute and value to use for an exact match on
the element. Valid attributes are ones required on the elements
``create`` method or can be viewed by the elements class docs.
If no filter_key is provided, the name field will be used to
find the element.
::
>>> Network.get_or_create(
filter_key={'ipv4_network': '123.123.123.0/24'},
name='mynetwork',
ipv4_network='123.123.123.0/24')
Network(name=mynetwork)
The kwargs should be used to satisfy the elements ``create``
classmethod parameters to create in the event it cannot be found.
:param dict filter_key: filter key represents the data attribute and
value to use to find the element. If none is provided, the name
field will be used.
:param kwargs: keyword arguments mapping to the elements ``create``
method.
:param bool with_status: if set to True, a tuple is returned with
(Element, created), where the second tuple item indicates if
the element has been created or not.
:raises CreateElementFailed: could not create element with reason
:raises ElementNotFound: if read-only element does not exist
:return: element instance by type
:rtype: Element | 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:
Category.create(name=tag)
category.add_element(self.href) | 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 to add to this
element
:type tags: list(str)
:raises ElementNotFound: Category tag element name not found
:return: None
.. seealso:: :class:`smc.elements.other.Category` | 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" % extask.filename)
:param str filename: filename to store exported element
:raises TaskRunFailed: invalid permissions, invalid directory, or this
element is a system element and cannot be exported.
:return: DownloadTask
.. note:: It is not possible to export system elements | 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 last modified and it's current state.
:raises ResourceNotFound: If not running SMC version >= 6.3.2
:rtype: History | 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: failed to duplicate the element
:return: the newly created element
:rtype: Element | 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
updated = True
else:
for ca in contact_addresses:
if ca not in loc.addresses:
loc['addresses'].append(ca)
updated = True
else:
self.data.setdefault('multi_contact_addresses', []).append(
dict(addresses=contact_addresses, location_ref=location_ref))
created = True
if updated or created:
self.update()
if with_status:
return self, updated, created
return self | 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 have multiple address for a
single location).
:param list(str) contact_addresses: list of contact addresses for
the specified location
:param str location: location to place the contact address in
:param bool overwrite_existing: if you want to replace existing
location to address mappings set this to True. Otherwise if
the location exists, only new addresses are appended
:param bool with_status: if set to True, a 3-tuple is returned with
(Element, modified, created), where the second and third tuple
items are booleans indicating the status
:raises UpdateElementFailed: failed to update element with reason
:rtype: MultiContactAddress | 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 contact_address in mgt_server.contact_addresses:
... contact_address
...
ContactAddress(location=Default,addresses=[u'1.1.1.1'])
ContactAddress(location=foolocation,addresses=[u'12.12.12.12'])
:rtype: MultiContactAddress | 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': secondary if secondary else []}
return ElementCreator(cls, json) | 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 (default: 8080)
:param str username: optional username for authentication (default: None)
:param str password: password for username if defined (default: None)
:param str comment: optional comment
:param list secondary: secondary list of proxy server addresses
:raises CreateElementFailed: Failed to create the proxy element
:rtype: HttpProxy | 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: Defines how often the DNS entries can be
updated to the DNS server if the link status changes constantly
(default: 10)
:param list secondary: a secondary set of IP address for this element
:raises CreateElementFailed: Failed to create with reason
:rtype: DNSServer | 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_host_header,
'add_x_forwarded_for': add_x_forwarded_for,
'location_ref': element_resolver(location)
}
addresses = address.split(',')
json.update(address=addresses.pop(0))
json.update(ip_address=addresses if 'ip_address' not in kw else kw['ip_address'])
if proxy_service == 'forcepoint_ap-web_cloud':
for key in ('fp_proxy_key', 'fp_proxy_key_id', 'fp_proxy_user_id'):
if key not in kw:
raise CreateElementFailed('Missing required fp key when adding a '
'proxy server to forward to forcepoint. Missing key: %s' % key)
json[key] = kw.get(key)
return ElementCreator(cls, json) | 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 balance traffic, valid options are
ha (first available server), src, dst, srcdst (default: ha)
:param str proxy_service: which proxy service to use for next hop, options
are generic or forcepoint_ap-web_cloud
:param str,Element location: location for this proxy server
:param bool add_x_forwarded_for: add X-Forwarded-For header when using the
Generic Proxy forwarding method (default: False)
:param bool trust_host_header: trust the host header when using the Generic
Proxy forwarding method (default: False)
:param dict inspected_service: inspection services dict. Valid keys are
service_type and port. Service type valid values are HTTP, HTTPS, FTP or SMTP
and are case sensitive
:param str comment: optional comment
:param kw: keyword arguments are used to collect settings when the proxy_service
value is forcepoint_ap-web_cloud. Valid keys are `fp_proxy_key`,
`fp_proxy_key_id`, `fp_proxy_user_id`. The fp_proxy_key is the password value.
All other values are of type int | 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('name'),
type=node.related_element_type,
href=node.data.get('href')) | 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 tunnel interface
# where the gateway is bound to interface versus network
parent = node._parent
if parent.level == 'interface':
interface = parent
network = None
else:
network = parent
interface = network._parent
if on_network is not None:
if network and network.ip == on_network:
yield (interface, network, node)
else:
yield (interface, network, node) | 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 is specified, should be CIDR and
specifies a filter to only return gateways on that network when
an interface has multiple
:return: tuple of RoutingNode(interface,network,gateway)
:rtype: list | 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, 'address', False), getattr(gateway, 'ipv6_address', False)
# It's an engine, return true
elif element.typeof == 'network':
return getattr(element, 'ipv4_network', False), getattr(element, 'ipv6_network', False)
except AttributeError:
pass
# Always return true so that the calling function assumes the element
# is valid for the routing node. This could fail when submitting but
# we don't want to prevent adding elements yet since this could change
return True, True | 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, 'invalid', False) or \
getattr(network, 'to_delete', False):
network.delete() | 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 nicids
:raises DeleteElementFailed: delete element failed with reason | 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: invalid interface for engine
:return: Routing element, or None if not found
:rtype: Routing | 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 netlink to the route table of interface 0::
engine = Engine('vm')
rnode = engine.routing.get(0)
rnode.add_traffic_handler(StaticNetlink('mynetlink'))
Add a pre-defined netlink only to a specific network on an interface
with multiple addresses. Specify a netlink_gw for the netlink::
rnode = engine.routing.get(0)
rnode.add_traffic_handler(
StaticNetlink('mynetlink'),
netlink_gw=[Router('myrtr'), Host('myhost')],
network='172.18.1.0/24')
:param StaticNetlink,Multilink netlink: netlink element
:param list(Element) netlink_gw: list of elements that should be destinations
for this netlink. Typically these may be of type host, router, group, server,
network or engine.
:param str network: if network specified, only add OSPF to this network on interface
:raises UpdateElementFailed: failure updating routing
:raises ModificationAborted: Change must be made at the interface level
:raises ElementNotFound: ospf area not found
:return: Status of whether the route table was updated
:rtype: bool | 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(
ospf_area, communication_mode=communication_mode,
destinations=destinations)
return self._add_gateway_node('ospfv2_area', routing_node_gateway, network) | 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
will receive the OSPF area by default unless the ``network`` parameter
is specified. OSPF cannot be applied to IPv6 networks.
Example of adding an area to interface routing node::
area = OSPFArea('area0') #obtain area resource
#Set on routing interface 0
interface = engine.routing.get(0)
interface.add_ospf_area(area)
.. note:: If UNICAST is specified, you must also provide a unicast_ref
of element type Host to identify the remote host. If no
unicast_ref is provided, this is skipped
:param OSPFArea ospf_area: OSPF area instance or href
:param OSPFInterfaceSetting ospf_interface_setting: used to override the
OSPF settings for this interface (optional)
:param str network: if network specified, only add OSPF to this network
on interface
:param str communication_mode: NOT_FORCED|POINT_TO_POINT|PASSIVE|UNICAST
:param Element unicast_ref: Element used as unicast gw (required for UNICAST)
:raises ModificationAborted: Change must be made at the interface level
:raises UpdateElementFailed: failure updating routing
:raises ElementNotFound: ospf area not found
:return: Status of whether the route table was updated
:rtype: bool | 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.routing.get(0)
interface.add_bgp_peering(
BGPPeering('mypeer'),
ExternalBGPPeer('neighbor'))
:param BGPPeering bgp_peering: BGP Peer element
:param ExternalBGPPeer,Engine external_bgp_peer: peer element or href
:param str network: if network specified, only add OSPF to this network
on interface
:raises ModificationAborted: Change must be made at the interface level
:raises UpdateElementFailed: failed to add BGP
:return: Status of whether the route table was updated
:rtype: bool | 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
addresses on different networks.
::
>>> engine = Engine('ve-1')
>>> itf = engine.routing.get(0)
>>> itf.add_static_route(
gateway=Router('tmprouter'),
destination=[Group('routegroup')])
:param Element gateway: gateway for this route (Router, Host)
:param Element destination: destination network/s for this route.
:type destination: list(Host, Router, ..)
:raises ModificationAborted: Change must be made at the interface level
:raises UpdateElementFailed: failure to update routing table
:return: Status of whether the route table was updated
:rtype: bool | 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([Network('mynetwork')])
:param list Network: list of network elements to add to
this DHCP gateway
:raises ModificationAborted: Change must be made at the interface level
:raises UpdateElementFailed: failure to update routing table
:return: Status of whether the route table was updated
:rtype: bool | 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 = True
# Have peering
else:
peers = [node.routing_node_element for peer in peering
for node in peer]
for destination in routing_node_gateway.destinations:
if destination not in peers:
peering[0].data.setdefault('routing_node', []).append(
{'level': 'any', 'href': destination.href,
'name': destination.name})
modified = True
if modified:
self.update()
return 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
:rtype: bool | 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(routing_node_gateway)
# Find any existing gateways
routing_node = list(gateway_by_type(self, type=gw_type, on_network=network))
_networks = [netwk for netwk in self if netwk.ip == network] if network is \
not None else list(self)
# Routing Node Gateway to add as Element
gateway_element_type = routing_node_gateway.routing_node_element
modified = False
for network in _networks:
# Short circuit for dynamic interfaces
if getattr(network, 'dynamic_classid', None):
network.data.setdefault('routing_node', []).append(
routing_node_gateway)
modified = True
break
# Used for comparison to
this_network_node = network.routing_node_element
if routing_node and any(netwk for _intf, netwk, gw in routing_node
if netwk.routing_node_element == this_network_node and
gateway_element_type == gw.routing_node_element):
# A gateway exists on this network
for gw in network:
if gw.routing_node_element == gateway_element_type:
existing_dests = [node.routing_node_element for node in gw]
for destination in routing_node_gateway.destinations:
is_valid_destination = False
if destination not in existing_dests:
dest_ipv4, dest_ipv6 = _which_ip_protocol(destination)
if len(network.ip.split(':')) > 1: # IPv6
if dest_ipv6:
is_valid_destination = True
else:
if dest_ipv4:
is_valid_destination = True
if is_valid_destination:
gw.data.setdefault('routing_node', []).append(
{'level': 'any', 'href': destination.href,
'name': destination.name})
modified = True
else: # Gateway doesn't exist
gw_ipv4, gw_ipv6 = _which_ip_protocol(gateway_element_type) # ipv4, ipv6 or both
if len(network.ip.split(':')) > 1:
if gw_ipv6:
network.data.setdefault('routing_node', []).append(
routing_node_gateway)
modified = True
else: # IPv4
if gw_ipv4:
network.data.setdefault('routing_node', []).append(
routing_node_gateway)
modified = True
if modified:
self.update()
return modified | 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
destinations specified do not have IP addresses that are valid, they
are still added (i.e. IPv4 gateway with IPv6 destination is considered
invalid).
:param Routing self: the routing node, should be the interface routing node
:param str gw_type: type of gateway, i.e. netlink, ospfv2_area, etc
:param RoutingNodeGateway route_node_gateway: gateway element
:param str network: network to bind to. If none, all networks
:return: Whether a change was made or not
:rtype: bool | 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:
# Tunnel Interface binds gateways to the interface
if network.level == 'gateway' and network.data.get('href') == element:
network.delete()
node_changed = True
break
for gateway in network:
if gateway.data.get('href') == element:
gateway.delete()
node_changed = True
return node_changed | 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(StaticNetlink('mynetlink'))
Only from a specific network on a multi-address interface::
interface0.remove_route_gateway(
StaticNetlink('mynetlink'),
network='172.18.1.0/24')
:param str,Element element: element to remove from this routing node
:param str network: if network specified, only add OSPF to this
network on interface
:raises ModificationAborted: Change must be made at the interface level
:raises UpdateElementFailed: failure to update routing table
:return: Status of whether the entry was removed (i.e. or not found)
:rtype: bool | 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',
'href': element.href,
'level': self.level,
'validity': 'enable',
'name': element.name})
self.update()
return True
return 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'), Host(..)
:raises CreateElementFailed: failed adding entry
:raises ElementNotFound: element entry specified not in SMC
:return: whether entry was added
:rtype: bool | 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 sure it was user added
_nodes.append(network.data)
if len(_nodes) != len_before_change:
self.data['antispoofing_node'] = _nodes
self.update()
return True
return False | 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 field in delete_by)] | 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': secondaries,
'comment': comment}
return ElementCreator(cls, json) | 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)
:raises CreateElementFailed: element creation failed with reason
:return: instance with meta
:rtype: Host
.. note:: Either ipv4 or ipv6 address is required | 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 ElementCreator(cls, json) | 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
:return: instance with meta
:rtype: Network
.. note:: Either an ipv4_network or ipv6_network must be specified | 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
calling create.
:param str name: name of sub-expression
:param list ne_ref: network elements references
:param str operator: exclusion (negation), union, intersection (default: union)
:return: JSON of subexpression. Use in :func:`~create` constructor | 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 str comment: optional comment
:raises CreateElementFailed: element creation failed with reason
:return: instance with meta
:rtype: Expression | 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.')
filename = '{}'.format(filename)
elif as_type == 'txt':
headers = {'accept': 'text/plain'}
elif as_type == 'json':
headers = {'accept': 'application/json'}
result = self.make_request(
FetchElementFailed,
raw_result=True,
resource='ip_address_list',
filename=filename,
headers=headers)
return result.json if as_type == 'json' else result.content | 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,zip (default: zip)
:raises IOError: problem writing to destination filename
:return: None | 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': 'application/json'}
elif as_type == 'txt':
params = {'format': 'txt'}
self.make_request(
CreateElementFailed,
method='create',
resource='ip_address_list',
headers=headers, files=files, json=json,
params=params) | 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 file as
the source is as_type='json'.
:param str filename: required for zip/txt uploads
:param str json: required for json uploads
:param str as_type: type of format to upload in: txt|json|zip (default)
:raises IOError: filename specified cannot be loaded
:raises CreateElementFailed: element creation failed with reason
:return: None | 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:
iplist.extend(diff)
else:
iplist = []
else:
iplist = kwargs.get('iplist', [])
if iplist:
element.upload(json={'ip': iplist}, as_type='json')
was_modified = True
except ElementNotFound:
element = cls.create(
kwargs.get('name'),
iplist = kwargs.get('iplist', []))
was_created = True
if with_status:
return element, was_modified, was_created
return element | 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_list',
json={'ip': iplist})
return result | 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 comment
:raises CreateElementFailed: element creation failed with reason
:return: instance with meta
:rtype: IPList | 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 created: # possible update
# Does alias already exist with a value
alias_value = [_alias
for _alias in engine.data.get('alias_value', [])
if _alias.get('alias_ref') == alias.href]
if alias_value:
if not elements:
alias_value[0].update(translated_element=None)
updated = True
else:
t_values = alias_value[0].get('translated_element')
if set(t_values) ^ set(elements):
t_values[:] = elements
updated = True
if elements and (created or not updated):
engine.data.setdefault('alias_value', []).append(
{'alias_ref': alias.href,
'translated_element': elements})
updated = True
if updated:
engine.update()
if with_status:
return alias, updated, created
return alias | 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
:param bool with_status: if set to True, a 3-tuple is returned with
(Element, modified, created), where the second and third tuple
items are booleans indicating the status
:raises ElementNotFound: specified engine or translation values are not
found in the SMC
:raises UpdateElementFailed: update failed with reason
:raises CreateElementFailed: create failed with reason
:rtype: Element | 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.
:rtype: Alias | 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 engine
:return: alias resolving values
:rtype: list | 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 the entry ID to match SMC
blid = TextFormat(field_format='pretty')
blid.field_ids([LogField.BLACKLISTENTRYID])
combined = CombinedFormat(bldata=bldata, blid=blid)
clone.update_format(combined)
for list_of_results in clone.fetch_raw(**kw):
for entry in list_of_results:
data = entry.get('bldata')
data.update(**entry.get('blid'))
yield BlacklistEntry(**data) | 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 new references will be created.
:param other_rule Rule: rule where this rule will be positioned after
:raises CreateRuleFailed: failed to duplicate this rule, no move
is made | 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=CreateRuleFailed,
href=href,
params=params,
json={'comment': name}) | 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 the relavant policy::
policy = FirewallPolicy('mypolicy')
policy.fw_ipv4_access_rules.create_rule_section(name='attop')
# For NAT rules
policy.fw_ipv4_nat_rules.create_rule_section(name='mysection', add_pos=5)
:param str name: create a rule section by name
:param int add_pos: position to insert the rule, starting with position 1.
If the position value is greater than the number of rules, the rule is
inserted at the bottom. If add_pos is not provided, rule is inserted in
position 1. Mutually exclusive with ``after`` and ``before`` params.
:param str after: Rule tag to add this rule after. Mutually exclusive with
``add_pos`` and ``before`` params.
:param str before: Rule tag to add this rule before. Mutually exclusive with
``add_pos`` and ``after`` params.
:raises MissingRequiredInput: when options are specified the need additional
setting, i.e. use_vpn action requires a vpn policy be specified.
:raises CreateRuleFailed: rule creation failure
:return: the created ipv4 rule
:rtype: IPv4Rule | 6.488471 | 7.014072 | 0.925065 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.