Capture status and toggle script

In network monitoring and management, the IOTA Capture Status and Toggle Script emerges as a powerful tool for network administrators. This Python script is designed to interact with IOTA devices through their REST API, providing a quick and efficient way to assess the status of multiple network interfaces, their readiness for packet capture, and the ability to toggle capture states for specific interfaces.

The script offers two primary functions:

  1. Interface Status Overview: Retrieves and displays the status of all network interfaces on an IOTA device. For each interface, it shows:
    • The interface name and its unique Pretty MAC address
    • Whether a capture can be started on this interface
    • The current physical state of the interface
    • Whether packet capture is currently enabled
  2. Capture State Toggle: Allows toggling the capture state of a specific interface identified by its Pretty MAC address.

The script considers an interface ready for capture when its physical state is 'idle' and packet capture is not currently enabled.

Let's break down the key components of the script:

  1. API Communication: The call_api function handles all API requests, supporting both GET and POST methods. It uses basic authentication and returns the 'data' part of the response if successful.
  2. Interface Information Retrieval: The get_interfaces and get_interface_status functions use the call_api function to fetch information about all interfaces or a specific interface, respectively.
  3. Capture Toggle: The toggle_capture function sends a POST request to toggle the capture state of a specified interface.
  4. Capture Readiness Check: The can_start_capture function determines if an interface is ready for capture based on its current status.
  5. Status Display: The print_interface_capture_status function iterates through all interfaces, retrieves their status, and prints the relevant information.
  6. Main Execution: The main function now supports two modes of operation:
    • Without a Pretty MAC: Lists all interfaces and their capture status.
    • With a Pretty MAC: Checks the status of the specified interface and toggles its capture state.

The script uses basic authentication for API requests. However, it currently disables SSL certificate verification, which should be addressed in security-sensitive environments.

The script now supports two usage modes:

  • To list all interfaces and their capture status:
python script.py <ip-address>
  • To toggle the capture state of a specific interface:
python script.py <ip-address> <pretty-mac>

Here's the complete IOTA Capture Status and Toggle Script:

capture_status_and_toggle.py
import sys
import requests
from requests.auth import HTTPBasicAuth
import json
 
# Global variables for authentication
USERNAME = "apitest"
PASSWORD = "apitest"
 
def call_api(url, method='GET', data=None):
    try:
        if method == 'GET':
            response = requests.get(
                url,
                auth=HTTPBasicAuth(USERNAME, PASSWORD),
                verify=False  # Note: This disables SSL certificate verification. Use with caution.
            )
        elif method == 'POST':
            response = requests.post(
                url,
                auth=HTTPBasicAuth(USERNAME, PASSWORD),
                json=data,
                verify=False  # Note: This disables SSL certificate verification. Use with caution.
            )
        response.raise_for_status()
        json_response = response.json()
 
        if isinstance(json_response, dict) and json_response.get('message') == 'Success':
            return json_response.get('data')
        else:
            print(f"API call failed: {json_response.get('message', 'Unknown error')}")
            return None
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")
        return None
 
def get_interfaces(ip_address):
    url = f"https://{ip_address}/api/datasources/proxy/2/interfaces"
    return call_api(url)
 
def get_interface_status(ip_address, pretty_mac):
    url = f"https://{ip_address}/api/datasources/proxy/2/interfaces/{pretty_mac}"
    return call_api(url)
 
def toggle_capture(ip_address, pretty_mac):
    url = f"https://{ip_address}/api/datasources/proxy/2/interfaces/{pretty_mac}/capture/toggle"
    return call_api(url, method='POST')
 
def can_start_capture(interface_status):
    return (
        interface_status['physical_state']['state'] == 'idle' and
        not interface_status['capture_enabled']
    )
 
def print_interface_capture_status(ip_address, interfaces):
    if interfaces:
        print("Interface Capture Status:")
        for interface in interfaces:
            pretty_mac = interface['pretty_mac']
            name = interface['interface']['name']
 
            status = get_interface_status(ip_address, pretty_mac)
            if status:
                capture_status = can_start_capture(status)
                print(f"Interface: {name} (Pretty MAC: {pretty_mac})")
                print(f"  Can start capture: {'Yes' if capture_status else 'No'}")
                print(f"  Current state: {status['physical_state']['state']}")
                print(f"  Capture enabled: {status['capture_enabled']}")
                print()
            else:
                print(f"Interface: {name} (Pretty MAC: {pretty_mac})")
                print("  Unable to retrieve status")
                print()
    else:
        print("No interfaces found or unable to retrieve interface information.")
 
def main():
    if len(sys.argv) < 2 or len(sys.argv) > 3:
        print("Usage: python script.py <ip-address> [pretty-mac]")
        sys.exit(1)
 
    ip_address = sys.argv[1]
    pretty_mac = sys.argv[2] if len(sys.argv) == 3 else None
 
    if pretty_mac:
        # Check status of specific interface and toggle capture
        status = get_interface_status(ip_address, pretty_mac)
        if status:
            print(f"Current status for interface {pretty_mac}:")
            print(f"  State: {status['physical_state']['state']}")
            print(f"  Capture enabled: {status['capture_enabled']}")
 
            print("\nToggling capture state...")
            toggle_result = toggle_capture(ip_address, pretty_mac)
            if toggle_result is not None:
                print("Capture state toggled successfully.")
                print("New status:")
                print(f"  Capture enabled: {toggle_result['capture_enabled']}")
            else:
                print("Failed to toggle capture state.")
        else:
            print(f"Failed to retrieve status for interface {pretty_mac}")
    else:
        # List all interfaces and their capture status
        interfaces = get_interfaces(ip_address)
        if interfaces:
            print_interface_capture_status(ip_address, interfaces)
        else:
            print("Failed to retrieve interface information.")
 
if __name__ == "__main__":
    main()

This enhanced script provides network administrators with a versatile tool for managing IOTA device interfaces. It not only automates the process of checking interface status and capture readiness, but also allows for quick toggling of capture states on specific interfaces. This functionality saves time, reduces the potential for human error in network monitoring setups, and provides more granular control over individual interfaces.

  • Last modified: September 13, 2024