PDF

REST API Use Cases

Use NetCrunch REST API to automate repeatable administration tasks, including maintenance mode, node import, custom field updates, and monitoring provider assignment.

NetCrunch REST API is best suited for deterministic automation: scripts, scheduled jobs, integrations, and repeatable operational procedures.

Typical REST API use cases include:

  • importing nodes from CSV or an external inventory system
  • synchronizing NetCrunch with a CMDB, IPAM, or asset database
  • updating node custom fields
  • assigning monitoring providers
  • enabling or disabling monitoring during maintenance
  • retrieving node, alert, view, or policy data
  • integrating NetCrunch with internal tools and portals

REST API is the right choice when the workflow is known in advance and should behave the same way every time.

For AI-assisted workflows, adaptive investigation, or autonomous agents, see the separate MCP and Agent Use Cases chapter.

REST API and MCP Server use the same API key mechanism, user permissions, read-only mode, connection restrictions, audit logging, and rate limiting. This chapter focuses on direct REST API scripting.

Before You Start

Before running any script, create an API key in NetCrunch.

See Getting Started for the API key creation process.

Recommended API key settings for scripts:

  • use a dedicated NetCrunch user account
  • use read-only mode unless the script must change NetCrunch configuration
  • set an expiration date
  • restrict the key by source IP address when possible
  • use a separate API key per script or integration
  • use the x-api-key header instead of passing the key in the URL
  • review NetCrunch event logs after deployment

Treat API keys as passwords. Do not commit API keys to source control or store them in shared script folders.

Maintenance-mode Script

This Python script puts a node into the monitoring disabled state and sets the given message in the Info1 field.

This can be used to avoid false-positive alerts on nodes under maintenance and inform other users that the disabled state is intentional.

Typical use cases:

  • planned server restart
  • switch replacement
  • operating system patching
  • hardware maintenance
  • temporary application shutdown
  • suppressing alerts during a known outage window

Pre-requisites

  • Python 3
  • argparse library
  • requests library

Install dependencies:

pip install argparse requests

Usage

python maintenance-mode.py 192.168.0.50 disable -msg Maintenance

To re-enable monitoring:

python maintenance-mode.py 192.168.0.50 enable

Setup

  1. Add an application in NetCrunch. See Getting Started to learn how to add an application and generate an API key

  2. Update these two lines in the script:

    • nc_address = "NetCrunch Address"
    • nc_api_key = "Application API Key"
  3. Required arguments:

    • node: node ID, IP address, or DNS name
    • action: enable or disable
  4. Optional argument:

    • -msg: message to set in the Info1 field

If the -msg argument is omitted, the Info1 field is cleared.

Using node ID is the most stable option for automation. Names and addresses can change.

Script file

maintenance-mode.py

import requests import argparse

nc_address = "NetCrunch Address" nc_api_key = "Application API-Key"

def send_request(url, request): headers = { "content-type": "application/json", "x-api-key": nc_api_key }

if (request == "delete"):
    r = requests.delete(url, headers=headers)
    print("Status Code:", r.status_code, ", NetCrunch response:", r.text)
    return r

elif (request == "put"):
    r = requests.put(url, headers=headers)
    print("Status Code:", r.status_code, ", NetCrunch response:", r.text)
    return r

parser = argparse.ArgumentParser() parser.add_argument("node", help="Node to change monitoring state, identified by ID, IP address, or DNS name") parser.add_argument("action", help="Monitoring state: enable or disable") parser.add_argument("-msg", nargs="?", help="Optional: set message in Info1 field. Omit to clear Info1 field") args = parser.parse_args()

if (args.action == "enable"): action = "on" else: action = "off"

url = "http://" + nc_address + "/api/rest/2/nodes/" + args.node + "/monitoring/" + action print("Changing monitoring state:") send_request(url, "put")

if (args.msg != None): url = "http://" + nc_address + "/api/rest/2/nodes/" + args.node + "/custom-fields/Info%201?value=" + args.msg print("Adding Info1 field:") send_request(url, "put") else: url = "http://" + nc_address + "/api/rest/2/nodes/" + args.node + "/custom-fields/Info%201" print("Removing data from Info1 field:") send_request(url, "delete")

