### Install smc-python using setup.py Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/README.rst Install the library after cloning the repository by running the setup script. ```bash python setup.py install ``` -------------------------------- ### Manual Script Execution Setup Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/examples/README.md Install necessary dependencies and create the smc_info.py configuration file for manual execution of smc-python scripts. ```bash pip3 install requests pip3 install pytz pip3 install websocket-client # only needed for monitoring ``` ```python SMC_URL='http://localhost:8082' WS_URL='ws://localhost:8082' API_VERSION='7.0.0' API_KEY='xxxxxxxxxxxxxxxxxxxx' ``` -------------------------------- ### Run Example Script Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/examples/README.md Execute an example script using the provided run_example.sh script. This script handles virtual environment creation and configuration prompts. ```bash cd ${repo_base}/smc/examples ./run_example.sh .py ``` ```bash ./run_example.sh layer3_fw.py ``` -------------------------------- ### Retrieve elements by entry point Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Use `Search.objects.entry_point()` with a specific object type string to retrieve all elements of that type. For example, to get all VPN policies. ```python >>> list(Search.objects.entry_point('vpn')) [PolicyVPN(name=Amazon AWS), PolicyVPN(name=sg_vm_vpn), PolicyVPN(name=TRITON AP-WEB Cloud VPN)] ``` -------------------------------- ### Install smc-python from Git Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/README.rst Install the library directly from the Git repository using pip. ```bash pip install git+https://github.com/Forcepoint/fp-NGFW-SMC-python.git ``` -------------------------------- ### Install smc-ngfw-smc-python Package Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/installation.rst Use pip to install the package. For offline installations, download the package and dependencies manually and use 'python setup.py install'. ```bash pip install fp-ngfw-smc-python ``` -------------------------------- ### Routing Management Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/engine.rst Examples for viewing and adding static routes to an engine. ```APIDOC ## View All Routes ### Description Retrieves and displays all routing entries configured on the engine. ### Method ```python engine = Engine('testfw') for routes in engine.routing.all(): print(routes) ``` ## View Specific Interface Routes ### Description Filters and displays routes associated with a specific interface. ### Method ```python engine = Engine('testfw') for routes in engine.routing.all(): if routes.name == 'Interface 1': print(routes.all()) ``` ## Add Static Route ### Description Adds a new static route to the engine. The interface is automatically determined by the gateway's IP address. ### Method ```python engine = Engine('master-eng') engine.add_route(gateway='172.18.1.200', network='192.168.17.0/24') ``` ``` -------------------------------- ### Add a VPN Site Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/reference.rst This example shows how to add a new VPN site to the firewall. VPN sites define groups of protected networks that can be applied to the VPN configuration. ```APIDOC ## Add a VPN Site ### Description Adds a new VPN site, optionally defining protected networks associated with it. This is an optional step after enabling VPN on an engine. ### Method Python SDK ### Parameters #### Network Element - **name** (string) - The name of the network element. - **ipv4_network** (string) - The IPv4 network address and subnet mask. #### VPN Site - **name** (string) - The name of the VPN site. - **site_elements** (list) - A list of network elements to include in the site. ### Request Example ```python net = Network.get_or_create(name='wireless', ipv4_network='192.168.5.0/24') engine.vpn.add_site(name='wireless', site_elements=[net]) ``` ### Response Example ```json VPNSite(name=wireless) ``` ### Usage Example ```python list(engine.vpn.sites) ``` ``` -------------------------------- ### License Management Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/engine.rst Examples for binding licenses to engine nodes. ```APIDOC ## Bind License to Engine Node ### Description Attempts to bind a license to each node within an engine. This can involve auto-fetching from the appliance or auto-binding a dynamic license. ### Method ```python engine = Engine('testfw') for node in engine.nodes: node.bind_license() ``` ``` -------------------------------- ### Search services by port Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Retrieve all services that match a specific port number by using `entry_point('services')` and filtering by the port. This example searches for port 80. ```python >>> list(Search.objects.entry_point('services').filter('80')) [TCPService(name=tcp80443), TCPService(name=HTTP to Web SaaS), EthernetService(name=IPX over Ethernet 802.2), UDPService(name=udp_10070-10080), Protocol(name=HTTP8080), TCPService(name=tcp_10070-10080), TCPService(name=TCP_8080), TCPService(name=tcp_3478-3480), EthernetService(name=IPX over Ethernet 802.3 (Novell)), TCPService(name=HTTP), TCPService(name=SSM HTTP), TCPService(name=HTTP (SafeSearch)), IPService(name=ISO-IP), UDPService(name=udp_3478-3480), TCPService(name=HTTP (with URL Logging))] ``` -------------------------------- ### Create and Manage Network Elements Source: https://context7.com/forcepoint/fp-ngfw-smc-python/llms.txt This example shows how to create various network elements such as Host, Network, AddressRange, Zone, and IPList using the SMC Python API. It also demonstrates updating IP lists, downloading their contents, and resolving aliases. Error handling for element creation and retrieval is provided. ```python from smc import session from smc.elements.network import Host, Network, AddressRange, Zone, IPList, Alias from smc.api.exceptions import CreateElementFailed, ElementNotFound session.login(url='http://192.168.1.10:8082', api_key='myApiKey123') try: # Create a host host = Host.create(name='webserver', address='10.1.1.100', comment='Web server') print("Host:", host.name, host.href) # Create IPv4 network net = Network.create(name='internal-net', ipv4_network='192.168.0.0/16') print("Network:", net.name) # Create an address range arange = AddressRange.create(name='dhcp-range', ip_range='10.0.0.50-10.0.0.100') print("Range:", arange.name) # Create a zone zone = Zone.create(name='DMZ', comment='Demilitarized zone') print("Zone:", zone.name) # Create an IPList with initial entries iplist = IPList.create(name='blocklist', iplist=['1.2.3.4', '5.6.7.8', '10.0.0.0/8']) print("IPList:", iplist.name) # Upload additional IPs to existing IPList iplist = IPList('blocklist') iplist.upload(json={'ip': ['200.0.0.1', '200.0.0.2']}, as_type='json') # Download IPList contents contents = iplist.download(as_type='json') print("IPs:", contents.get('ip')) # update_or_create pattern (idempotent) iplist2 = IPList.update_or_create(name='allowlist', iplist=['192.168.1.0/24'], append_lists=True) print("IPList upserted:", iplist2.name) # Resolve an alias to a specific engine alias = Alias('$$ Interface ID 0.ip') print("Alias resolves to:", alias.resolve('my-firewall')) except (CreateElementFailed, ElementNotFound) as e: print("Error:", e) finally: session.logout() ``` -------------------------------- ### Interface Management Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/engine.rst Examples for retrieving, updating, and deleting network interfaces on an engine. ```APIDOC ## Get and Modify Interface Addresses ### Description Retrieves an interface, modifies its IP address, and saves the changes. ### Method ```python intf = engine.interface.get(0) intf.addresses = '172.18.1.60' intf.save() ``` ## Change Interface Zone ### Description Updates the security zone associated with a physical interface. ### Method ```python intf = engine.interface.get(0) intf.zone_ref = zone_helper('My New Zone') intf.save() ``` ## Modify VLAN Interface ### Description Finds a specific VLAN interface by its ID and updates its VLAN ID, then saves the parent interface. ### Method ```python intf = engine.interface.get(2) for vlan in intf.vlan_interface: if vlan.vlan_id == '14': vlan.vlan_id = '15' intf.save() ``` ## Delete Interface ### Description Retrieves an interface by its index and then deletes it from the engine configuration. ### Method ```python engine = Engine('testfw') intf = engine.interface.get(20) intf.delete() ``` ``` -------------------------------- ### Filter elements by entry point and name Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Combine `entry_point()` with `filter()` to retrieve specific elements of a given type that match a search string. This example filters VPNs by 'AWS'. ```python >>> list(Search.objects.entry_point('vpn').filter('AWS')) [PolicyVPN(name=Amazon AWS)] ``` -------------------------------- ### Download and Activate Dynamic Update Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/administration.rst Download and activate a specific dynamic update package. This involves getting the package, checking its state, downloading it with wait_for_finish=True, and then activating it, also with wait_for_finish=True. Task status and messages are printed throughout the process. ```python system = System() available_packages = system.update_package() my_dynup = available_packages.get_contains('1097') if my_dynup.state.lower() == 'available': download_task = my_dynup.download(wait_for_finish=True) while not download_task.done(): download_task.wait(3) print(download_task.last_message()) if download_task.success: print("Success!") # We are now downloaded, so activate activation = my_dynup.activate(wait_for_finish=True) while not activation.done(): activation.wait(3) print(activation.last_message()) if activation.success: print("We are now activated") else: print("Something bad went wrong: %s" % activation.last_message()) ``` -------------------------------- ### Retrieve elements from multiple entry points Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Specify multiple entry points as a comma-separated string in `entry_point()` to retrieve elements from several types simultaneously. This example searches for routers and hosts. ```python >>> list(Search.objects.entry_point('router,host')) [Host(name=172.18.2.254), Router(name=router-172.18.3.129), Host(name=All Routers (Site-Local))] ``` -------------------------------- ### Use Collection Query Convenience Functions Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Utilize convenience functions like 'exists', 'all', 'first', 'last', and 'count' on collection query results. This example demonstrates checking for existence and retrieving specific items. ```python >>> query1 = iterator.filter('10.10.10.1') >>> if query1.exists(): ... list(query1.all()) ... [Router(name=Router-110.10.10.10), Router(name=Router-10.10.10.10), Router(name=Router-10.10.10.1)] >>> list(query1) [Router(name=Router-110.10.10.10), Router(name=Router-10.10.10.10), Router(name=Router-10.10.10.1)] >>> query1.first() Router(name=Router-110.10.10.10) >>> query1.last() Router(name=Router-10.10.10.1) >>> query1.count() 3 >>> query2 = query1.filter(address='10.10.10.1') # Add kwarg to new query >>> list(query2) [Router(name=Router-10.10.10.1)] ``` -------------------------------- ### Real-time Monitoring Queries with smc-monitoring Source: https://context7.com/forcepoint/fp-ngfw-smc-python/llms.txt Utilizes the smc-monitoring package for live log fetching, batch log queries with filters, and active connection monitoring. Ensure smc-monitoring is installed and session is logged in. ```python from smc import session from smc_monitoring.monitors.logs import LogQuery from smc_monitoring.monitors.connections import ConnectionQuery from smc_monitoring.monitors.vpnsas import VPNSAQuery from smc_monitoring.monitors.users import UserQuery from smc_monitoring.models.filters import InFilter, DefinedFilter from smc_monitoring.models.values import FieldValue, ConstantValue, IPValue from smc_monitoring.models.constants import LogField, Alerts from smc_monitoring.models.formats import TableFormat, CSVFormat, RawDictFormat from smc_monitoring.pubsub.subscriber import Notification from smc_monitoring.pubsub.events import Event session.login(url='http://192.168.1.10:8082', api_key='myApiKey123') # Fetch live logs query = LogQuery() for log in query.fetch_live(): print(log) break # just first entry # Batch log query with filters query = LogQuery(fetch_size=50) query.format.timezone('UTC') query.add_and_filter([ InFilter(FieldValue(LogField.ALERTSEVERITY), [ConstantValue(Alerts.HIGH)]), DefinedFilter(FieldValue(LogField.ACTION)), ]) for log in query.fetch_batch(TableFormat): print(log) # Query logs for a specific source IP with selected fields query = LogQuery(fetch_size=10) query.format.field_ids([LogField.TIMESTAMP, LogField.SRC, LogField.DST]) query.add_and_filter([InFilter(FieldValue(LogField.SRC), [IPValue('192.168.4.84')])]) for log in query.fetch_batch(TableFormat): print(log) # Active connections on a specific engine query = ConnectionQuery('my-firewall') for record in query.fetch_batch(CSVFormat): print(record) # VPN Security Associations query = VPNSAQuery('my-firewall') for record in query.fetch_as_element(): print(record) # Authenticated users query = UserQuery('my-firewall') for record in query.fetch_as_element(): print(record) # Subscribe to element change events (pub/sub) notification = Notification('network,host') for event in notification.notify(as_type=Event): print(f"Event: action={event.action}, element={event.element}") break # stop after first event session.logout() ``` -------------------------------- ### Filter elements from multiple entry points Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Combine searching multiple entry points with a filter to narrow down results. This example finds hosts and routers matching '172.18.1'. ```python >>> list(Search.objects.entry_point('router,host').filter('172.18.1')) [Host(name=172.18.1.135), Host(name=SMC), Host(name=ePolicy Orchestrator), Router(name=router-172.18.1.225), Host(name=fw-internal-primary), Router(name=router-172.18.1.209)] ``` -------------------------------- ### Get and Print Interface Name Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/engine.rst Retrieve a specific interface by its index and print its name. ```python >>> intf = engine.interface.get(20) #Get interface 20 >>> print(intf.name) Interface 20 ``` -------------------------------- ### Monitor Asynchronous Engine Refresh Task Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/administration.rst Fire off an engine refresh and monitor its asynchronous task using TaskMonitor. This example shows how to get the follower href, wait for completion, and check the task's success status and last message. ```python engine = Engine('myfw') task_follower = engine.refresh(wait_for_finish=True) #This isn't required as engine will still refresh while not task_follower.done(): task_follower.wait(3) print("Did task succeed: %s" % task_follower.success) print("Last message from task: %s" % task_follower.last_message) ``` -------------------------------- ### Create Layer 3 Firewall Engines Source: https://context7.com/forcepoint/fp-ngfw-smc-python/llms.txt Creates standalone Layer 3 firewall engines. Use `create()` for single-interface setups or `create_bulk()` for multi-interface configurations. `create_dynamic()` is used for cloud/DHCP firewalls. ```python from smc import session from smc.core.engines import Layer3Firewall from smc.api.exceptions import CreateEngineFailed session.login(url='http://192.168.1.10:8082', api_key='myApiKey123') try: # Simple single-interface firewall fw = Layer3Firewall.create( name='my-firewall', mgmt_ip='192.168.10.1', mgmt_network='192.168.10.0/24', mgmt_interface=0, domain_server_address=['8.8.8.8'], default_nat='automatic', enable_antivirus=False, enable_gti=False, comment='Created via smc-python', ) print("Created:", fw.name, fw.href) # Multi-interface firewall via create_bulk fw2 = Layer3Firewall.create_bulk( name='my-fw-bulk', primary_mgt=0, domain_server_address=['8.8.8.8'], interfaces=[ { 'interface_id': 0, 'interfaces': [{'nodes': [{'address': '10.0.0.1', 'network_value': '10.0.0.0/24'}]}], }, { 'interface_id': 1, 'interfaces': [{'nodes': [{'address': '172.16.0.1', 'network_value': '172.16.0.0/24'}]}], 'zone_ref': 'internal', }, { 'interface_id': 1000, 'interfaces': [{'nodes': [{'address': '10.99.0.1', 'network_value': '10.99.0.0/24'}]}], 'type': 'tunnel_interface', }, ], ) print("Created bulk:", fw2.name) # Cloud / dynamic (DHCP) firewall from smc.core.engines import CloudSGSingleFW cloud_fw = CloudSGSingleFW.create_dynamic(name='cloud-fw', interface_id=0) print("Cloud FW:", cloud_fw.name) except CreateEngineFailed as e: print("Error:", e) finally: session.logout() ``` -------------------------------- ### Add IP Address and VLAN to Cluster Interface Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/engine.rst This example demonstrates how to add an IP address and VLAN to a cluster interface, including specifying node assignments and cluster virtual IP details. ```APIDOC ## Add IP Address and VLAN to Cluster Interface ### Description Adds an IP address and VLAN to a cluster interface. This can include specifying node assignments, cluster virtual IP, MAC address, and CVI mode. ### Method `engine.physical_interface.add_ipaddress_and_vlan_to_cluster` ### Parameters - `interface_id` (int) - The ID of the physical interface. - `vlan_id` (int) - The VLAN ID to assign. - `nodes` (list of dict) - List of nodes to assign the interface to. Each dict should contain 'address', 'network_value', and 'nodeid'. - `cluster_virtual` (str) - The virtual IP address for the cluster. - `cluster_mask` (str) - The network mask for the cluster virtual IP. - `macaddress` (str) - The MAC address for the interface. - `cvi_mode` (str) - The CVI mode (e.g., 'packetdispatch'). - `zone_ref` (Zone) - Reference to the zone to assign. ### Request Example ```python engine.physical_interface.add_ipaddress_and_vlan_to_cluster( interface_id=2, vlan_id=2, nodes=[{'address': '4.4.4.4', 'network_value': '4.4.4.0/24', 'nodeid':1}, {'address': '4.4.4.5', 'network_value': '4.4.4.0/24', 'nodeid':2}], cluster_virtual='4.4.4.1', cluster_mask='4.4.4.0/24', macaddress='02:02:02:02:02:02', cvi_mode='packetdispatch', zone_ref=zone_helper('thiszone')) ``` ``` -------------------------------- ### Retrieve All Host Elements Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Access a collection directly on an Element type to retrieve all instances of that element. This example shows retrieving all Host elements. ```python >>> list(Host.objects.all()) [Host(name=SMC), Host(name=172.18.1.135), Host(name=172.18.2.254), Host(name=host)] ... ``` -------------------------------- ### Get Interface Addresses Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/engine.rst Retrieve and print the configured addresses for a given interface. ```python >>> intf = engine.interface.get(0) >>> print(intf.addresses) [('172.18.1.60', '172.18.1.0/24', '0')] ``` -------------------------------- ### Layer 3 Firewall Creation - create() / create_bulk() Source: https://context7.com/forcepoint/fp-ngfw-smc-python/llms.txt Creates Layer 3 firewall engines. `create()` is for simple single-interface setups, while `create_bulk()` allows defining all interfaces in a single call. `create_dynamic()` is used for cloud/DHCP firewalls. ```APIDOC ## Layer 3 Firewall Creation — `Layer3Firewall.create()` / `Layer3Firewall.create_bulk()` `Layer3Firewall` (in `smc.core.engines`) represents a standalone single-node Layer 3 firewall engine. Use `create()` for a simple single-interface setup or `create_bulk()` to define all interfaces in one call. ```python from smc import session from smc.core.engines import Layer3Firewall from smc.api.exceptions import CreateEngineFailed session.login(url='http://192.168.1.10:8082', api_key='myApiKey123') try: # Simple single-interface firewall fw = Layer3Firewall.create( name='my-firewall', mgmt_ip='192.168.10.1', mgmt_network='192.168.10.0/24', mgmt_interface=0, domain_server_address=['8.8.8.8'], default_nat='automatic', enable_antivirus=False, enable_gti=False, comment='Created via smc-python', ) print("Created:", fw.name, fw.href) # Multi-interface firewall via create_bulk fw2 = Layer3Firewall.create_bulk( name='my-fw-bulk', primary_mgt=0, domain_server_address=['8.8.8.8'], interfaces=[ { 'interface_id': 0, 'interfaces': [{'nodes': [{'address': '10.0.0.1', 'network_value': '10.0.0.0/24'}]}], }, { 'interface_id': 1, 'interfaces': [{'nodes': [{'address': '172.16.0.1', 'network_value': '172.16.0.0/24'}]}], 'zone_ref': 'internal', }, { 'interface_id': 1000, 'interfaces': [{'nodes': [{'address': '10.99.0.1', 'network_value': '10.99.0.0/24'}]}], 'type': 'tunnel_interface', }, ], ) print("Created bulk:", fw2.name) # Cloud / dynamic (DHCP) firewall from smc.core.engines import CloudSGSingleFW cloud_fw = CloudSGSingleFW.create_dynamic(name='cloud-fw', interface_id=0) print("Cloud FW:", cloud_fw.name) except CreateEngineFailed as e: print("Error:", e) finally: session.logout() ``` ``` -------------------------------- ### Engine Node Operations Source: https://context7.com/forcepoint/fp-ngfw-smc-python/llms.txt Provides examples for controlling individual engine nodes, pushing policies, and managing engine features. ```APIDOC ## Engine Node Operations — `Engine.nodes` / `Node` methods Once an engine is loaded, individual nodes can be controlled with go_online, go_offline, reboot, policy push, and more. ```python from smc import session from smc.core.engine import Engine from smc.api.exceptions import NodeCommandFailed, EngineCommandFailed session.login(url='http://192.168.1.10:8082', api_key='myApiKey123') try: engine = Engine('my-firewall') # Push policy task = engine.upload(policy='My Firewall Policy') print("Policy push task:", task) # Node-level commands for node in engine.nodes: print(f"Node: {node.name}, version: {node.version}") node.go_online() # node.go_offline() # node.reboot() # node.bind_license() # Enable/disable features engine.enable_antivirus() engine.disable_antivirus() # Routing info for route in engine.routing.all(): print("Route:", route) # Snapshots engine.generate_snapshot(name='before-change') for snap in engine.snapshots: print("Snapshot:", snap.name) except (NodeCommandFailed, EngineCommandFailed) as e: print("Error:", e) finally: session.logout() ``` ``` -------------------------------- ### Create Master Engine Cluster Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/engine.rst Create a Master NGFW Engine cluster for active/standby redundancy. This example includes adding a second interface for each cluster node. ```python from smc.core.engines import MasterEngineCluster MasterEngineCluster.create(name='engine-cluster', master_type='firewall', macaddress='22:22:22:22:22:22', nodes=[{'address':'5.5.5.2','network_value':'5.5.5.0/24','nodeid':1}, {'address':'5.5.5.3','network_value':'5.5.5.0/24','nodeid':2}]) ``` -------------------------------- ### Get Supported API Versions Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/examples/README.md Retrieve a list of supported API versions from the SMC management server using curl and jq. This is useful for determining the correct API_VERSION to use. ```bash curl -s http://localhost:8082/api|jq -r .version[].rel 6.10 6.11 7.0 ``` -------------------------------- ### Chain Filter and Limit Operations on Host Elements Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Chain filter and limit operations to refine the results from a Host collection. This example filters by a partial IP and limits the output. ```python >>> list(Host.objects.filter('172.18.1').limit(5)) [Host(name=172.18.1.135), Host(name=SMC), Host(name=TIE Server), Host(name=172.18.1.93)] ``` -------------------------------- ### Create and Configure Policy VPN Source: https://context7.com/forcepoint/fp-ngfw-smc-python/llms.txt Demonstrates creating a new Policy VPN and assigning existing engine gateways to it. Ensure the engine and API key are correctly configured. ```python from smc import session from smc.vpn.policy import PolicyVPN from smc.core.engine import Engine from smc.api.exceptions import CreateElementFailed session.login(url='http://192.168.1.10:8082', api_key='myApiKey123') try: # Create a Policy VPN vpn = PolicyVPN.create(name='MyVPN') print("VPN created:", vpn.name) # Load existing engine gateways and assign to VPN engine = Engine('my-firewall') gw = engine.vpn.internal_gateway print("Gateway:", gw.name) # List VPN sites on an engine for site in gw.vpn_site.all(): print("VPN site:", site.name) # Existing Policy VPN list for existing_vpn in PolicyVPN.objects.all(): print("VPN:", existing_vpn.name) except CreateElementFailed as e: print("Error:", e) finally: session.logout() ``` -------------------------------- ### Filter network elements by IP address Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Use `context_filter('network_elements')` to get all network-related elements and then apply a filter to find those matching a specific IP address or subnet. This example filters for '172.18.1'. ```python >>> list(Search.objects.context_filter('network_elements').filter('172.18.1')) [Host(name=172.18.1.135), Host(name=SMC), Network(name=Any network), FirewallCluster(name=sg_vm), Element(name=dc-smtp), Network(name=network-172.18.1.0/24), LogServer(name=LogServer 172.18.1.150), Layer3Firewall(name=testfw), Element(name=SecurID), Element(name=Windows 2003 DHCP), AddressRange(name=range-172.18.1.100-172.18.1.120), ManagementServer(name=Management Server)] ``` -------------------------------- ### Login with API Key and Basic Parameters Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/session.rst Use this method to establish a basic API session by providing the SMC URL and API key. Ensure the API service is enabled on the SMC and an API client with an authentication key is created. ```python from smc import session session.login(url='http://1.1.1.1:8082', api_key='xxxxxxxxxxxxxxxxx') ....do stuff.... session.logout() ``` -------------------------------- ### Create and Manage Firewall Policies and Rules Source: https://context7.com/forcepoint/fp-ngfw-smc-python/llms.txt Demonstrates creating a new firewall policy, adding various types of IPv4 access rules (permit, custom action with logging, discard), listing rules, searching by name, and deleting rules. Requires prior login to the SMC. ```python from smc import session from smc.policy.layer3 import FirewallPolicy from smc.policy.rule_elements import Action, LogOptions from smc.elements.network import Host, Network from smc.elements.service import TCPService from smc.api.exceptions import CreatePolicyFailed session.login(url='http://192.168.1.10:8082', api_key='myApiKey123') try: # Create a new policy policy = FirewallPolicy.create( name='MyPolicy', template='Firewall Inspection Template' ) # Simple permit rule policy.fw_ipv4_access_rules.create( name='allow-web-outbound', sources=[Host('webserver')], destinations='any', services=[TCPService('HTTP'), TCPService('HTTPS')], action='allow', ) # Rule with custom action and logging log_opts = LogOptions() log_opts.log_accounting_info_mode = True log_opts.log_level = 'stored' action = Action() action.deep_inspection = True policy.fw_ipv4_access_rules.create( name='inspect-internal', sources=[Network('internal-net')], destinations='any', services='any', action=action, log_options=log_opts, add_pos=1, # insert at position 1 ) # Discard rule at a specific position policy.fw_ipv4_access_rules.create( name='block-rfc1918-inbound', sources=[Network('internal-net')], destinations='any', services='any', action='discard', add_pos=50, ) # List all rules for rule in policy.fw_ipv4_access_rules.all(): print(f" Rule: {rule.name}, action: {rule.action.action}") # Search rules by name results = policy.search_rule('allow-web-outbound') print("Found:", results) # Delete a specific rule for rule in policy.fw_ipv4_access_rules.all(): if rule.name == 'block-rfc1918-inbound': rule.delete() print("Deleted rule") except CreatePolicyFailed as e: print("Error:", e) finally: session.logout() ``` -------------------------------- ### Create a Basic Firewall Policy Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/policy.rst Create a new firewall policy by referencing an existing policy template by its name. This establishes a foundational policy structure. ```python from smc.policy.layer3 import FirewallPolicy FirewallPolicy.create('newpolicy', template='Firewall Template') ``` -------------------------------- ### Manage Engine Routing and Antispoofing Source: https://context7.com/forcepoint/fp-ngfw-smc-python/llms.txt Shows how to view and configure static routes and antispoofing settings for an engine. Requires an existing engine and network elements. ```python from smc import session from smc.core.engine import Engine from smc.elements.network import Router, Network session.login(url='http://192.168.1.10:8082', api_key='myApiKey123') engine = Engine('my-firewall') # View routing table for network in engine.routing.all(): print("Routing entry:", network) # Add a static route (route via specific interface) interface = engine.interface.get(1) # get interface 1 interface.add_static_route( gateway=Router('default-gateway'), network=[Network('0.0.0.0/0')], ) # View antispoofing configuration for entry in engine.antispoofing.all(): print("Antispoofing:", entry) # View BGP dynamic routing (if configured) for bgp in engine.dynamic_routing.bgp.all(): print("BGP:", bgp) session.logout() ``` -------------------------------- ### Counting Results Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Use the `count()` method to get the number of elements matching the search criteria. ```APIDOC ## Counting Results ### Description Helper collection method which returns the number of results. You can still obtain the results after counting. ### Method `count()` ### Code Example ```python it = Router.objects.iterator() query1 = it.filter('10.10.10.1') query1.count() list(query1) ``` ``` -------------------------------- ### Get Available Object Types Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Retrieves a list of all available element types that can be searched for in the SMC API. ```APIDOC ## Get Available Object Types ### Description This operation returns a list of all searchable object types (entry points) available in the SMC API. ### Method `Search.object_types()` ### Parameters None ### Response Example ```python [ 'elements', 'sub_ipv6_fw_policy', 'ids_alert', 'application_not_specific_tag', 'fw_alert', 'virtual_ips', 'sidewinder_tag', 'os_specific_tag', 'eia_application_usage_group_tag', 'external_bgp_peer', 'local_cluster_cvi_alias', 'ssl_vpn_service_profile', 'active_directory_server', 'eia_golden_image_tag', 'client_gateway', 'situation_tag', 'api_client', 'tls_match_situation', 'ssl_vpn_policy', 'category_group_tag', 'ip_list', 'vpn_profile', 'ipv6_access_list', 'appliance_information', 'single_layer2', 'ei_executable', 'community_access_list' ] ``` ``` -------------------------------- ### Create Network Elements Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/elements.rst Demonstrates the creation of Host, Network, and AddressRange elements. Ensure the necessary classes are imported from smc.elements.network. ```python from smc.elements.network import Host, Network, AddressRange >>> host = Host.create(name='hostelement', address='1.1.1.1') >>> host Host(name=hostelement) >>> host.address u'1.1.1.1' >>> network = Network.create(name='networkelement', ipv4_network='1.1.1.0/24', comment='mynet') >>> network Network(name=networkelement) >>> network.ipv4_network u'1.1.1.0/24' >>> network.comment u'mynet' >>> AddressRange.create(name='myaddrrange', ip_range='1.1.1.1-1.1.1.10') AddressRange(name=myaddrrange) ``` -------------------------------- ### Filter TCP Services by Name Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Filter TCP Service elements by a string, such as a service name. This example searches for 'HTTP'. ```python >>> list(TCPService.objects.filter('HTTP')) [TCPService(name=HTTPS_No_Decryption), TCPService(name=Squid HTTP proxy), TCPService(name=HTTP to Web SaaS)] ``` -------------------------------- ### Modify Existing Interface IP Address Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/engine.rst Example of how to change the IP address of an existing single-node interface. Remember to save changes. ```APIDOC ## Modify Existing Interface IP Address ### Description Demonstrates the process of changing the IP address assigned to an existing single-node interface. It's crucial to save the changes after modification. ### Method `engine.interface.all()` followed by modification of interface attributes and `interface.save()` ### Parameters - `interface.name` (str) - The name of the interface to modify. - New IP address details to be set on the interface object. ### Request Example ```python # Obtain a reference to the interface for interface in engine.interface.all(): if interface.name == 'YourInterfaceName': # Replace with the actual interface name # Modify the IP address (example assumes a method to set IP, actual implementation may vary) # interface.set_ip_address('new_ip_address', 'new_netmask') # Save the changes interface.save() break ``` .. note:: Save must be called on the interface itself or changes will only be made to a local copy of the element. ``` -------------------------------- ### VPN Site Creation Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/vpn.rst Illustrates how to create a VPN site configuration for an external gateway, linking it to network elements. ```APIDOC ## VPN Site Creation ### Description Configure a VPN site for an external gateway, associating it with specific network elements. ### Method ```python ExternalGateway.vpn_site.create(name: str, networks: list) ``` ### Parameters * **name** (str) - Required - The name of the VPN site. * **networks** (list) - Required - A list of network element hrefs to associate with this site. ### Request Example ```python >>> network = Network('internal-network') >>> gateway.vpn_site.create('remote-site', [network.href]) 'http://1.1.1.1:8082/7.1/elements/external_gateway/22961/vpn_site/22994' ``` ``` -------------------------------- ### Count Matching Elements Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Use the .count() method to get the number of elements that match the query. The results can still be retrieved after counting. ```python >>> it = Router.objects.iterator() >>> query1 = it.filter('10.10.10.1') >>> query1.count() 3 >>> list(query1) [Router(name=Router-110.10.10.10), Router(name=Router-10.10.10.10), Router(name=Router-10.10.10.1)] ``` -------------------------------- ### Add VLAN to Inline Interface Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/engine.rst This example shows how to add VLANs to layer 2 or IPS inline interfaces, associating them with a logical interface. ```APIDOC ## Add VLAN to Inline Interface ### Description Adds a VLAN to a specified range of physical interface IDs. This operation associates the VLAN with a logical interface. ### Method `engine.physical_interface.add_vlan_to_inline_interface` ### Parameters - `interface_id` (str) - The range of physical interface IDs (e.g., '5-6'). - `vlan_id` (int) - The VLAN ID to assign. - `logical_interface_ref` (LogicalInterface) - Reference to the logical interface. ### Request Example ```python logical_interface = logical_intf_helper('default_eth') engine.physical_interface.add_vlan_to_inline_interface(interface_id='5-6', vlan_id=56, logical_interface_ref=logical_interface) engine.physical_interface.add_vlan_to_inline_interface(interface_id='5-6', vlan_id=57, logical_interface_ref=logical_interface) engine.physical_interface.add_vlan_to_inline_interface(interface_id='5-6', vlan_id=58, logical_interface_ref=logical_interface) ``` .. note:: The physical interface will be created if it doesn't already exist. ``` -------------------------------- ### Create and Configure VPN Policy Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/vpn.rst Creates a VPN Policy, applying internal and external gateways. Ensure to call open(), save(), and close() on the policy object. ```python vpn = PolicyVPN.create(name='myVPN', nat=True) print(vpn.name, vpn.vpn_profile) vpn.open() vpn.add_central_gateway(engine.internal_gateway.href) vpn.add_satellite_gateway(external_gateway.href) vpn.save() vpn.close() ``` -------------------------------- ### Configuration File Login Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/session.rst Simplify login by storing SMC connection details in a `~/.smcrc` file. This eliminates the need to hardcode credentials in scripts. The `alt_filepath` argument can be used to specify an alternative configuration file location. ```python [smc] smc_address=1.1.1.1 smc_apikey=xxxxxxxxxxxxxxxxxxx api_version=7.1 smc_port=8082 smc_ssl=True verify_ssl=True ssl_cert_file='/Users/username/home/mycacert.pem' domain=mydomain ``` ```python session.login() session.logout() ``` ```python session.login(alt_filepath='/home/somedir/test') ``` -------------------------------- ### Retrieve the First Element Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Use the .first() method on an ElementCollection iterator to get only the first element matching the query. This is an alternative to iterating and breaking. ```python >>> host = Host.objects.iterator() >>> host.first() Host(name=SMC) ``` -------------------------------- ### Retrieve only firewall clusters Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Use `context_filter('fw_clusters')` to specifically retrieve a list of all firewall cluster elements. This is a direct way to get this subset of elements. ```python >>> list(Search.objects.context_filter('fw_clusters')) [FirewallCluster(name=sg_vm), Layer3VirtualEngine(name=ve-8), Layer3Firewall(name=testfw), Layer3Firewall(name=i-04eec8f019adf818e (us-east-2a)), MasterEngine(name=master)] ``` -------------------------------- ### Create Elements Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/elements.rst Demonstrates how to create various types of elements like Host, Network, and AddressRange. The create() method returns the href of the new element or raises an exception on failure. ```APIDOC ## Create Elements Elements within the Management Server are common object types that are referenced by other configurable areas of the system such as policy, routing, VPN, etc. Examples of creating elements are as follows: ```python >> from smc.elements.network import Host, Network, AddressRange >>> host = Host.create(name='hostelement', address='1.1.1.1') >>> host Host(name=hostelement) >>> host.address u'1.1.1.1' >>> network = Network.create(name='networkelement', ipv4_network='1.1.1.0/24', comment='mynet') >>> network Network(name=networkelement) >>> network.ipv4_network u'1.1.1.0/24' >>> network.comment u'mynet' >>> AddressRange.create(name='myaddrrange', ip_range='1.1.1.1-1.1.1.10') AddressRange(name=myaddrrange) ``` ``` -------------------------------- ### Limit Number of Returned Host Entries Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/collections.rst Limit the number of Host elements returned from a collection query. This example retrieves the first 3 Host elements. ```python >>> list(Host.objects.limit(3)) [Host(name=SMC), Host(name=172.18.1.135), Host(name=172.18.2.254)] ``` -------------------------------- ### Create Layer3VirtualEngine Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/engine.rst Creates a Layer 3 Virtual Engine with specified interfaces. ```APIDOC ## Create Layer3VirtualEngine ### Description Creates a Layer 3 Virtual Engine with specified interfaces. ### Method ```python Layer3VirtualEngine.create(name, master_engine, virtual_resource, interfaces) ``` ### Parameters - **name** (str) - The name of the virtual engine. - **master_engine** (str) - The name or IP address of the master engine. - **virtual_resource** (str) - The name of the virtual resource. - **interfaces** (list) - A list of dictionaries, where each dictionary defines an interface with 'address', 'network_value', and 'interface_id'. ### Request Example ```python from smc.core.engines import Layer3VirtualEngine Layer3VirtualEngine.create(name='myvirtual', master_engine='api-master', virtual_resource='ve-1', interfaces=[{'address':'5.5.5.5','network_value':'5.5.5.0/24','interface_id':0}, {'address':'6.6.6.6','network_value':'6.6.6.0/24','interface_id':1}]) ``` ``` -------------------------------- ### View Available System Update Packages Source: https://github.com/forcepoint/fp-ngfw-smc-python/blob/master/smc/docs/pages/administration.rst Instantiate the System class and call update_package() to retrieve a list of available update packages. The result can be printed as a list. ```python from smc.administration.system import System system = System() available_packages = system.update_package() print(list(available_packages)) ```