Automation guides, explanations and reader checklists on whilenetworking.com

Python Automation: Building a Custom API Client to Push Configuration Changes to Juniper Devices via REST

Network engineers often find themselves toggling between SSH sessions for CLI configuration and HTTP clients for RESTful management. While Juniper Networks…

Network engineers often find themselves toggling between SSH sessions for CLI configuration and HTTP clients for RESTful management. While Juniper Networks devices support both, integrating Python libraries like requests and paramiko allows for robust, scriptable workflows that go beyond simple file transfers. This guide details how to build a secure, custom API client in Python to push configuration changes directly to Juniper EX Series or SRX Series devices using the REST API. By automating this process, you can eliminate manual copy-paste errors, ensure consistent change management, and integrate device updates into broader orchestration tools like Ansible or scheduled cron jobs.

Understanding the Architecture and Prerequisites

Before writing code, it is essential to understand how Juniper’s REST interface operates. Unlike traditional CLI pushes where a user enters commands line-by-line, the REST API expects JSON payloads that define the desired state of the device. The device then calculates the delta between the current configuration and the requested payload to apply changes atomically.

To proceed with this automation, you must have:
* Python 3.8 or higher installed on your workstation.
* The requests library (pip install requests) to handle HTTP communications.
* A valid SSH key pair generated for the device user (e.g., admin).
* Network connectivity from your client machine to the Juniper device’s management interface (typically port 8083 for REST).
* Access to the device configuration via a read-only or commit-authorized account.

Step 1: Establishing a Secure Session with SSH Keys

Direct HTTP calls often fail on modern Juniper devices without prior authentication setup because they require an established SSL session. The standard approach is to authenticate via SSH first to establish a trust relationship, then use that session for subsequent REST calls.

Begin by generating an SSH key pair if you do not already have one:

ssh-keygen -t ed25519 -f juniper_api_key

Next, copy the public key to the device using the copy command via a temporary SSH session, or upload it manually through the console. On the Juniper device, ensure the key is authorized for the specific user (often admin):

configure
set system authentication-authorization-profile admin ssh-keys juniper_api_key /path/to/key.pub
commit
exit

Note: Replace /path/to/key.pub with the actual path to your public key file.

Once the key is authorized, your Python script can use paramiko or a library wrapper like netmiko (which simplifies SSH handling) to log in. If using raw requests, you must handle the initial handshake carefully. A common pattern involves sending an HTTP POST request with a Content-Type: application/json header containing a JSON object that includes the username and the public key, or simply relying on the SSL session established via the junos-evo library concepts adapted for standard REST calls.

For this example, we assume a simplified scenario where the device accepts standard bearer token authentication after an initial SSH handshake, or we are using the Junos OS REST API which supports direct POST requests with credentials in specific headers.

Step 2: Constructing the Configuration Payload

The core of the automation lies in constructing the JSON payload that represents the desired configuration state. Juniper’s REST API for configuration updates typically targets the /api/ops/config endpoint. The payload must be a valid hierarchical representation of the Junos configuration hierarchy.

Consider a scenario where you need to disable OSPF on interface ge-0/0/0. The JSON structure mirrors the CLI hierarchy but uses snake_case keys and boolean values for toggles.

import requests
import json

# Define the target device details
DEVICE_URL = "https://192.168.1.10"
USERNAME = "admin"
PASSWORD = "YourSecurePasswordHere" # In production, use environment variables or a secrets manager
INTERFACE = "ge-0/0/0"
PROTOCOL = "ospf"

# Construct the JSON payload for the configuration update
payload = {
    "commit": True,
    "operations": [
        {
            "path": f"/interfaces/{INTERFACE}/unit/0/families/ospf",
            "command": "delete",
            "arguments": {}
        }
    ]
}

# Prepare headers for the request
headers = {
    "Content-Type": "application/json",
    "Accept": "application/json"
}

In this example, the operations array defines a single action: deleting the OSPF family under the specified interface. You can extend the operations list to include multiple changes, such as adding a new route or modifying a firewall filter, all within a single atomic commit transaction.

Step 3: Executing the Push and Verifying Results

With the session established and the payload constructed, the script executes the HTTP POST request to trigger the configuration change. This step includes handling the response code and verifying that the commit was successful.

response = requests.post(
    f"{DEVICE_URL}/api/ops/config",
    json=payload,
    headers=headers,
    verify=True # Set to False only for lab environments with self-signed certs
)

if response.status_code == 200:
    print("Configuration pushed successfully.")
    print(response.json())
elif response.status_code == 401:
    print("Authentication failed. Check credentials or SSH key authorization.")
else:
    print(f"Error occurred. Status code: {response.status_code}")
    print(response.text)

Expected Output:
Upon success, the device returns a JSON object confirming the commit status and often includes a transaction ID that can be used for rollback if necessary.

{
  "result": {
    "status": "OK",
    "message": "Configuration changes applied successfully"
  }
}

Verification and Common Pitfalls

After pushing the configuration, it is critical to verify the change on the device itself. The script can include a final step that queries the /api/ops/config endpoint with commit-check: false or simply retrieves the running configuration via SSH to confirm the state matches expectations.

Common Errors and Fixes:
1. Authentication Timeout: If the REST API call fails immediately, ensure the SSL session was established. Juniper devices may require a specific timeout interval for idle sessions. Add timeout=30 to your requests.post call.
2. Invalid JSON Path: The path in the payload must exactly match the hierarchy. A typo like ge-0/0/0 vs ge-0/0/1 will result in a 404 error. Use Python string formatting carefully to avoid off-by-one errors in interface numbering.
3. Missing Permissions: If you receive a 403 Forbidden error, the user account lacks commit privileges. Ensure the user is part of the users-admins group or has explicit commit rights configured in the system authentication profile.

Industry Application and Student Practice

For industry practitioners, this script serves as a foundational building block for an Ansible playbook. You can wrap this Python logic into an Ansible module to manage fleets of Juniper routers, ensuring that every device in a data center cluster receives the same security baseline updates automatically during maintenance windows.

For students, the practice task is to set up a local lab using EVE-NG or GNS3 with a supported Juniper image. Create a script that:
1. Connects to a virtual EX switch.
2. Pushes a configuration change (e.g., setting a hostname).
3. Waits for the commit to complete.
4. Queries the device to confirm the hostname change.

This exercise reinforces understanding of state management, error handling, and the difference between synchronous CLI operations and asynchronous REST workflows. Remember that in real-world scenarios, you must integrate logging mechanisms (like sending results to Splunk or a central SIEM) and implement retry logic for transient network failures to ensure high availability of your automation tools.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.