### Install fortigate-api Source: https://context7.com/vladimirs-git/fortigate-api/llms.txt Install the package using pip from PyPI or directly from GitHub. ```bash pip install fortigate-api ``` ```bash # or from source pip install git+https://github.com/vladimirs-git/fortigate-api ``` -------------------------------- ### Python Fortigate API Extended Filtering Examples Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/extended_filtering_conditions.rst Demonstrates creating firewall resources and applying extended filtering conditions to retrieve policy rules. Includes examples for equals, not equals, subnets, and supernets operators. Ensure the FortiOS library is installed and connection details are correctly configured. ```python import logging from fortigate_api import FortiOS logging.getLogger().setLevel(logging.DEBUG) HOST = "host" USERNAME = "username" PASSWORD = "password" api = FortiOS(host=HOST, username=USERNAME, password=PASSWORD) # Create address, address-group and policy in the Fortigate for idx in range(2): data = { "name": f"ADDRESS_{idx}", "obj-type": "ip", "subnet": f"127.0.{idx}.0 255.255.255.252", "type": "ipmask", } response = api.cmdb.firewall.address.create(data=data) print("address.create", response) # address.create data = {"name": "ADDR_GROUP", "member": [{"name": "ADDRESS_1"}]} response = api.cmdb.firewall.addrgrp.create(data=data) print("addrgrp.create", response) # addrgrp.create data = dict( name="POLICY", status="enable", action="accept", srcintf=[{"name": "any"}], dstintf=[{"name": "any"}], srcaddr=[{"name": "ADDRESS_0"}], dstaddr=[{"name": "ADDR_GROUP"}], service=[{"name": "ALL"}], schedule="always", ) response = api.cmdb.firewall.policy.create(data=data) print("policy.create", response) # policy.create # Get the rules where source prefix is equals 127.0.0.0/30 efilters = "srcaddr==127.0.0.0/30" items = api.cmdb.firewall.policy.get(efilters=efilters) print(f"{efilters=}", len(items)) # efilters="srcaddr==127.0.0.0/30" 1 # Get the rules where source prefix is not equals 127.0.0.0/30 efilters = "srcaddr!=127.0.0.0/30" items = api.cmdb.firewall.policy.get(efilters=efilters) print(f"{efilters=}", len(items)) # efilters="srcaddr!=127.0.0.0/30" 3 # Get the rules where source addresses are in subnets of 127.0.0.0/24 efilters = "srcaddr<=127.0.0.0/24" items = api.cmdb.firewall.policy.get(efilters=efilters) print(f"{efilters=}", len(items)) # efilters="srcaddr<=127.0.0.0/24" 1 # Get the rules where source prefixes are supernets of address 127.0.0.1/32 efilters = "srcaddr>=127.0.0.1/32" items = api.cmdb.firewall.policy.get(efilters=efilters) print(f"{efilters=}", len(items)) # efilters="srcaddr>=127.0.0.1/32" 3 # Get the rules where source are equals 127.0.0.0/30 and destination are equals 127.0.2.0/30 efilters = ["srcaddr==127.0.0.0/30", "dstaddr==127.0.1.0/30"] items = api.cmdb.firewall.policy.get(efilters=efilters) print(f"{efilters=}", len(items)) # efilters=["srcaddr==127.0.0.0/30", "dstaddr==127.0.1.0/30"] 1 # Delete policy, address-group, addresses from the Fortigate (order is important) response = api.cmdb.firewall.policy.delete(filters="name==POLICY") print("policy.delete", response) # policy.delete response = api.cmdb.firewall.addrgrp.delete("ADDR_GROUP") print("addrgrp.delete", response) # addrgrp.delete response = api.cmdb.firewall.address.delete("ADDRESS_0") print("address.delete", response) # address.delete response = api.cmdb.firewall.address.delete("ADDRESS_1") print("address.delete", response) # address.delete api.logout() ``` -------------------------------- ### Install fortigate-api using pip Source: https://github.com/vladimirs-git/fortigate-api/blob/main/README.rst Install the package from pypi.org using pip. ```bash pip install fortigate-api ``` -------------------------------- ### Install fortigate-api from GitHub Source: https://github.com/vladimirs-git/fortigate-api/blob/main/README.rst Install the package directly from the GitHub repository using pip. ```bash pip install git+https://github.com/vladimirs-git/fortigate-api ``` -------------------------------- ### Get Resource (GET) Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/FortiGate.rst Demonstrates how to retrieve a specific resource from the FortiGate device using the `get` method. ```APIDOC ## Get Resource (GET) ### Description Retrieve a specific resource from the FortiGate device using the `get` method. This requires the API endpoint URL for the resource. ### Method `get(url: str)` ### Endpoint `api/v2/cmdb/firewall/address/ADDRESS` ### Parameters #### Path Parameters - **ADDRESS** (str) - Required - The name or identifier of the resource to retrieve. ### Request Example ```python response = fgt.get(url="api/v2/cmdb/firewall/address/ADDRESS") print(f"GET {response}") result = response.json()["results"] pprint(result) ``` ### Response #### Success Response (200) Returns a JSON object containing the requested resource details. ``` -------------------------------- ### FortiGateAPI - Initialization and Authentication Source: https://context7.com/vladimirs-git/fortigate-api/llms.txt Demonstrates how to initialize the FortiGateAPI client using username/password or API token authentication, and includes examples of explicit login and context manager usage. ```APIDOC ## FortiGateAPI Initialization and Authentication ### Description Initialize the `FortiGateAPI` client with either username/password or an API token. Supports various connection parameters and optional explicit login. ### Usage **Username/Password Authentication:** ```python from fortigate_api import FortiGateAPI api = FortiGateAPI( host="192.168.1.1", username="admin", password="secret", scheme="https", # "https" (default) or "http" port=443, # default: 443 for https, 80 for http timeout=15, # session timeout in minutes verify=False, # TLS cert verification vdom="root", # virtual domain, default "root" logging_error=True, # log only error responses ) ``` **Token-Based Authentication:** ```python api_token = FortiGateAPI(host="192.168.1.1", token="your-api-token") ``` **Explicit Login (Optional):** ```python api.login() ``` **Context Manager for Automatic Session Cleanup:** ```python with FortiGateAPI(host="192.168.1.1", username="admin", password="secret") as api: items = api.cmdb.firewall.address.get(name="all") print(items[0]["subnet"]) ``` **Changing VDOM at Runtime:** ```python api.vdom = "VDOM9" items = api.cmdb.system.interface.get() print(f"interfaces in VDOM9: {len(items)}") ``` **Logout:** ```python api.logout() ``` ``` -------------------------------- ### Get Global System Configuration Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/cmdb/system/global_.rst Retrieves the current global system configuration settings from the FortiGate. ```APIDOC ## Get Global System Configuration ### Description Retrieves the current global system configuration from the FortiGate. ### Method GET ### Endpoint /api/v2/cmdb/system/global ### Parameters This endpoint does not require any parameters. ### Request Example ```python result = api.cmdb.system.global_.get() ``` ### Response #### Success Response (200) - A list of dictionaries, where each dictionary represents a global system setting. - Example fields include `admin-concurrent`, `admin-console-timeout`, `admin-hsts-max-age`, `timezone`, etc. #### Response Example ```json [ { "admin-concurrent": "enable", "admin-console-timeout": 300, "admin-hsts-max-age": 15552000, "timezone": "80" } ] ``` ``` -------------------------------- ### FortiGateAPI Initialization and Address Management Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/FortiGateAPI.rst Demonstrates how to initialize the FortiGateAPI, log in, and perform create, get, update, delete, and existence check operations for firewall address objects. ```APIDOC ## Initialize FortiGateAPI ### Description Initializes the FortiGateAPI client with host, username, password, and optional scheme and port. ### Method `FortiGateAPI(host, username, password, scheme='https', port=443, logging_error=False)` ### Parameters - **host** (string) - Required - The hostname or IP address of the FortiGate device. - **username** (string) - Required - The username for authentication. - **password** (string) - Required - The password for authentication. - **scheme** (string) - Optional - The connection scheme (e.g., 'https'). Defaults to 'https'. - **port** (integer) - Optional - The connection port. Defaults to 443. - **logging_error** (boolean) - Optional - Enables logging of errors. Defaults to False. ### Request Example ```python from fortigate_api import FortiGateAPI api = FortiGateAPI( host="host", username="username", password="password", scheme="https", port=443, logging_error=True, ) api.login() # login is optional ``` ## Create Firewall Address ### Description Creates a new firewall address object on the FortiGate device. ### Method `api.cmdb.firewall.address.create(data)` ### Parameters - **data** (dict) - Required - A dictionary containing the address object details. - **name** (string) - Required - The name of the address object. - **obj-type** (string) - Required - The type of the object (e.g., 'ip'). - **subnet** (string) - Required - The IP address and subnet mask. - **type** (string) - Required - The type of address (e.g., 'ipmask'). ### Request Example ```python data = { "name": "ADDRESS", "obj-type": "ip", "subnet": "127.0.0.100 255.255.255.252", "type": "ipmask", } response = api.cmdb.firewall.address.create(data) ``` ## Get Firewall Address ### Description Retrieves firewall address objects by name. ### Method `api.cmdb.firewall.address.get(name)` ### Parameters - **name** (string) - Required - The name of the address object to retrieve. ### Request Example ```python items = api.cmdb.firewall.address.get(name="ADDRESS") ``` ## Update Firewall Address ### Description Updates an existing firewall address object on the FortiGate device. ### Method `api.cmdb.firewall.address.update(data)` ### Parameters - **data** (dict) - Required - A dictionary containing the updated address object details. Must include the 'name' field. - **name** (string) - Required - The name of the address object to update. - **subnet** (string) - Optional - The updated subnet mask. ### Request Example ```python data = {"name": "ADDRESS", "subnet": "127.0.0.255 255.255.255.255"} response = api.cmdb.firewall.address.update(data) ``` ## Delete Firewall Address ### Description Deletes a firewall address object from the FortiGate device. ### Method `api.cmdb.firewall.address.delete(name)` ### Parameters - **name** (string) - Required - The name of the address object to delete. ### Request Example ```python response = api.cmdb.firewall.address.delete("ADDRESS") ``` ## Check Firewall Address Existence ### Description Checks if a firewall address object exists on the FortiGate device. ### Method `api.cmdb.firewall.address.is_exist(name)` ### Parameters - **name** (string) - Required - The name of the address object to check. ### Request Example ```python response = api.cmdb.firewall.address.is_exist("ADDRESS") ``` ## FortiGateAPI `with` Statement ### Description Demonstrates using the FortiGateAPI with a `with` statement for automatic resource management (login/logout). ### Method `with FortiGateAPI(host, username, password) as api:` ### Parameters - **host** (string) - Required - The hostname or IP address of the FortiGate device. - **username** (string) - Required - The username for authentication. - **password** (string) - Required - The password for authentication. ### Request Example ```python with FortiGateAPI(host=HOST, username=USERNAME, password=PASSWORD) as api: response = api.cmdb.firewall.address.is_exist("ADDRESS") print("address.is_exist", response) ``` ``` -------------------------------- ### FortiOS System Interface Configuration Example Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/data/cmdb/cmdb_system_interface.rst This YAML snippet illustrates a comprehensive configuration for a FortiOS system interface, including network settings, security features, and advanced options. ```yaml ac-name: '' algorithm: L4 alias: '' allowaccess: '' ap-discover: enable arpforward: enable auth-type: auto auto-auth-extension-device: disable bandwidth-measure-time: 0 bfd: global bfd-desired-min-tx: 250 bfd-detect-mult: 3 bfd-required-min-rx: 250 broadcast-forward: disable captive-portal: 0 cli-conn-status: 0 client-options: [] color: 0 dedicated-to: none defaultgw: enable description: '' detected-peer-mtu: 0 detectprotocol: ping detectserver: '' device-identification: enable device-user-identification: enable devindex: 39 dhcp-client-identifier: '' dhcp-relay-agent-option: enable dhcp-relay-interface: '' dhcp-relay-interface-select-method: auto dhcp-relay-ip: '' dhcp-relay-service: disable dhcp-relay-type: regular dhcp-renew-time: 0 disc-retry-timeout: 1 disconnect-threshold: 0 distance: 5 dns-server-override: enable drop-fragment: disable drop-overlapped-fragment: disable egress-shaping-profile: '' estimated-downstream-bandwidth: 0 estimated-upstream-bandwidth: 0 explicit-ftp-proxy: disable explicit-web-proxy: disable external: disable fail-action-on-extender: soft-restart fail-alert-interfaces: [] fail-alert-method: link-down fail-detect: disable fail-detect-option: link-down fortilink: disable fortilink-backup-link: 0 fortilink-neighbor-detect: fortilink fortilink-split-interface: enable fortilink-stacking: enable forward-domain: 0 gwdetect: disable ha-priority: 1 icmp-accept-redirect: enable icmp-send-redirect: enable ident-accept: disable idle-timeout: 0 inbandwidth: 0 ingress-shaping-profile: '' ingress-spillover-threshold: 0 interface: '' internal: 0 ip: 0.0.0.0 0.0.0.0 ip-managed-by-fortiipam: disable ipmac: disable ips-sniffer-mode: disable ipunnumbered: 0.0.0.0 ipv6: autoconf: disable dhcp6-client-options: '' dhcp6-information-request: disable dhcp6-prefix-delegation: disable dhcp6-prefix-hint: ::/0 dhcp6-prefix-hint-plt: 604800 dhcp6-prefix-hint-vlt: 2592000 dhcp6-relay-ip: '' dhcp6-relay-service: disable dhcp6-relay-type: regular icmp6-send-redirect: enable interface-identifier: '::' ip6-address: ::/0 ip6-allowaccess: '' ip6-default-life: 1800 ip6-delegated-prefix-list: [] ip6-dns-server-override: enable ip6-extra-addr: [] ip6-hop-limit: 0 ip6-link-mtu: 0 ip6-manage-flag: disable ip6-max-interval: 600 ip6-min-interval: 198 ip6-mode: static ip6-other-flag: disable ip6-prefix-list: [] ip6-reachable-time: 0 ip6-retrans-time: 0 ip6-send-adv: disable ip6-subnet: ::/0 ip6-upstream-interface: '' nd-cert: '' nd-cga-modifier: 000000000000000073735B765D202573 nd-mode: basic nd-security-level: 0 nd-timestamp-delta: 300 nd-timestamp-fuzz: 1 unique-autoconf-addr: disable vrip6_link_local: '::' vrrp6: [] l2forward: disable l2tp-client: disable l2tp-client-settings: auth-type: auto defaultgw: disable distance: 2 ip: 0.0.0.0 0.0.0.0 mtu: 1460 password: '' peer-host: '' peer-mask: 255.255.255.255 peer-port: 1701 priority: 0 user: '' lacp-ha-slave: enable lacp-mode: active lacp-speed: slow lcp-echo-interval: 5 lcp-max-echo-fails: 3 link-up-delay: 50 lldp-network-policy: '' lldp-reception: enable lldp-transmission: enable macaddr: 00:00:00:00:00:00 managed-subnetwork-size: '256' management-ip: 0.0.0.0 0.0.0.0 measured-downstream-bandwidth: 0 measured-upstream-bandwidth: 0 member: - interface-name: port1 q_origin_key: port1 - interface-name: port2 q_origin_key: port2 min-links: 1 min-links-down: operational mode: static monitor-bandwidth: enable mtu: 1500 mtu-override: disable name: INTERFACE_NAME ndiscforward: enable netbios-forward: disable netflow-sampler: disable outbandwidth: 0 padt-retry-timeout: 1 password: '' ping-serv-status: 0 polling-interval: 20 pppoe-unnumbered-negotiate: enable pptp-auth-type: auto pptp-client: disable pptp-password: '' pptp-server-ip: 0.0.0.0 pptp-timeout: 0 pptp-user: '' preserve-session-route: disable priority: 0 priority-override: enable proxy-captive-portal: disable q_origin_key: INTERFACE_NAME remote-ip: 0.0.0.0 0.0.0.0 replacemsg-override-group: '' role: undefined sample-direction: both sample-rate: 2000 secondary-IP: disable secondaryip: [] ``` -------------------------------- ### Manage VDOMs with FortiGateAPI Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/cmdb/system/vdom.rst Demonstrates the full lifecycle of VDOM management, including creation, retrieval by name, deletion, and checking for existence. Ensure you have the FortiGateAPI library installed and your connection details are correctly configured. ```python from pprint import pprint from fortigate_api import FortiGateAPI HOST = "host" USERNAME = "username" PASSWORD = "password" api = FortiGateAPI(host=HOST, username=USERNAME, password=PASSWORD) # Create vdom in the Fortigate data = {"name": "VDOM1"} response = api.cmdb.system.vdom.create(data) print(f"vdom.create {response}") # vdoms.create # Get all vdoms from the Fortigate items = api.cmdb.system.vdom.get() print(f"vdoms count={len(items)}") # vdoms count=3 # Get vdom by name (unique identifier) items = api.cmdb.system.vdom.get(name="VDOM1") print(f"vdoms count={len(items)}") # vdoms count=1 pprint(items) # [{'flag': 0, # 'name': 'VDOM1', # 'q_origin_key': 'VDOM1', # 'short-name': 'VDOM1', # 'vcluster-id': 0}] # Delete vdom from the Fortigate response = api.cmdb.system.vdom.delete("VDOM1") print(f"vdom.delete {response}") # vdoms.delete # Check for presence of vdom in the Fortigate response = api.cmdb.system.vdom.is_exist("VDOM1") print("vdom.is_exist", response) # vdom.is_exist False api.logout() ``` -------------------------------- ### Manage Fortigate VDOMs Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/objects/Vdoms.rst Demonstrates the full lifecycle of a VDOM: creation, retrieval (all and by name), and deletion. Ensure you have the FortigateAPI library installed and configured with your Fortigate's host, username, and password. ```python import logging from pprint import pprint from fortigate_api import FortigateAPI logging.getLogger().setLevel(logging.DEBUG) HOST = "host" USERNAME = "username" PASSWORD = "password" fgt = FortigateAPI(host=HOST, username=USERNAME, password=PASSWORD) # Create vdom in the Fortigate data = { "name": "VDOM1", } response = fgt.vdoms.create(data) print(f"vdoms.create {response}") # vdoms.create # Get all vdoms from the Fortigate vdoms = fgt.vdoms.get() pprint(vdoms) # [{'flag': 0, # 'name': 'VDOM1', # 'q_origin_key': 'VDOM1', # 'short-name': 'VDOM1', # 'vcluster-id': 0}, # {'flag': 0, # 'name': 'root', # 'q_origin_key': 'root', # 'short-name': 'root', # 'vcluster-id': 0}] # Get vdom by name (unique identifier) vdoms = fgt.vdoms.get(uid="VDOM1") pprint(vdoms) # [{'flag': 0, # 'name': 'VDOM1', # 'q_origin_key': 'VDOM1', # 'short-name': 'VDOM1', # 'vcluster-id': 0}] # Delete vdom from the Fortigate response = fgt.vdoms.delete(uid="VDOM1") print(f"vdoms.delete {response}") # vdoms.delete fgt.logout() ``` -------------------------------- ### Create Test Firewall Addresses Source: https://context7.com/vladimirs-git/fortigate-api/llms.txt Creates three test firewall address objects with sequential names and subnets for filtering examples. ```python for i in range(3): api.cmdb.firewall.address.create({ "name": f"TEST_{i}", "subnet": f"10.0.{i}.0 255.255.255.0", "type": "ipmask", }) ``` -------------------------------- ### Configure System External Resource (YAML) Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/data/cmdb/cmdb_system_external_resource.rst Example of configuring a system external resource using YAML format. This defines parameters like resource URL, refresh rate, and status. ```yaml category: 0 comments: '' interface: '' interface-select-method: auto name: EXTERNAL_RESOURCE_NAME password: '' q_origin_key: EXTERNAL_RESOURCE_NAME refresh-rate: 5 resource: https://domain.com/resource.txt source-ip: 0.0.0.0 status: enable type: category user-agent: curl/7.58.0 username: '' ``` -------------------------------- ### Get List of Resources (get_results) Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/FortiGate.rst Explains how to fetch a list of resources from the 'results' section of the JSON response using `get_results`. ```APIDOC ## Get List of Resources (get_results) ### Description Fetch a list of resources from the 'results' section of the JSON response. This is useful for retrieving multiple objects of a specific type. ### Method `get_results(url: str)` ### Endpoint `api/v2/cmdb/firewall/address` ### Parameters #### Query Parameters - **url** (str) - Required - The API endpoint URL to fetch the list of resources. ### Request Example ```python items = fgt.get_results(url="api/v2/cmdb/firewall/address") print(f"addresses count={len(items)}") ``` ### Response #### Success Response (200) Returns a list of resource objects. ``` -------------------------------- ### Firewall IP Pool Configuration Example Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/data/cmdb/cmdb_firewall_ippool.rst This YAML snippet shows a sample configuration for a FortiOS firewall IP pool. It includes settings for the IP range, type of NAT, and other pool-specific options. ```yaml arp-intf: '' arp-reply: enable associated-interface: '' block-size: 128 comments: '' endip: 10.0.0.1 name: IP_POOL_NAME num-blocks-per-user: 8 pba-timeout: 30 permit-any-host: disable q_origin_key: IP_POOL_NAME source-endip: 0.0.0.0 source-startip: 0.0.0.0 startip: 10.0.0.1 type: overload ``` -------------------------------- ### FortiGateAPI - CMDB Operations Source: https://context7.com/vladimirs-git/fortigate-api/llms.txt Examples of using the high-level `FortiGateAPI` to interact with the Configuration Database (CMDB) for managing firewall addresses. ```APIDOC ## FortiGateAPI - CMDB Operations ### Description Perform Create, Read, Update, Delete (CRUD) operations on FortiGate configuration objects using the `api.cmdb` interface. ### Example: Managing Firewall Addresses **Get all addresses:** ```python items = api.cmdb.firewall.address.get(name="all") print(items[0]["subnet"]) ``` **Get a specific address by name:** ```python address = api.cmdb.firewall.address.get(name="MyAddress") ``` **Create a new address:** ```python api.cmdb.firewall.address.create(name="NewAddress", subnet="192.168.1.0 255.255.255.0") ``` **Update an existing address:** ```python api.cmdb.firewall.address.update(name="NewAddress", subnet="192.168.1.0 255.255.255.0", comment="Updated subnet") ``` **Delete an address:** ```python api.cmdb.firewall.address.delete(name="NewAddress") ``` **Check if an address exists:** ```python exists = api.cmdb.firewall.address.is_exist(name="NewAddress") print(f"Address exists: {exists}") ``` ``` -------------------------------- ### Create and Get External Resources Source: https://context7.com/vladimirs-git/fortigate-api/llms.txt Configures external resources, which allow FortiGate to fetch dynamic IP or URL lists from external sources for threat intelligence. Supports 'address' and 'domain' types. ```python from fortigate_api import FortiGateAPI api = FortiGateAPI(host="192.168.1.1", username="admin", password="secret") # Create an address-type external resource response = api.cmdb.system.external_resource.create({ "name": "THREAT_FEED", "resource": "https://feeds.example.com/malicious-ips.txt", "type": "address", "refresh-rate": 60, # minutes }) print(f"external_resource.create {response}") # external_resource.create # Create a domain-type external resource response = api.cmdb.system.external_resource.create({ "name": "DOMAIN_BLOCK", "resource": "https://feeds.example.com/malicious-domains.txt", "type": "domain", }) print(f"external_resource.create {response}") # external_resource.create # List all external resources items = api.cmdb.system.external_resource.get() print(f"resources: {len(items)}") # resources: 2 ``` -------------------------------- ### Create, Get, Update, and Delete IP Pool Source: https://context7.com/vladimirs-git/fortigate-api/llms.txt Demonstrates the full CRUD lifecycle for IP pools, which are used for NAT address pools in firewall policies. Ensure the FortiGateAPI is initialized with connection details. ```python from fortigate_api import FortiGateAPI api = FortiGateAPI(host="192.168.1.1", username="admin", password="secret") # Create an IP pool response = api.cmdb.firewall.ippool.create({ "name": "NAT_POOL", "startip": "203.0.113.10", "endip": "203.0.113.20", "type": "overload", # many-to-one NAT }) print(f"ippool.create {response}") # ippool.create # Get all IP pools pools = api.cmdb.firewall.ippool.get() print(f"pools: {len(pools)}") # pools: 2 # Get by name pool = api.cmdb.firewall.ippool.get(name="NAT_POOL") print(pool[0]["startip"]) # 203.0.113.10 # Update pool comment response = api.cmdb.firewall.ippool.update({"name": "NAT_POOL", "comments": "Outbound NAT pool"}) print(f"ippool.update {response}") # ippool.update # Check existence print(api.cmdb.firewall.ippool.is_exist("NAT_POOL")) # True # Delete response = api.cmdb.firewall.ippool.delete("NAT_POOL") print(f"ippool.delete {response}") # ippool.delete api.logout() ``` -------------------------------- ### Get All DHCP Servers Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/objects/DhcpServer.rst Retrieves a list of all configured DHCP servers on the Fortigate device. This is useful for auditing or getting an overview of the current DHCP setup. ```python print("\nGets all dhcp_server") dhcp_servers = fgt.dhcp_server.get() print(f"dhcp_servers count={len(dhcp_servers)}") # dhcp_server count=3 ``` -------------------------------- ### Quickstart FortiGate: Manage Firewall Addresses via Raw API Calls Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/index.rst Demonstrates creating, retrieving, updating, and deleting firewall addresses using the FortiGate class, which makes direct REST API calls. Requires host, username, and password configuration. ```python """Quickstart FortiGate. - Creates address in the Fortigate - Get address by name (unique identifier) - Updates address data in the Fortigate - Delete address from the Fortigate """ from pprint import pprint from fortigate_api import FortiGate HOST = "host" USERNAME = "username" PASSWORD = "password" fgt = FortiGate(host=HOST, username=USERNAME, password=PASSWORD) # Creates address in the Fortigate data = { "name": "ADDRESS", "obj-type": "ip", "subnet": "127.0.0.100 255.255.255.252", "type": "ipmask", } response = fgt.post(url="api/v2/cmdb/firewall/address/", data=data) print(f"POST {response}", ) # POST # Get address by name (unique identifier) response = fgt.get(url="api/v2/cmdb/firewall/address/ADDRESS") print(f"GET {response}", ) # POST result = response.json()["results"] pprint(result) # [{"name": "ADDRESS", # "subnet": "127.0.0.100 255.255.255.252", # "uuid": "a386e4b0-d6cb-51ec-1e28-01e0bc0de43c", # ... # }] # Updates address data in the Fortigate data = {"name": "ADDRESS", "subnet": "127.0.0.255 255.255.255.255"} response = fgt.put(url="api/v2/cmdb/firewall/address/ADDRESS", data=data) print(f"PUT {response}") # PUT # Delete address from the Fortigate ``` -------------------------------- ### FortiGate Initialization and Login Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/FortiGate.rst Demonstrates how to initialize the FortiGate client with host, username, password, and optional scheme/port, and how to perform an optional login. ```APIDOC ## FortiGate Initialization and Login ### Description Initialize the FortiGate client with connection details and optional parameters like scheme and port. A login step is also shown, which is optional. ### Usage ```python from fortigate_api import FortiGate HOST = "host" USERNAME = "username" PASSWORD = "password" # Initialize FortiGate with optional parameters scheme=`https`, port=443 fgt = FortiGate( host=HOST, username=USERNAME, password=PASSWORD, scheme="https", port=443, logging_error=True, ) fgt.login() # login is optional ``` ``` -------------------------------- ### Initialize and Use FortiGate API Client Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/FortiGate.rst Demonstrates initializing the FortiGate client with connection details, performing a POST request to create a firewall address object, and handling the response. Includes optional login and error logging. ```python import logging from pprint import pprint from fortigate_api import FortiGate logging.getLogger().setLevel(logging.DEBUG) HOST = "host" USERNAME = "username" PASSWORD = "password" # Initialize FortiGate with optional parameters scheme=`https`, port=443 fgt = FortiGate( host=HOST, username=USERNAME, password=PASSWORD, scheme="https", port=443, logging_error=True, ) fgt.login() # login is optional # FortiGate.post() - Create fortigate-object in the Fortigate data = { "name": "ADDRESS", "obj-type": "ip", "subnet": "127.0.0.100 255.255.255.252", "type": "ipmask", } response = fgt.post(url="api/v2/cmdb/firewall/address/", data=data) print(f"POST {response}", ) # POST ``` -------------------------------- ### Update and Get FortiGate Global Settings Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/cmdb/system/global_.rst Use this snippet to update specific global settings (e.g., timezone) and retrieve the current global configuration from the FortiGate. Ensure you have the FortiGateAPI library installed and provide valid host, username, and password credentials. ```python from pprint import pprint from fortigate_api import FortiGateAPI HOST = "host" USERNAME = "username" PASSWORD = "password" api = FortiGateAPI(host=HOST, username=USERNAME, password=PASSWORD) # Update data in the Fortigate data = {"timezone": 80} response = api.cmdb.system.global_.update(data) print(f"update {response}") # update # Get data from the Fortigate result = api.cmdb.system.global_.get() pprint(result) # [{"admin-concurrent": "enable", # "admin-console-timeout": 300, # "admin-hsts-max-age": 15552000, # "timezone": "80", # ... api.logout() ``` -------------------------------- ### Quickstart FortiGateAPI: Manage Firewall Addresses Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/index.rst Demonstrates creating, retrieving, filtering, updating, and deleting firewall addresses using the FortiGateAPI class. Ensure you have the necessary host, username, and password configured. The API connection is logged out at the end. ```python """Quickstart FortiGateAPI. - Create address in the Fortigate - Get all addresses from the Fortigate vdom root - Get address by name (unique identifier) - Filter address by operator contains `=@` - Update address data in the Fortigate - Delete address from the Fortigate """ from pprint import pprint from fortigate_api import FortiGateAPI HOST = "host" USERNAME = "username" PASSWORD = "password" api = FortiGateAPI(host=HOST, username=USERNAME, password=PASSWORD) # Create address in the Fortigate data = { "name": "ADDRESS", "obj-type": "ip", "subnet": "127.0.0.100 255.255.255.252", "type": "ipmask", } response = api.cmdb.firewall.address.create(data) print(f"address.create {response}") # address.create # Get all addresses from the Fortigate vdom root items = api.cmdb.firewall.address.get() print(f"All addresses count={len(items)}") # All addresses count=14 # Get address by name (unique identifier) items = api.cmdb.firewall.address.get(name="ADDRESS") print(f"addresses count={len(items)}") # addresses count=1 pprint(items) # [{"comment": "", # "name": "ADDRESS", # "subnet": "127.0.0.100 255.255.255.252", # "uuid": "a386e4b0-d6cb-51ec-1e28-01e0bc0de43c", # ... # }] # Filter address by operator contains `=@` items = api.cmdb.firewall.address.get(filter="subnet=@127.0") print(f"Filtered by `=@`, count={len(items)}") # Filtered by `=@`, count=2 # Update address data in the Fortigate data = {"name": "ADDRESS", "subnet": "127.0.0.255 255.255.255.255"} response = api.cmdb.firewall.address.update(data) print(f"address.update {response}") # address.update # Delete address from the Fortigate response = api.cmdb.firewall.address.delete("ADDRESS") print(f"address.delete {response}") # address.delete api.logout() ``` -------------------------------- ### Get Policies by Destination Address Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/cmdb/firewall/policy.rst Retrieves firewall policies that have a specific destination address. This involves first getting the address object and then iterating through policies to find matches. The count of matching policies is printed. ```python # Get all policies with destination address == `192.168.1.2/32` # Note, the efilter parameter does the same items = [] addresses = api.cmdb.firewall.address.get(filter="subnet==192.168.1.2 255.255.255.255") for item in api.cmdb.firewall.policy.get(): dstaddr = [d["name"] for d in item["dstaddr"]] for address in addresses: if address["name"] in dstaddr: items.append(item) print(f"policies count={len(items)}") # policies count=2 ``` -------------------------------- ### Get Address Groups Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/cmdb/firewall/addrgrp.rst Retrieves firewall address groups from the FortiGate. ```APIDOC ## GET /api/v2/cmdb/firewall/addrgrp ### Description Retrieves firewall address groups. Can fetch all groups or filter by specific criteria. ### Method GET ### Endpoint /api/v2/cmdb/firewall/addrgrp ### Parameters #### Query Parameters - **name** (string) - Optional - Filters address groups by their name. - **filter** (string or list of strings) - Optional - Filters address groups based on specified conditions. Can be a single condition or a list of conditions. ### Request Example (Get all) ``` GET /api/v2/cmdb/firewall/addrgrp ``` ### Request Example (Filter by name) ``` GET /api/v2/cmdb/firewall/addrgrp?name=ADDR_GROUP ``` ### Request Example (Filter by condition) ``` GET /api/v2/cmdb/firewall/addrgrp?filter=name=@MS ``` ### Request Example (Filter by multiple conditions) ``` GET /api/v2/cmdb/firewall/addrgrp?filter=["name=@MS","color==6"] ``` ### Response #### Success Response (200) - A list of address group objects, where each object contains details about an address group. #### Response Example ```json [ { "name": "ADDR_GROUP", "member": [{"name": "ADDRESS"}], "color": 6 } ] ``` ``` -------------------------------- ### Create Resource (POST) Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/FortiGate.rst Shows how to create a new resource on the FortiGate device using the `post` method. ```APIDOC ## Create Resource (POST) ### Description Use the `post` method to create a new resource on the FortiGate device. This involves specifying the API endpoint URL and providing the data for the new resource in a dictionary. ### Method `post(url: str, data: dict)` ### Endpoint `api/v2/cmdb/firewall/address/` ### Parameters #### Request Body - **data** (dict) - Required - The data for the new resource. ### Request Example ```python data = { "name": "ADDRESS", "obj-type": "ip", "subnet": "127.0.0.100 255.255.255.252", "type": "ipmask", } response = fgt.post(url="api/v2/cmdb/firewall/address/", data=data) print(f"POST {response}") ``` ### Response #### Success Response (200) Indicates the resource was created successfully. The response object contains details about the operation. ``` -------------------------------- ### Get External Resources Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/objects/ExternalResource.rst Retrieves external resources from Fortigate, with options for filtering. ```APIDOC ## get ### Description Retrieves external resources. Can fetch all resources or filtered results. ### Method GET ### Endpoint /api/v2/cmdb/external-resource/external-resource ### Parameters #### Query Parameters - **uid** (str) - Optional - The unique identifier of the external resource to retrieve. - **filter** (str or list) - Optional - Filters the results based on specified criteria. Can be a single filter string or a list of filter strings. - Example filter strings: "name==EXTERNAL_RESOURCE_NAME", "resource=@domain.com", "name!=EXTERNAL_RESOURCE_NAME" - Example list of filters: ["resource=@domain.com", "type==address"] ### Response #### Success Response (200) - **response** (list) - A list of external resource objects matching the criteria. ``` -------------------------------- ### Get External Resources Source: https://github.com/vladimirs-git/fortigate-api/blob/main/docs/fortigateapi/cmdb/system/external_resource.rst Retrieves a list of all external resources or a specific one by name. ```APIDOC ## Get External Resources ### Description Retrieves a list of all external resources or a specific one by name. ### Method GET ### Endpoint /api/v2/cmdb/system/external-resource ### Parameters #### Query Parameters - **name** (string) - Optional - The name of the external resource to filter by. ### Response #### Success Response (200) - **name** (string) - The name of the external resource. - **resource** (string) - The URL or path of the external resource. - **type** (string) - The type of the external resource. - **status** (string) - The status of the external resource. #### Response Example ```json [ { "name": "RESOURCE_1", "resource": "https://domain.com/resource.txt", "type": "address", "status": "enable" } ] ``` ```