Notes

This script uses the x-api-key header. This is preferred over passing the API key in the URL.

The API key must not be read-only because the script changes node monitoring state and updates a custom field.

Recommended Improvements

For production use, consider extending the script with:

  • HTTPS instead of HTTP
  • validation of the enable or disable argument
  • URL encoding for the message value
  • timeout handling
  • retry logic for temporary connection errors
  • environment variables for API key storage
  • logging to a file
  • automatic re-enable time if used in maintenance workflows

Import Nodes from CSV File

This JavaScript script adds nodes to NetCrunch from a CSV file.

Additionally, this use case adds extra data to two custom fields for each node:

  • Location
  • Info 2

The use case includes two files:

  • script file: add-nodes.js
  • data file: data.csv

This pattern is useful when importing nodes from:

  • external inventory systems
  • CMDB exports
  • asset management databases
  • IPAM tools
  • manually prepared spreadsheets
  • provisioning systems

Pre-requisites

  • Node.js

Usage

node add-nodes.js

Setup

  1. Add an application in NetCrunch. See Getting Started to learn how to add an application and generate an API key

  2. Update these entries in the script:

    • hostname: "NetCrunch address or DNS name"
    • "x-api-key": "application api key"
  3. The script requires no additional parameters. It reads data from data.csv and sends it to NetCrunch

Additional Information

The script can be modified to include more custom fields. Add more else if statements with the required field name.

Make sure that the custom field is defined in NetCrunch before executing the script.

For additional fields like Display Name, add the parameter name in the first row of the CSV file and add values in the rows.

See Node Property List for available parameters.

This is a minimal CSV example. If field values can contain commas, quotes, or line breaks, use a proper CSV parser instead of splitting lines by comma.

Script files

add-nodes.js

const http = require("http"), fs = require("fs"), readline = require("readline"), nodesFile = (__dirname + "/data.csv"), options = { method: "POST", hostname: "IP or Name of NC server", path: "/api/rest/2/nodes", headers: { "Content-Type": "application/json", "x-api-key": "api-key" } };

function sendRequest(payload) { const req = http.request(options, res => { res.setEncoding("utf8");

    if (res.statusCode != 200) {
        console.log("Error: Status code: " + res.statusCode + " Message: " + res.statusMessage);
    } else {
        res.on("data", chunk => {
            let response = JSON.parse(chunk);

            if (response.info === "Already monitored") {
                console.log("Warning: ID: " + response.id + " Node is already monitored");
            } else {
                console.log("OK: ID:" + response.id + " Node is added");
            }
        });
    }
});

req.write(JSON.stringify(payload));
req.end();

}

function addNodesFromFile(fileName) { console.log("Reading file and adding nodes...");

const rl = readline.createInterface({
    input: fs.createReadStream(fileName),
    crlfDelay: Infinity
});

let header;

rl.on("line", line => {
    if (header == null) {
        header = line.split(",");
    } else {
        const
            properties = line.split(","),
            data = {
                customFields: {}
            };

        header.forEach((name, ix) => {
            if ((properties[ix] || "") !== "") {
                if (name === "Location") {
                    data.customFields.Location = properties[ix];
                } else if (name === "Info 2") {
                    data.customFields["Info 2"] = properties[ix];
                } else {
                    data[name] = properties[ix];
                }
            }
        });

        sendRequest(data);
    }
});

}

addNodesFromFile(nodesFile);

Data file

data.csv

name,networkAddress,osMonitorType,Location,Info 2
vm-test-0066.ac.acme,10.20.16.66,Windows,Server-Rack-1,VM-For-Testing
vm-test-0084.ac.acme,10.20.16.84,Windows,Server-Rack-2,VM-For-Testing
cam-0015.ac.acme,10.20.16.15,none,Server-Room,Camera
cam-0057.ac.acme,10.20.16.57,none,Office,Camera

How It Works

The script:

  1. Opens data.csv
  2. Reads the first row as the header
  3. Uses every following row as node data
  4. Creates a JSON payload for each node
  5. Sends a POST request to:
