code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
rule_values = self.update_targets(sources, destinations, services) rule_values.update(name=name, comment=comment) rule_values.update(is_disabled=is_disabled) if isinstance(action, Action): rule_action = action else: rule_action = Action() ...
def create(self, name, sources=None, destinations=None, services=None, action='allow', is_disabled=False, logical_interfaces=None, add_pos=None, after=None, before=None, comment=None)
Create an Ethernet rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[s...
3.532212
3.634791
0.971778
for intvalue, sevname in SEVERITY.items(): if name.lower() == sevname: return intvalue return 1
def _severity_by_name(name)
Return the severity integer value by it's name. If not found, return 'information'. :rtype: int
5.337548
5.423367
0.984176
for param in self.data.get('situation_parameters', []): cache = ElementCache(data=self.make_request(href=param)) yield type('SituationParameter', (SituationParameter,), { 'data': cache})(name=cache.name, type=cache.type, href=param)
def situation_parameters(self)
Situation parameters defining detection logic for the context. This will return a list of SituationParameter indicating how the detection is made, i.e. regular expression, integer value, etc. :rtype: list(SituationParameter)
7.38067
8.979151
0.821979
for param in self.data.get('parameter_values', []): cache = ElementCache(data=self.make_request(href=param)) name = '{}'.format(cache.type.title()).replace('_', '') yield type(name, (SituationParameterValue,), { 'data': cache})(name=cache.name, type=c...
def parameter_values(self)
Parameter values for this inspection situation. This correlate to the the situation_context. :rtype: list(SituationParameterValue)
9.377131
8.598848
1.09051
try: json = { 'name': name, 'comment': comment, 'description': description, 'situation_context_ref': situation_context.href, 'attacker': attacker, 'victim': target, 'severity': _severity_by_name(severity)} ...
def create(cls, name, situation_context, attacker=None, target=None, severity='information', situation_type=None, description=None, comment=None)
Create an inspection situation. :param str name: name of the situation :param InspectionSituationContext situation_context: The situation context type used to define this situation. Identifies the proper parameter that identifies how the situation is defined (i.e. regex,...
6.397536
6.47761
0.987638
for parameter in self.situation_context.situation_parameters: if parameter.type == 'regexp': return self.add_parameter_value( 'reg_exp_situation_parameter_values', **{'parameter_ref': parameter.href, 'reg_exp': r...
def create_regular_expression(self, regexp)
Create a regular expression for this inspection situation context. The inspection situation must be using an inspection context that supports regex. :param str regexp: regular expression string :raises CreateElementFailed: failed to modify the situation
10.443574
8.92519
1.170123
if not filename: filename = '{}{}'.format(self.name, '.zip') try: self.make_request( EngineCommandFailed, resource='content', filename=filename) except IOError as e: raise EngineCommandFailed("...
def download(self, filename=None)
Download snapshot to filename :param str filename: fully qualified path including filename .zip :raises EngineCommandFailed: IOError occurred downloading snapshot :return: None
8.598282
6.010433
1.43056
return Task.execute(self, 'upload', params={'filter': engine}, timeout=timeout, wait_for_finish=wait_for_finish, **kw)
def upload(self, engine, timeout=5, wait_for_finish=False, **kw)
Upload policy to specific device. Using wait for finish returns a poller thread for monitoring progress:: policy = FirewallPolicy('_NSX_Master_Default') poller = policy.upload('myfirewall', wait_for_finish=True) while not poller.done(): poller.wait(3) ...
5.562015
6.390201
0.870397
result = self.make_request( resource='search_rule', params={'filter': search}) if result: results = [] for data in result: typeof = data.get('type') if 'ethernet' in typeof: klazz = look...
def search_rule(self, search)
Search a rule for a rule tag or name value Result will be the meta data for rule (name, href, type) Searching for a rule in specific policy:: f = FirewallPolicy(policy) search = f.search_rule(searchable) :param str search: search string :return: rule elements m...
4.406803
4.713205
0.934991
json = {'target_ref': engine.href, 'duration_type': duration_type} return [RuleCounter(**rule) for rule in self.make_request( method='create', resource='rule_counter', json=json)]
def rule_counters(self, engine, duration_type='one_week', duration=0, start_time=0)
.. versionadded:: 0.5.6 Obtain rule counters for this policy. Requires SMC >= 6.2 Rule counters can be obtained for a given policy and duration for those counters can be provided in duration_type. A custom start range can also be provided. :param Engine engine: the ...
7.377041
7.736112
0.953585
vpn_profile = element_resolver(vpn_profile) or \ VPNProfile('VPN-A Suite').href json = {'mobile_vpn_topology_mode': mobile_vpn_toplogy_mode, 'name': name, 'nat': nat, 'vpn_profile': vpn_profile} try: retur...
def create(cls, name, nat=False, mobile_vpn_toplogy_mode=None, vpn_profile=None)
Create a new policy based VPN :param name: name of vpn policy :param bool nat: whether to apply NAT to the VPN (default False) :param mobile_vpn_toplogy_mode: whether to allow remote vpn :param VPNProfile vpn_profile: reference to VPN profile, or uses default :rtype: PolicyVPN
5.469472
5.86033
0.933304
if self.nat: self.data['nat'] = False else: self.data['nat'] = True
def enable_disable_nat(self)
Enable or disable NAT on this policy. If NAT is disabled, it will be enabled and vice versa. :return: None
3.973869
4.839147
0.821192
try: gateway = gateway.vpn.internal_gateway.href # Engine except AttributeError: gateway = element_resolver(gateway) # External Gateway self.make_request( PolicyCommandFailed, method='create', resource='mobile_gateway_...
def add_mobile_gateway(self, gateway)
Add a mobile VPN gateway to this policy VPN. Example of adding or removing a mobile VPN gateway:: policy_vpn = PolicyVPN('myvpn') policy_vpn.open() policy_vpn.add_mobile_vpn_gateway(ExternalGateway('extgw3')) for mobile_gateway in policy_vpn...
21.067366
10.675525
1.973427
try: vpn = PolicyVPN(vpn_policy) vpn.open() if vpn_role == 'central': vpn.add_central_gateway(internal_gateway_href) else: vpn.add_satellite_gateway(internal_gateway_href) vpn.save() vpn.close() ...
def add_internal_gateway_to_vpn(internal_gateway_href, vpn_policy, vpn_role='central')
Add an internal gateway (managed engine node) to a VPN policy based on the internal gateway href. :param str internal_gateway_href: href for engine internal gw :param str vpn_policy: name of vpn policy :param str vpn_role: central|satellite :return: True for success :rty...
2.704595
2.561956
1.055676
if self.enabled: self.update(enabled=False) else: self.update(enabled=True)
def enable_disable(self)
Enable or disable the tunnel link between endpoints. :raises UpdateElementFailed: failed with reason :return: None
3.400212
3.41918
0.994453
json = {} directions = {src: 'end_point1', dst: 'end_point2'} for direction, key in directions.items(): json[key] = {'address_mode': 'any'} if \ 'any' in direction.lower() else {'address_mode': 'address', 'ip_network': direction} if src_port1: json.se...
def prepare_blacklist(src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp')
Create a blacklist entry. A blacklist can be added directly from the engine node, or from the system context. If submitting from the system context, it becomes a global blacklist. This will return the properly formatted json to submit. :param src: source address, with cidr, i.e. 10.10.10.1...
3.115662
3.288182
0.947533
element = element_resolver(element) self.make_request( ModificationFailed, method='create', resource='category_add_element', json={'value': element})
def add_element(self, element)
Element can be href or type :py:class:`smc.base.model.Element` :: >>> from smc.elements.other import Category >>> category = Category('foo') >>> category.add_element(Host('kali')) :param str,Element element: element to add to tag :raises: ModificationFailed:...
19.591761
19.233313
1.018637
tags = element_resolver(tags) self.update( category_parent_ref=tags, append_lists=append_lists)
def add_category_tag(self, tags, append_lists=True)
Add this category to a category tag (group). This provides drop down filters in the SMC UI by category tag. :param list tags: category tag by name :param bool append_lists: append to existing tags or overwrite default: append) :type tags: list(str) :return: N...
12.433796
15.082115
0.824407
categories = element_resolver(categories) diff = [category for category in self.data['category_child_ref'] if category not in categories] self.update(category_child_ref=diff)
def remove_category(self, categories)
Remove a category from this Category Tag (group). :param list categories: categories to remove :type categories: list(str,Element) :return: None
7.813067
8.384337
0.931865
self.entries.setdefault('entries', []).append(prepare_blacklist( src, dst, duration, src_port1, src_port2, src_proto, dst_port1, dst_port2, dst_proto))
def add_entry(self, src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp')
Create a blacklist entry. A blacklist can be added directly from the engine node, or from the system context. If submitting from the system context, it becomes a global blacklist. This will return the properly formatted json to submit. :param src: source address...
3.396958
3.404655
0.997739
was_created, was_modified = False, False element = None try: element = cls.get(kwargs.get('name')) was_modified = element.update_members( kwargs.get('members', []), append_lists=append_lists, remove_members=remove...
def update_or_create(cls, append_lists=True, with_status=False, remove_members=False, **kwargs)
Update or create group entries. If the group exists, the members will be updated. Set append_lists=True to add new members to the list, or False to reset the list to the provided members. If setting remove_members, this will override append_lists if set. :param bool append_lists...
3.053502
2.785161
1.096347
if members: elements = [element_resolver(element) for element in members] if remove_members: element = [e for e in self.members if e not in elements] if set(element) == set(self.members): remove_members = element = False ...
def update_members(self, members, append_lists=False, remove_members=False)
Update group members with member list. Set append=True to append to existing members, or append=False to overwrite. :param list members: new members for group by href or Element :type members: list[str, Element] :param bool append_lists: whether to append :param bool remove_memb...
3.307923
3.388077
0.976342
element = [] if members is None else element_resolver(members) json = {'name': name, 'element': element, 'comment': comment} return ElementCreator(cls, json)
def create(cls, name, members=None, comment=None)
Create the TCP Service group :param str name: name of tcp service group :param list element: tcp services by element or href :type element: list(str,Element) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: TCPServiceGr...
8.056517
7.090465
1.136247
kw.setdefault('params', {}).update( {'start_time': start_time, 'end_time': end_time}) if senders: kw.setdefault('json', {}).update({'senders': element_resolver(senders)}) return Task.execute(self, 'generate', timeout=timeout, wait_for_...
def generate(self, start_time=0, end_time=0, senders=None, wait_for_finish=False, timeout=5, **kw): # @ReservedAssignment if start_time and end_time
Generate the report and optionally wait for results. You can optionally add filters to the report by providing the senders argument as a list of type Element:: report = ReportDesign('Firewall Weekly Summary') begin = datetime_to_ms(datetime.strptime("2018-02-03T00:00:00"...
4.130214
4.593247
0.899193
result = self.make_request( CreateElementFailed, resource='create_design', raw_result=True, method='create', params={'name': name}) return ReportDesign( href=result.href, type=self.typeof, name=name)
def create_design(self, name)
Create a report design based on an existing template. :param str name: Name of new report design :raises CreateElementFailed: failed to create template :rtype: ReportDesign
13.168143
9.819635
1.341001
self.make_request( raw_result=True, resource='export', filename=filename, headers = {'accept': 'application/pdf'})
def export_pdf(self, filename)
Export the report in PDF format. Specify a path for which to save the file, including the trailing filename. :param str filename: path including filename :return: None
9.087857
10.193156
0.891565
result = self.make_request( resource='export', params={'format': 'txt'}, filename=filename, raw_result=True, headers = {'accept': 'text/plain'}) if not filename: return result.content
def export_text(self, filename=None)
Export in text format. Optionally provide a filename to save to. :param str filename: path including filename (optional) :return: None
5.59273
6.206647
0.901087
group = monitoring_group or TunnelMonitoringGroup('Uncategorized') profile = vpn_profile or VPNProfile('VPN-A Suite') json = { 'name': name, 'mtu': mtu, 'ttl': ttl, 'enabled': enabled, 'monitoring_group_ref': group.hre...
def create_ipsec_tunnel(cls, name, local_endpoint, remote_endpoint, preshared_key=None, monitoring_group=None, vpn_profile=None, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None)
The VPN tunnel type negotiates IPsec tunnels in the same way as policy-based VPNs, but traffic is selected to be sent into the tunnel based on routing. :param str name: name of VPN :param TunnelEndpoint local_endpoint: the local side endpoint for this VPN. :p...
3.436191
2.530943
1.357672
json = { 'name': name, 'ttl': ttl, 'mtu': mtu, 'pmtu_discovery': pmtu_discovery, 'tunnel_encryption': 'tunnel_mode', 'tunnel_mode': 'gre', 'enabled': enabled, 'comment': comment, 'rbvpn_tunnel_si...
def create_gre_tunnel_mode(cls, name, local_endpoint, remote_endpoint, policy_vpn, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None)
Create a GRE based tunnel mode route VPN. Tunnel mode GRE wraps the GRE tunnel in an IPSEC tunnel to provide encrypted end-to-end security. Therefore a policy based VPN is required to 'wrap' the GRE into IPSEC. :param str name: name of VPN :param TunnelEndpoint local_en...
3.123752
2.865558
1.090103
return cls.create_gre_tunnel_mode( name, local_endpoint, remote_endpoint, policy_vpn=None, mtu=mtu, pmtu_discovery=pmtu_discovery, ttl=ttl, enabled=enabled, comment=comment)
def create_gre_tunnel_no_encryption(cls, name, local_endpoint, remote_endpoint, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None)
Create a GRE Tunnel with no encryption. See `create_gre_tunnel_mode` for constructor descriptions.
2.621252
2.477072
1.058206
if self.data.get('preshared_key'): self.update(preshared_key=new_key)
def set_preshared_key(self, new_key)
Set the preshared key for this VPN. A pre-shared key is only present when the tunnel type is 'VPN' or the encryption mode is 'transport'. :return: None
3.920507
4.319486
0.907633
if self.endpoint_ref and self.tunnel_interface_ref: return InternalEndpoint(href=self.endpoint_ref) return Element.from_href(self.endpoint_ref)
def endpoint(self)
Endpoint is used to specify which interface is enabled for VPN. This is the InternalEndpoint property of the InternalGateway. :return: internal endpoint where VPN is enabled :rtype: InternalEndpoint,ExternalGateway
10.594459
8.04716
1.316546
tunnel_interface = tunnel_interface.href if tunnel_interface else None endpoint = endpoint.href if endpoint else None return TunnelEndpoint( tunnel_interface_ref=tunnel_interface, endpoint_ref=endpoint, ip_address=remote_address)
def create_gre_tunnel_endpoint(cls, endpoint=None, tunnel_interface=None, remote_address=None)
Create the GRE tunnel mode or no encryption mode endpoint. If the GRE tunnel mode endpoint is an SMC managed device, both an endpoint and a tunnel interface is required. If the endpoint is externally managed, only an IP address is required. :param InternalEndpoint,ExternalEndpoi...
3.049352
3.356816
0.908406
tunnel_interface = tunnel_interface.href if tunnel_interface else None return TunnelEndpoint( endpoint_ref=endpoint.href, tunnel_interface_ref=tunnel_interface)
def create_gre_transport_endpoint(cls, endpoint, tunnel_interface=None)
Create the GRE transport mode endpoint. If the GRE transport mode endpoint is an SMC managed device, both an endpoint and a tunnel interface is required. If the GRE endpoint is an externally managed device, only an endpoint is required. :param InternalEndpoint,ExternalEndpoint e...
4.324216
5.072681
0.852452
tunnel_interface = tunnel_interface.href if tunnel_interface else None return TunnelEndpoint( gateway_ref=gateway.href, tunnel_interface_ref=tunnel_interface)
def create_ipsec_endpoint(cls, gateway, tunnel_interface=None)
Create the VPN tunnel endpoint. If the VPN tunnel endpoint is an SMC managed device, both a gateway and a tunnel interface is required. If the VPN endpoint is an externally managed device, only a gateway is required. :param InternalGateway,ExternalGateway gateway: the gateway ...
4.15316
4.62704
0.897585
self.interface.set_auth_request(interface_id, address) self._engine.update()
def set_auth_request(self, interface_id, address=None)
Set the authentication request field for the specified engine.
5.705154
6.426922
0.887696
self.interface.set_unset(interface_id, 'primary_heartbeat') self._engine.update()
def set_primary_heartbeat(self, interface_id)
Set this interface as the primary heartbeat for this engine. This will 'unset' the current primary heartbeat and move to specified interface_id. Clusters and Master NGFW Engines only. :param str,int interface_id: interface specified for primary mgmt :raises InterfaceNot...
11.032043
11.195998
0.985356
self.interface.set_unset(interface_id, 'backup_heartbeat') self._engine.update()
def set_backup_heartbeat(self, interface_id)
Set this interface as the backup heartbeat interface. Clusters and Master NGFW Engines only. :param str,int interface_id: interface as backup :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: failure to update interface :return: Non...
11.351171
12.672351
0.895743
intfattr = ['primary_mgt', 'outgoing'] if self.interface.engine.type in ('virtual_fw',): intfattr.remove('primary_mgt') for attribute in intfattr: self.interface.set_unset(interface_id, attribute, address) if auth_request is not None: ...
def set_primary_mgt(self, interface_id, auth_request=None, address=None)
Specifies the Primary Control IP address for Management Server contact. For single FW and cluster FW's, this will enable 'Outgoing', 'Auth Request' and the 'Primary Control' interface. For clusters, the primary heartbeat will NOT follow this change and should be set separately using :met...
5.068781
4.467801
1.134514
self.interface.set_unset(interface_id, 'backup_mgt') self._engine.update()
def set_backup_mgt(self, interface_id)
Set this interface as a backup management interface. Backup management interfaces cannot be placed on an interface with only a CVI (requires node interface/s). To 'unset' the specified interface address, set interface id to None :: engine.interface_options.s...
10.58088
10.302416
1.027029
self.interface.set_unset(interface_id, 'outgoing') self._engine.update()
def set_outgoing(self, interface_id)
Specifies the IP address that the engine uses to initiate connections (such as for system communications and ping) through an interface that has no Node Dedicated IP Address. In clusters, you must select an interface that has an IP address defined for all nodes. Setting primary_mgt also ...
12.243402
12.883636
0.950306
self._interface.data.update(qos_limit=-1, qos_mode='dscp', qos_policy_ref=qos_policy.href)
def dscp_marking_and_throttling(self, qos_policy)
Enable DSCP marking and throttling on the interface. This requires that you provide a QoS policy to which identifies DSCP tags and how to prioritize that traffic. :param QoSPolicy qos_policy: the qos policy to apply to the interface
13.229636
11.665018
1.134129
super(Interface, self).delete() for route in self._engine.routing: if route.to_delete: route.delete() self._engine._del_cache()
def delete(self)
Override delete in parent class, this will also delete the routing configuration referencing this interface. :: engine = Engine('vm') interface = engine.interface.get(2) interface.delete()
9.897369
6.848115
1.445269
super(Interface, self).update(*args, **kw) self._engine._del_cache() return self
def update(self, *args, **kw)
Update/save this interface information back to SMC. When interface changes are made, especially to sub interfaces, call `update` on the top level interface. Example of changing the IP address of an interface:: >>> engine = Engine('sg_vm') >>> interface = engine.physical...
9.359992
13.189214
0.70967
addresses = [] for i in self.all_interfaces: if isinstance(i, VlanInterface): for v in i.interfaces: addresses.append((v.address, v.network_value, v.nicid)) else: addresses.append((i.address, i.network_value, i.nicid)) ...
def addresses(self)
Return 3-tuple with (address, network, nicid) :return: address related information of interface as 3-tuple list :rtype: list
3.764827
2.913836
1.292052
interfaces = self.all_interfaces sub_interfaces = [] for interface in interfaces: if isinstance(interface, VlanInterface): if interface.has_interfaces: for subaddr in interface.interfaces: sub_interfaces.append(suba...
def sub_interfaces(self)
Flatten out all top level interfaces and only return sub interfaces. It is recommended to use :meth:`~all_interfaces`, :meth:`~interfaces` or :meth:`~vlan_interfaces` which return collections with helper methods to get sub interfaces based on index or attribute value pairs. :rtype: list...
2.8217
2.847647
0.990888
for interface in self.all_interfaces: if isinstance(interface, VlanInterface): if any(vlan for vlan in interface.interfaces if getattr(vlan, name)): return True else: if getattr(interface, name): ...
def get_boolean(self, name)
Get the boolean value for attribute specified from the sub interface/s.
4.26403
3.756059
1.13524
try: routing = self._engine.routing.get(self.interface_id) for route in routing: if route.invalid or route.to_delete: route.delete() except InterfaceNotFound: # Only VLAN identifiers, so no routing pass
def delete_invalid_route(self)
Delete any invalid routes for this interface. An invalid route is a left over when an interface is changed to a different network. :return: None
11.927411
10.998805
1.084428
self.data['interfaces'] = [] if self.typeof != 'tunnel_interface': self.data['vlanInterfaces'] = [] self.update() self.delete_invalid_route()
def reset_interface(self)
Reset the interface by removing all assigned addresses and VLANs. This will not delete the interface itself, only the sub interfaces that may have addresses assigned. This will not affect inline or capture interfaces. Note that if this interface is used as a primary control, auth request...
12.384481
12.173185
1.017358
splitted = str(interface_id).split('-') if1 = splitted[0] for interface in self.all_interfaces: # Set top level interface, this only uses a single value which # will be the leftmost interface if isinstance(interface, VlanInterface): ...
def change_interface_id(self, interface_id)
Change the interface ID for this interface. This can be used on any interface type. If the interface is an Inline interface, you must provide the ``interface_id`` in format '1-2' to define both interfaces in the pair. The change is committed after calling this method. :: ...
4.636794
4.598841
1.008253
updated = False for name, value in other_interface.data.items(): if isinstance(value, string_types) and getattr(self, name, None) != value: self.data[name] = value updated = True elif value is None and getattr(self, name, None): ...
def _update_interface(self, other_interface)
Update the physical interface base settings with another interface. Only set updated if a value has changed. You must also call `update` on the interface if modifications are made. This is called from other interfaces (i.e. PhysicalInterface, ClusterPhysicalInterface, etc) to update the ...
2.628862
2.531402
1.038501
base_updated = self._update_interface(other_interface) mgmt = ('auth_request', 'backup_heartbeat', 'backup_mgt', 'primary_mgt', 'primary_heartbeat', 'outgoing') updated = False invalid_routes = [] def process_interfaces(current,...
def update_interface(self, other_interface, ignore_mgmt=True)
Update an existing interface by comparing values between two interfaces. If a VLAN interface is defined in the other interface and it doesn't exist on the existing interface, it will be created. :param other_interface Interface: an instance of an interface where values in th...
4.565935
4.492297
1.016392
name = super(Interface, self).name return name if name else self.data.get('name')
def name(self)
Read only name tag
8.939985
9.072352
0.98541
base_interface = ElementCache() base_interface.update( interface_id=str(interface_id), interfaces=[]) if 'zone_ref' in kw: zone_ref = kw.pop('zone_ref') base_interface.update(zone_ref=zone_helper(zone_ref) if zone_ref else None) ...
def _add_interface(self, interface_id, **kw)
Create a tunnel interface. Kw argument list is as follows
4.964882
4.990888
0.994789
return [{'address': interface.address, 'nicid': interface.nicid} for interface in self.interfaces if isinstance(interface, (NodeInterface, SingleNodeInterface))]
def ndi_interfaces(self)
Return a formatted dict list of NDI interfaces on this engine. This will ignore CVI or any inline or layer 2 interface types. This can be used to identify to indicate available IP addresses for a given interface which can be used to run services such as SNMP or DNS Relay. ...
9.231957
5.264088
1.753762
vlan = self.vlan_interface.get_vlan(original) newvlan = str(new).split('-') splitted = vlan.interface_id.split('.') vlan.interface_id = '{}.{}'.format(splitted[0], newvlan[0]) for interface in vlan.interfaces: if isinstance(interface, InlineInterface): ...
def change_vlan_id(self, original, new)
Change VLAN ID for a single VLAN, cluster VLAN or inline interface. When changing a single or cluster FW vlan, you can specify the original VLAN and new VLAN as either single int or str value. If modifying an inline interface VLAN when the interface pair has two different VLAN identifier...
3.636562
3.651923
0.995794
if mode in ['lb', 'ha']: self.data['aggregate_mode'] = mode self.data['second_interface_id'] = ','.join(map(str, interfaces)) self.save()
def enable_aggregate_mode(self, mode, interfaces)
Enable Aggregate (LAGG) mode on this interface. Possible LAGG types are 'ha' and 'lb' (load balancing). For HA, only one secondary interface ID is required. For load balancing mode, up to 7 additional are supported (8 max interfaces). :param str mode: 'lb' or 'ha' :param...
7.213736
4.750671
1.518467
self.data['arp_entry'].append({ 'ipaddress': ipaddress, 'macaddress': macaddress, 'netmask': netmask, 'type': arp_type})
def static_arp_entry(self, ipaddress, macaddress, arp_type='static', netmask=32)
Add an arp entry to this physical interface. :: interface = engine.physical_interface.get(0) interface.static_arp_entry( ipaddress='23.23.23.23', arp_type='static', macaddress='02:02:02:02:04:04') interface.save() :par...
2.604284
2.789983
0.933441
_kw = copy.deepcopy(kw) # Preserve original kw, especially lists mgt = mgt if mgt else {} if 'cvi_mode' in _kw: self.data.update(cvi_mode=_kw.pop('cvi_mode')) if 'macaddress' in _kw: self.data.update( macaddress=_kw.pop('...
def _add_interface(self, interface_id, mgt=None, **kw)
Add the Cluster interface. If adding a cluster interface to an existing node, retrieve the existing interface and call this method. Use the supported format for defining an interface.
3.280192
3.286864
0.99797
if self in self._parent.vlan_interface: self._parent.data['vlanInterfaces'] = [ v for v in self._parent.vlan_interface if v != self] self.update() for route in self._parent._engine.routing: if route.to_delete: ...
def delete(self)
Delete this Vlan interface from the parent interface. This will also remove stale routes if the interface has networks associated with it. :return: None
7.002006
5.931305
1.180517
intf_id, _ = self.interface_id.split('.') self.interface_id = '{}.{}'.format(intf_id, vlan_id) for interface in self.interfaces: interface.change_vlan_id(vlan_id) self.update()
def change_vlan_id(self, vlan_id)
Change the VLAN id for this VLAN interface. If this is an inline interface, you can specify two interface values to create unique VLANs on both sides of the inline pair. Or provide a single to use the same VLAN id. :param str vlan_id: string value for new VLAN id. :raise...
3.334127
3.440066
0.969204
for collection in self.items: if args: index = args[0] if len(collection) and (index <= len(collection)-1): return collection[index] else: # Collection with get result = collection.get(**kwargs) ...
def get(self, *args, **kwargs)
Get from the interface collection. It is more accurate to use kwargs to specify an attribute of the sub interface to retrieve rather than using an index value. If retrieving using an index, the collection will first check vlan interfaces and standard interfaces second. In most cases, if ...
5.281527
5.413441
0.975632
if args: kwargs = {'vlan_id': str(args[0])} key, value = kwargs.popitem() for vlan in self: if getattr(vlan, key, None) == value: return vlan raise InterfaceNotFound('VLAN ID {} was not found on this engine.' .format(value))
def get_vlan(self, *args, **kwargs)
Get the VLAN from this PhysicalInterface. Use args if you want to specify only the VLAN id. Otherwise you can specify a valid attribute for the VLAN sub interface such as `address` for example:: >>> vlan = itf.vlan_interface.get_vlan(4) >>> vlan Layer...
5.153558
4.480151
1.150309
if args: kwargs = {'vlan_id': str(args[0])} key, value = kwargs.popitem() for item in self: if 'vlan_id' in key and getattr(item, key, None) == value: return item for vlan in item.interfaces: if getattr(vlan, key, None)...
def get(self, *args, **kwargs)
Get the sub interfaces for this VlanInterface >>> itf = engine.interface.get(3) >>> list(itf.vlan_interface) [Layer3PhysicalInterfaceVlan(name=VLAN 3.3), Layer3PhysicalInterfaceVlan(name=VLAN 3.5), Layer3PhysicalInterfaceVlan(name=VLAN 3.4)] :par...
4.136168
3.718023
1.112464
for intf in self: for allitf in intf.all_interfaces: if isinstance(allitf, VlanInterface): for vlan in allitf.interfaces: if getattr(vlan, mgmt, None): return allitf.interface_id else: ...
def find_mgmt_interface(self, mgmt)
Find the management interface specified and return either the string representation of the interface_id. Valid options: primary_mgt, backup_mgt, primary_heartbeat, backup_heartbeat, outgoing, auth_request :return: str interface_id
3.485358
3.702012
0.941477
# From within engine, skips nested iterators for this find # Make sure were dealing with a string interface_id = str(interface_id) for intf in self: if intf.interface_id == interface_id: intf._engine = self.engine return intf ...
def get(self, interface_id)
Get the interface from engine json :param str interface_id: interface ID to find :raises InterfaceNotFound: Cannot find interface
5.143394
4.994239
1.029865
interface = self.get(interface_id) if interface_id is not None else None if address is not None: target_network = None sub_interface = interface.all_interfaces.get(address=address) if sub_interface: target_network = sub_interface.network_value...
def set_unset(self, interface_id, attribute, address=None)
Set attribute to True and unset the same attribute for all other interfaces. This is used for interface options that can only be set on one engine interface. :raises InterfaceNotFound: raise if specified address does not exist or if the interface is not supported for this m...
3.673331
3.649391
1.00656
for engine_type in ['master', 'layer2', 'ips']: if engine_type in self.engine.type: return interface = self.get(interface_id) if 'cluster' in self.engine.type: # Auth request on a cluster interface must have at least a CVI. # ...
def set_auth_request(self, interface_id, address=None)
Set auth request, there can only be one per engine so unset all other interfaces. If this is a cluster, auth request can only be set on an interface with a CVI (not valid on NDI only cluster interfaces). If this is a cluster interface, address should be CVI IP.
3.988688
3.502555
1.138794
#max_asn = 4294967295 (65535 * 65535) if '.' not in dotted_str: return dotted_str max_byte = 65535 left, right = map(int, dotted_str.split('.')) if left > max_byte or right > max_byte: raise ValueError('The max low and high order value for ' 'a 32-bit ASN is 65535') ...
def as_dotted(dotted_str)
Implement RFC 5396 to support 'asdotted' notation for BGP AS numbers. Provide a string in format of '1.10', '65000.65015' and this will return a 4-byte decimal representation of the AS number. Get the binary values for the int's and pad to 16 bits if necessary (values <255). Concatenate the first 2 byte...
3.708137
2.791645
1.328298
if not networks and len(self.data.get('antispoofing_ne_ref')): self.data.update(antispoofing_ne_ref=[]) return True _networks = element_resolver(networks) if set(_networks) ^ set(self.data.get('antispoofing_ne_ref')): self.data.update(antispoofing_ne_...
def update_antispoofing(self, networks=None)
Pass a list of networks to update antispoofing networks with. You can clear networks by providing an empty list. If networks are provided but already exist, no update is made. :param list networks: networks, groups or hosts for antispoofing :rtype: bool
3.564087
3.411535
1.044716
autonomous_system = element_resolver(autonomous_system) bgp_profile = element_resolver(bgp_profile) or \ BGPProfile('Default BGP Profile').href announced = self._unwrap(announced_networks) self.data.update( enabled=True, ...
def enable(self, autonomous_system, announced_networks, router_id=None, bgp_profile=None)
Enable BGP on this engine. On master engine, enable BGP on the virtual firewall. When adding networks to `announced_networks`, the element types can be of type :class:`smc.elements.network.Host`, :class:`smc.elements.network.Network` or :class:`smc.elements.group.Group`. If passing a Gro...
5.408726
4.830171
1.119779
updated = False if 'announced_networks' in kwargs: kwargs.update(announced_ne_setting=kwargs.pop('announced_networks')) if 'bgp_profile' in kwargs: kwargs.update(bgp_profile_ref=kwargs.pop('bgp_profile')) if 'autonomous_system' in kwargs: kwar...
def update_configuration(self, **kwargs)
Update configuration using valid kwargs as defined in the enable constructor. :param dict kwargs: kwargs to satisfy valid args from `enable` :rtype: bool
3.138318
3.167759
0.990706
return [(Element.from_href(ne.get('announced_ne_ref')), Element.from_href(ne.get('announced_rm_ref'))) for ne in self.data.get('announced_ne_setting')]
def announced_networks(self)
Show all announced networks for the BGP configuration. Returns tuple of advertised network, routemap. Route map may be None. :: for advertised in engine.bgp.advertisements: net, route_map = advertised :return: list of tuples (advertised_netwo...
10.38208
9.774696
1.062138
as_number = as_dotted(str(as_number)) json = {'name': name, 'as_number': as_number, 'comment': comment} return ElementCreator(cls, json)
def create(cls, name, as_number, comment=None)
Create an AS to be applied on the engine BGP configuration. An AS is a required parameter when creating an ExternalBGPPeer. You can also provide an AS number using an 'asdot' syntax:: AutonomousSystem.create(name='myas', as_number='200.600') :param str name: name of this AS...
4.766408
5.129431
0.929228
json = {'name': name, 'external': external_distance, 'internal': internal_distance, 'local': local_distance, 'port': port} if subnet_distance: d = [{'distance': distance, 'subnet': subnet.href} for sub...
def create(cls, name, port=179, external_distance=20, internal_distance=200, local_distance=200, subnet_distance=None)
Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external administrative distance; (1-255) :param int internal_distance: internal administrative distance (1-255) :param int local_distance: local admi...
3.659241
3.852021
0.949954
return [(Element.from_href(entry.get('subnet')), entry.get('distance')) for entry in self.data.get('distance_entry')]
def subnet_distance(self)
Specific subnet administrative distances :return: list of tuple (subnet, distance)
15.332497
11.874412
1.291222
json = {'name': name, 'neighbor_ip': neighbor_ip, 'neighbor_port': neighbor_port, 'comment': comment} neighbor_as_ref = element_resolver(neighbor_as) json.update(neighbor_as=neighbor_as_ref) return ElementCreator(cls, json)
def create(cls, name, neighbor_as, neighbor_ip, neighbor_port=179, comment=None)
Create an external BGP Peer. :param str name: name of peer :param str,AutonomousSystem neighbor_as_ref: AutonomousSystem element or href. :param str neighbor_ip: ip address of BGP peer :param int neighbor_port: port for BGP, default 179. :raises CreateElementFailed...
3.736791
3.668082
1.018732
json = {'name': name, 'local_as_option': local_as_option, 'max_prefix_option': max_prefix_option, 'send_community': send_community, 'connected_check': connected_check, 'orf_option': orf_option, 'next_hop_sel...
def create(cls, name, connection_profile_ref=None, md5_password=None, local_as_option='not_set', max_prefix_option='not_enabled', send_community='no', connected_check='disabled', orf_option='disabled', next_hop_self=True, override_capability=False, ...
Create a new BGPPeering configuration. :param str name: name of peering :param str,BGPConnectionProfile connection_profile_ref: required BGP connection profile. System default used if not provided. :param str md5_password: optional md5_password :param str local_as_option: th...
1.868121
1.868463
0.999817
json = {'name': name, 'connect': connect_retry, 'session_hold_timer': session_hold_timer, 'session_keep_alive': session_keep_alive} if md5_password: json.update(md5_password=md5_password) return ElementCreator(cls, json)
def create(cls, name, md5_password=None, connect_retry=120, session_hold_timer=180, session_keep_alive=60)
Create a new BGP Connection Profile. :param str name: name of profile :param str md5_password: optional md5 password :param int connect_retry: The connect retry timer, in seconds :param int session_hold_timer: The session hold timer, in seconds :param int session_keep_alive: The...
2.594286
2.889758
0.897752
for value in values: if value in self.data: self.data[value] = True
def enable(self, values)
Enable specific permissions on this role. Use :py:attr:`~permissions` to view valid permission settings and current value/s. Change is committed immediately. :param list values: list of values by allowed types :return: None
3.701562
5.614092
0.659334
for value in values: if value in self.data: self.data[value] = False
def disable(self, values)
Disable specific permissions on this role. Use :py:attr:`~permissions` to view valid permission settings and current value/s. Change is committed immediately. :param list values: list of values by allowed types :return: None
3.66739
5.92368
0.619107
permissions = [] for permission, value in self.data.items(): if permission not in self._reserved: permissions.append({permission: value}) return permissions
def permissions(self)
Return valid permissions and setting for this role. Permissions are returned as a list of dict items, {permission: state}. State for the permission is either True or False. Use :meth:`~enable` and :meth:`~disable` to toggle role settings. :return: list of permission settings ...
4.686952
4.774618
0.981639
_ports = str(port_string) if '-' in _ports: start, end = _ports.split('-') return {'min_port': start, 'max_port': end} return {'min_port': _ports, 'max_port': _ports}
def _extract_ports(port_string)
Return a dict for translated_value based on a string or int value. Value could be 80, or '80' or '80-90'. Will be returned as {'min_port': 80, 'max_port': 80} or {'min_port': 80, 'max_port': 90} :rtype: dict
2.845208
2.321775
1.225445
original_value = source_or_dest.all_as_href() if original_value: nat_element = None if 'src' in source_or_dest.typeof and self.static_src_nat.has_nat: nat_element = self.static_src_nat elif 'dst' in source_or_dest.typeof and self.static_dst_na...
def _update_nat_field(self, source_or_dest)
If the source or destination field of a rule is changed and the rule is a NAT rule, this method will check to see if the changed field maps to a NAT type and modifies the `original_value` field within the NAT dict to reflect the new element reference. It is possible that a NAT rule doesn...
4.054525
3.748878
1.08153
updated = False if natvalue.element and natvalue.element != self.element: self.update(element=natvalue.element) self.pop('ip_descriptor', None) updated = True elif natvalue.ip_descriptor and self.ip_descriptor and \ natvalue.ip_descriptor ...
def _update_field(self, natvalue)
Update this NATValue if values are different :rtype: bool
2.599475
2.537833
1.024289
updated = False src = _resolve_nat_element(element_or_ip_address) if \ element_or_ip_address else {} automatic_proxy = kw.pop('automatic_proxy', None) # Original value is only used when creating a rule for static src NAT. # This should be the href of...
def update_field(self, element_or_ip_address=None, start_port=None, end_port=None, **kw)
Update the source NAT translation on this rule. You must call `save` or `update` on the rule to make this modification. To update the source target for this NAT rule, update the source field directly using rule.sources.update_field(...). This will automatically update the NAT value. This...
4.864305
4.424984
1.099282
if self.typeof in self: return NATValue(self.get(self.typeof, {}).get( 'translated_value'))
def translated_value(self)
The translated value for this NAT type. If this rule does not have a NAT value defined, this will return None. :return: NATValue or None :rtype: NATValue
23.400253
11.99895
1.950192
updated = False src = _resolve_nat_element(element_or_ip_address) if \ element_or_ip_address else {} automatic_proxy = kw.pop('automatic_proxy', None) # Original value is only used when creating a rule for static src NAT. # This should be the href of...
def update_field(self, element_or_ip_address=None, original_port=None, translated_port=None, **kw)
Update the destination NAT translation on this rule. You must call `save` or `update` on the rule to make this modification. The destination field in the NAT rule determines which destination is the target of the NAT. To change the target, call the rule.destinations.update_field(...) met...
5.177242
4.929099
1.050342
_credential_refresh_attempt = kwargs.pop( '_credential_refresh_attempt', 0) # Make a copy of the headers. They will be modified by the credentials # and we want to pass the original headers if we recurse. request_headers = headers.copy() if headers is not None else...
def request(self, uri, method='GET', body=None, headers=None, **kwargs)
Implementation of httplib2's Http.request.
3.162194
3.103806
1.018812
logger.info('Connecting to %s at port %s' % (broker, port)) self._connected = False self._unexpected_disconnect = False self._mqttc = mqtt.Client(client_id, clean_session) # set callbacks self._mqttc.on_connect = self._on_connect self._mqttc.on_disconnec...
def connect(self, broker, port=1883, client_id="", clean_session=True)
Connect to an MQTT broker. This is a pre-requisite step for publish and subscribe keywords. `broker` MQTT broker host `port` broker port (default 1883) `client_id` if not specified, a random id is generated `clean_session` specifies the clean session flag for the connection ...
2.298057
2.496342
0.92057
logger.info('Publish topic: %s, message: %s, qos: %s, retain: %s' % (topic, message, qos, retain)) self._mid = -1 self._mqttc.on_publish = self._on_publish result, mid = self._mqttc.publish(topic, message, int(qos), retain) if result != 0: raise R...
def publish(self, topic, message=None, qos=0, retain=False)
Publish a message to a topic with specified qos and retained flag. It is required that a connection has been established using `Connect` keyword before using this keyword. `topic` topic to which the message will be published `message` message payload to publish `qos` qos of th...
2.883952
3.149928
0.915561
seconds = convert_time(timeout) self._messages[topic] = [] limit = int(limit) self._subscribed = False logger.info('Subscribing to topic: %s' % topic) self._mqttc.on_subscribe = self._on_subscribe self._mqttc.subscribe(str(topic), int(qos)) self....
def subscribe(self, topic, qos, timeout=1, limit=1)
Subscribe to a topic and return a list of message payloads received within the specified time. `topic` topic to subscribe to `qos` quality of service for the subscription `timeout` duration of subscription. Specify 0 to enable background looping (async) `limit` the max nu...
3.801386
4.105473
0.925931
if not self._subscribed: logger.warn('Cannot listen when not subscribed to a topic') return [] if topic not in self._messages: logger.warn('Cannot listen when not subscribed to topic: %s' % topic) return [] # If enough messages have alre...
def listen(self, topic, timeout=1, limit=1)
Listen to a topic and return a list of message payloads received within the specified time. Requires an async Subscribe to have been called previously. `topic` topic to listen to `timeout` duration to listen `limit` the max number of payloads that will be returned. Specify 0 ...
4.110615
4.414039
0.931259
seconds = convert_time(timeout) self._verified = False logger.info('Subscribing to topic: %s' % topic) self._mqttc.subscribe(str(topic), int(qos)) self._payload = str(payload) self._mqttc.on_message = self._on_message timer_start = time.time() w...
def subscribe_and_validate(self, topic, qos, payload, timeout=1)
Subscribe to a topic and validate that the specified payload is received within timeout. It is required that a connection has been established using `Connect` keyword. The payload can be specified as a python regular expression. If the specified payload is not received within timeout, an...
3.387929
3.699933
0.915673
try: tmp = self._mqttc except AttributeError: logger.info('No MQTT Client instance found so nothing to unsubscribe from.') return if self._background_mqttc: logger.info('Closing background loop') self._background_mqttc.loop_st...
def unsubscribe(self, topic)
Unsubscribe the client from the specified topic. `topic` topic to unsubscribe from Example: | Unsubscribe | test/mqtt_test |
3.402013
3.475858
0.978755
try: tmp = self._mqttc except AttributeError: logger.info('No MQTT Client instance found so nothing to disconnect from.') return self._disconnected = False self._unexpected_disconnect = False self._mqttc.on_disconnect = self._on_disco...
def disconnect(self)
Disconnect from MQTT Broker. Example: | Disconnect |
4.087214
4.146779
0.985636
logger.info('Publishing to: %s:%s, topic: %s, payload: %s, qos: %s' % (hostname, port, topic, payload, qos)) publish.single(topic, payload, qos, retain, hostname, port, client_id, keepalive, will, auth, tls, protocol)
def publish_single(self, topic, payload=None, qos=0, retain=False, hostname="localhost", port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None, protocol=mqtt.MQTTv31)
Publish a single message and disconnect. This keyword uses the [http://eclipse.org/paho/clients/python/docs/#single|single] function of publish module. `topic` topic to which the message will be published `payload` message payload to publish (default None) `qos` qos of the mes...
2.024328
2.38631
0.848309
logger.info('Publishing to: %s:%s, msgs: %s' % (hostname, port, msgs)) publish.multiple(msgs, hostname, port, client_id, keepalive, will, auth, tls, protocol)
def publish_multiple(self, msgs, hostname="localhost", port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None, protocol=mqtt.MQTTv31)
Publish multiple messages and disconnect. This keyword uses the [http://eclipse.org/paho/clients/python/docs/#multiple|multiple] function of publish module. `msgs` a list of messages to publish. Each message is either a dict or a tuple. If a dict, it must be of the form: ...
2.505308
3.067239
0.816796
'''Add user to request if user logged in''' @wraps(handler) async def decorator(*args): request = _get_request(args) request[cfg.REQUEST_USER_KEY] = await get_cur_user(request) return await handler(*args) return decorator
def user_to_request(handler)
Add user to request if user logged in
4.698852
4.152031
1.1317
self.synonyms.extend(other.synonyms) other.synonyms = self.synonyms
def add_synonym(self, other)
Every word in a group of synonyms shares the same list.
3.344
3.072982
1.088194