JosefJezek
1/13/2014 - 12:48 PM

Zenoss JSON API Shell / Bash script

Zenoss JSON API Shell / Bash script

#!/bin/sh

# Zenoss JSON API Shell / Bash script
# Link: https://gist.github.com/8399651

# Resources
#   http://wiki.zenoss.org/Working_with_the_JSON_API
#   https://gist.github.com/cluther/1901884
#   http://blog.remibergsma.com/2013/04/26/automatically-adding-and-editing-devices-in-zenoss-core-4-using-the-api

# Get the zenoss_api function by sourcing zenoss_json_api.sh.
#   source zenoss_json_api.sh

# Your Zenoss server settings.
ZENOSS_URL="http://localhost:8080"
ZENOSS_USERNAME="admin" # Role ZenManager
ZENOSS_PASSWORD="zenoss"

# Generic call to make Zenoss JSON API calls easier on the shell.
#
# Example usage: Call the getGraphDefs method.
#   zenoss_api device_router DeviceRouter getGraphDefs '{"uid":"/zport/dmd/Devices/Server/Linux/devices/zenosstrain6.zenoss.com","drange":129600}'
zenoss_api () {
    ROUTER_ENDPOINT=$1
    ROUTER_ACTION=$2
    ROUTER_METHOD=$3
    DATA=$4

    if [ -z "${DATA}" ]; then
        echo "Usage: zenoss_api <endpoint> <action> <method> <data>"
        return 1
    fi

    curl \
        -u "$ZENOSS_USERNAME:$ZENOSS_PASSWORD" \
        -X POST \
        -H "Content-Type: application/json" \
        -d "{\"action\":\"$ROUTER_ACTION\",\"method\":\"$ROUTER_METHOD\",\"data\":[$DATA], \"tid\":1}" \
        "$ZENOSS_URL/zport/dmd/$ROUTER_ENDPOINT" \
        >/dev/null 2>&1
}

# Helper call to send an event.
#
# Example usage:
#   zenoss_send_event device1 component1 Critical key1 test
zenoss_send_event() {
    DEVICE=$1
    COMPONENT=$2
    EVENT_CLASS_KEY=$3 # Of EventClass Mapping
    SEVERITY=$4 # Critical, Error, Warning, Info, Debug, or Clear
    SUMMARY=$5

    if [ -z "$SUMMARY" ]; then
        echo "Usage: zenoss_send_event <device> <component> <severity> <eventClassKey> <summary>"
        return 1
    fi

    zenoss_api evconsole_router EventsRouter add_event \
        "{\"device\":\"$DEVICE\",\"summary\":\"$SUMMARY\",\"component\":\"$COMPONENT\",\"severity\":\"$SEVERITY\",\"evclasskey\":\"$EVENT_CLASS_KEY\"}"
}

# Helper call for adding standard device types.
zenoss_add_device() {
    DEVICE_HOSTNAME=$1
    DEVICE_CLASS=$2

    if [ -z "$DEVICE_CLASS" ]; then
        echo "Usage: zenoss_add_device <host> <device class>"
        return 1
    fi

    zenoss_api device_router DeviceRouter addDevice "{\"deviceName\":\"$DEVICE_HOSTNAME\",\"deviceClass\":\"$DEVICE_CLASS\",\"collector\":\"localhost\",\"model\":true,\"title\":\"\",\"productionState\":\"1000\",\"priority\":\"3\",\"snmpCommunity\":\"\",\"snmpPort\":161,\"tag\":\"\",\"rackSlot\":\"\",\"serialNumber\":\"\",\"hwManufacturer\":\"\",\"hwProductName\":\"\",\"osManufacturer\":\"\",\"osProductName\":\"\",\"comments\":\"\"}"
}