/api/rest/2/nodes
  1. Adds selected fields into customFields
  2. Prints whether each node was added or was already monitored

Recommended Improvements

For production use, consider adding:

  • HTTPS support
  • API key from environment variable
  • proper CSV parser
  • request timeout
  • retry handling
  • failed-row log
  • duplicate detection before sending
  • dry-run mode
  • rate limit handling

Import Nodes from CSV File and Set Monitoring Provider

This is a modified version of the Import Nodes from CSV File script.

It allows you to add multiple nodes monitored by a remote probe.

The use case includes two files:

  • script file: add-nodes.js
  • data file: data.csv

This is useful when adding nodes for:

  • branch offices
  • remote sites
  • isolated networks
  • customer networks
  • networks monitored by dedicated probes
  • segmented address spaces

Pre-requisites

  • Node.js

Usage

node add-nodes.js

Setup

  1. Add an application in NetCrunch. See Getting Started to learn how to add an application and generate an API key

  2. Update these entries in the script:

    • hostname: "NetCrunch address or DNS name"
    • "x-api-key": "application api key"
  3. The remote probe node must be added before executing this script. Otherwise, added nodes may be assigned to the Master Server

  4. The script requires no additional parameters. It reads data from data.csv and sends it to NetCrunch

The monitoring provider value must match an existing NetCrunch monitoring provider. Add and verify the remote probe before running the import.

Script files

add-nodes.js

const http = require("http"), fs = require("fs"), readline = require("readline"), nodesFile = (__dirname + "/data.csv"), options = { method: "POST", hostname: "IP Address or DNS name of NC Server", path: "/api/rest/2/nodes", headers: { "Content-Type": "application/json", "x-api-key": "apikey" } };

function sendRequest(payload) { const req = http.request(options, res => { res.setEncoding("utf8");

    if (res.statusCode != 200) {
        console.log("Error: Status code: " + res.statusCode + " Message: " + res.statusMessage);
    } else {
        res.on("data", chunk => {
            let response = JSON.parse(chunk);

            if (response.info === "Already monitored") {
                console.log("Warning: ID: " + response.payload.id + " Node is already monitored");
            } else {
                console.log("OK: ID:" + response.payload.id + " Node is added");
            }
        });
    }
});

req.write(JSON.stringify(payload));
req.end();

}

function addNodesFromFile(fileName) { console.log("Reading file and adding nodes...");

const rl = readline.createInterface({
    input: fs.createReadStream(fileName),
    crlfDelay: Infinity
});

let header;

rl.on("line", line => {
    if (header == null) {
        header = line.split(",");
    } else {
        const
            properties = line.split(","),
            data = {
                name: null,
                monitoringProvider: null
            };

        header.forEach((name, ix) => {
            if ((properties[ix] || "") !== "") {
                if (name === "monitoringProvider") {
                    data.monitoringProvider = properties[ix];
                } else {
                    data.name = properties[ix];
                }
            }
        });

        sendRequest(data);
    }
});

}

addNodesFromFile(nodesFile);

Data file

data.csv

name,monitoringProvider
vm-test-0066.ac.acme,remoteProbe1
vm-test-0084.ac.acme,remoteProbe1
cam-0015.ac.acme,remoteProbe1
cam-0057.ac.acme,remoteProbe1

How It Works

The script:

  1. Opens data.csv
  2. Reads the first row as the header
  3. Creates a node payload for each row
  4. Sets the monitoringProvider property
  5. Sends a POST request to:
/api/rest/2/nodes
  1. Prints whether each node was added or already monitored

When to Use This Pattern

Use this pattern when nodes should immediately be assigned to a specific monitoring provider.

Examples:

  • all devices in a branch office should be monitored by the branch probe
  • all cameras in a building should be monitored by a local probe
  • devices in an isolated network are reachable only from a remote probe
  • overlapping private IP ranges require separation by site or address space

Inventory System Integration

A common REST API use case is synchronizing NetCrunch with an external inventory system.

External systems may include:

  • CMDB
  • IPAM
  • asset inventory
  • virtualization inventory
  • cloud inventory
  • provisioning database
  • internal configuration portal

