-
Notifications
You must be signed in to change notification settings - Fork 0
/
opennms.py
executable file
·126 lines (100 loc) · 4.01 KB
/
opennms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python
'''
OpenNMS dynamic inventory
Query OpenNMS REST API to obtain nodes and categories
'''
import os
import sys
import argparse
import requests
import time
try:
import json
except ImportError:
import simplejson as json
class OPENNMSInventory(object):
def __init__(self):
self.transport = "http://"
self.opennms_ip = "server_ip"
self.opennms_port = "8980"
self.username = "user"
self.password = "password"
self.headers = {"Accept": "application/json"}
self.inventory = {}
self.read_cli_args()
# Called with `--list`.
if self.args.list:
self.inventory = self.get_discovered_devices()
# Called with `--host [hostname]`.
elif self.args.host:
# Not implemented, since we return _meta info `--list`.
self.inventory = self.empty_inventory()
# If no groups or vars are present, return an empty inventory.
else:
self.inventory = self.empty_inventory()
print json.dumps(self.inventory);
# Empty inventory for testing.
def empty_inventory(self):
return {'_meta': {'hostvars': {}}}
# Read the command line args passed to the script.
def read_cli_args(self):
parser = argparse.ArgumentParser()
parser.add_argument('--list', action = 'store_true')
parser.add_argument('--host', action = 'store')
self.args = parser.parse_args()
def genericGET(self, URL):
"""
Issue an HTTP GET base on the URL passed as an argument and example in cURL is:
$ curl -k https://<opennms_ip>/opennms/rest/nodes
"""
URL = "%s%s:%s%s" % (self.transport, self.opennms_ip, self.opennms_port, URL)
try:
r = requests.get(URL, headers=self.headers, auth=(self.username, self.password))
except requests.ConnectionError as e:
return (False, e)
return (r.status_code, r.json())
def get_discovered_devices(self):
""" Query OpenNMS server for all nodes.
For information on the response body, see the API documentation on:
http://wiki.opennms.org/wiki/ReST
"""
# dictionary for the complete result
result = { }
# dictionary for hostvars
hostvars = { }
# list for all available categories on OpenNMS
groups_list = [ ]
# dictionary to insert in result
groups = { }
# query OpenNMS for nodes
status, response = self.genericGET("/opennms/rest/nodes?limit=0")
for node in response['node']:
try:
hostvars[node['label']] = { }
facts = {'description': node["sysDescription"],
'location': node["sysLocation"],
'device_ip': "0.0.0.0"
}
# query OpenNMS for ipinterfaces
URL = "/opennms/rest/nodes/%s/ipinterfaces?limit=0" % (node["id"])
status, ipinterfaces = self.genericGET(URL)
for ipinterface in ipinterfaces['ipInterface']:
if ipinterface["snmpPrimary"] == "P":
facts.update({'device_ip': ipinterface["ipAddress"]})
hostvars[node["label"]].update(facts)
# add node to categories if set
for category in node['categories']:
if not category["name"] in groups_list:
groups_list.append(category["name"])
groups.update({ category["name"]: { 'hosts': [ ], 'vars': { } }})
groups[category["name"]]["hosts"].append(node["label"])
except KeyError:
pass
# at first set the groups (in our case categories) to the result
result = groups
# now insert the meta-data (host variables) for each host
result.update({ '_meta': { 'hostvars': hostvars }})
return result
if __name__ == '__main__':
# Get the inventory.
OPENNMSInventory()