A synchronization script can:

  • add missing nodes
  • update node names
  • update network addresses
  • update custom fields
  • assign device metadata
  • set location or owner information
  • assign monitoring provider
  • disable monitoring for retired assets
  • report mismatches between NetCrunch and the source inventory

Recommended synchronization pattern:

  1. Read source inventory
  2. Normalize source data
  3. Query NetCrunch for existing nodes
  4. Match records by stable identifier
  5. Prepare a list of changes
  6. Run in dry-run mode first
  7. Apply changes through REST API
  8. Log every changed object
  9. Report skipped or failed records

Do not blindly overwrite NetCrunch data from an external inventory system unless that system is authoritative for the given field.

Script Design Guidelines

Use deterministic scripts when the workflow is known.

Good candidates for scripts:

  • nightly inventory synchronization
  • bulk node import
  • custom field update
  • maintenance mode
  • scheduled report extraction
  • repeated configuration cleanup
  • one-time migration task

Poor candidates for scripts:

  • tasks requiring investigation
  • ambiguous remediation decisions
  • comparing many possible causes
  • workflows where the next step depends on interpretation
  • workflows requiring operator conversation

For those cases, MCP and AI-assisted agents may be more appropriate.

Handling Rate Limits

NetCrunch applies rate limiting to REST API requests.

Default limit:

100 requests per 60 seconds

The same limit also applies to MCP Server calls.

Rate limiting protects:

  • NetCrunch Server responsiveness
  • monitoring performance
  • API availability for other integrations
  • event and configuration database access
  • system stability

If a REST script reaches the limit, improve the script before changing the server configuration.

Recommended improvements:

  • avoid repeated calls for the same object
  • cache already retrieved data
  • filter requests by view or group
  • batch operations when possible
  • add delay between requests
  • process large imports in chunks
  • avoid full-Atlas scans unless necessary

The limit can be changed in:

server.cfg.yml

Changing the default value is not recommended.

Troubleshooting REST API Scripts

Authentication Fails

Check:

  • API key is correct
  • API key has not expired
  • API key is passed in the x-api-key header
  • API key is tied to an active NetCrunch user
  • connection restriction allows the script host
  • request is sent to the correct NetCrunch Server

Access Is Denied

Check:

  • the linked user can access the target object
  • the linked user has rights to perform the requested operation
  • the API key is not read-only for write operations
  • the target object belongs to an accessible view or organization

Node Is Not Added

Check:

  • required node fields are present
  • network address or name is valid
  • node is not already monitored
  • monitoring provider exists
  • device type or OS monitor type value is correct
  • request body is valid JSON

CSV Import Fails

Check:

  • CSV header names match expected API property names
  • custom fields already exist in NetCrunch
  • values do not contain unescaped commas
  • empty values are handled correctly
  • file encoding is valid
  • each row has the expected number of columns

Script Reaches Rate Limit

Check:

  • script is not looping unexpectedly
  • requests are not repeated for the same node
  • bulk import size is reasonable
  • retries do not happen too aggressively
  • delay or batching is used

Best Practices

Use REST API for known procedures
Scripts are ideal when the workflow is predictable and repeatable.
Use dedicated API users
Avoid using personal administrator accounts for automation.
Use separate API keys
Create one key per script, application, or integration.
Use read-only keys when possible
Write access should be limited to scripts that actually modify NetCrunch.
Prefer IDs for automation
Names and addresses can change. IDs are more stable.
Prefer HTTPS
Use HTTPS when sending API keys over the network.
Use the x-api-key header
Avoid passing keys in URLs.
Add dry-run mode
For bulk updates, show planned changes before applying them.
Log changes
Keep script logs for imports, updates, and failed operations.
Handle failures explicitly
Do not ignore non-200 responses.
Respect rate limits
Avoid unnecessary polling and repeated full scans.
Validate source data
Do not import malformed or incomplete inventory records.
Review event logs
NetCrunch logs API usage with application name, user, and source IP.

Related Topics

See also:

api automationapi keyapi use casescmdbcsv importcustom fieldsinventory integrationipammaintenance modemonitoring providernetcrunchnode managementrate limitingrest apiscripts