· 6 years ago · Dec 20, 2019, 04:32 PM
1import pprint
2import re
3import requests
4from collections import defaultdict
5
6
7def poll_statseeker():
8 # set the url for looking up devices in the Statseeker API and it's query. sysServices_filter is set to 4 for
9 # firewalls only at this time
10 url = "https://statseeker.ei.rutgers.edu/api/v2.1/cdt_device"
11 querystring = {"fields": ['id', 'name', 'ipaddress', 'vendor', 'sysServices'], "limit": ['1000']}
12 payload = ""
13 headers = {
14 'Authorization': "Basic xxx=",
15 'cache-control': "no-cache",
16 }
17 response = requests.request("GET", url, data=payload, headers=headers, params=querystring, verify=False)
18
19 # use the following to debug
20 # pprint.pprint(response.text)
21
22 # convert GET request to json
23 myjson = (response.json())
24
25 # set cdt_device as json variable without extra dictionaries and lists
26 cdt_device = myjson['data']['objects'][0]['data']
27
28 # set the url for looking up fields in inventory table in the Statseeker API and it's query
29 url = "https://statseeker.ei.rutgers.edu/api/v2.1/cdt_inventory_entity/"
30 querystring = {"fields": ['serial', 'name', 'model', 'deviceid', 'softwareRev'],
31 "name_filter": ['IS("ent 1")'], "limit": ['1000']}
32 payload = ""
33 headers = {
34 'Authorization': "Basic ZXdiMjc6IVozM0RldmVyMjc=",
35 'cache-control': "no-cache",
36 }
37 response = requests.request("GET", url, data=payload, headers=headers, params=querystring, verify=False)
38
39 # convert GET request to json
40 myjson = (response.json())
41
42 # set cdt_inventory_entity as json variable without extra dictionaries and lists
43 cdt_inventory_entity = myjson['data']['objects'][0]['data']
44
45 # enable pprint to debug
46 # pprint.pprint(cdt_inventory_entity)
47
48 # strip the ID field from the variable as we do not need it and it always includes it
49 for item in cdt_inventory_entity:
50 del item['id']
51
52 # change the cdt_device ID field to deviceid for merging on the cdt_inventory device ID field
53 for item in cdt_device:
54 item['deviceid'] = item.pop('id')
55 return cdt_device, cdt_inventory_entity
56
57
58def query_snipeit(query, query_type):
59 url = "https://inventory.soc.rutgers.edu/api/v1/{}".format(query_type)
60 querystring = {"search": query}
61 headers = {
62 'Authorization': "Bearer xxx",
63 'cache-control': "no-cache",
64 'Content-Type': "application/json",
65 'Accept': "application/json",
66 }
67 response = requests.request("GET", url, headers=headers, params=querystring)
68 # convert response to json
69 myjson = (response.json())
70 return myjson
71
72
73def add_model(model, model_number, manufacturer_id):
74 url = "https://inventory.soc.rutgers.edu/api/v1/models"
75 headers = {
76 'Authorization': "Bearer xxx",
77 'cache-control': "no-cache",
78 }
79 payload = "{{\"name\":\"{}}\",\"model_number\":\"{}\",\"category_id\":2,\"manufacturer_id\":{}}}"\
80 .format(model, model_number, manufacturer_id)
81 response = requests.request("POST", url, data=payload, headers=headers)
82 # return whatever the model_id will be
83
84# function to create SnipeIT asset
85def add_asset(serial, model, name):
86 # search for model
87 query_snipeit(model, "models")
88 # json is returned. if json has a model ID in it, set the variable
89 try:
90 model_id = myjson['rows'][0]['id']
91 except:
92 # I should find the exact except message here. but if json has no model ID field, add the model
93 add_model(model, model_number, manufacturer_id)
94 url = "https://inventory.soc.rutgers.edu/api/v1/hardware"
95 headers = {
96 'Authorization': "Bearer xxx",
97 'cache-control': "no-cache",
98 'Content-Type': "application/json",
99 'Accept': "application/json",
100 }
101 payload = "{{\"asset_tag\":\"{}\",\"status_id\":1,\"serial\":{},\"model_id\":{},\"name\":\"{}\"}}".format(serial, serial,
102 model_id, name)
103 response = requests.request("POST", url, data=payload, headers=headers)
104
105
106def update_asset(software, vendor, snipeid):
107 url = "https://inventory.soc.rutgers.edu/api/v1/hardware/{}".format(snipeid)
108 if vendor == "Cisco":
109 payload = "{{\"_snipeit_asa_version_3\" : \"{}\"}}".format(software)
110 elif vendor == "Palo Alto Networks":
111 payload = "{{\"_snipeit_pan_os_version_15\" : \"{}\"}}".format(software)
112 else:
113 print("nothing updated")
114 headers = {
115 'Authorization': "Bearer xxx",
116 'cache-control': "no-cache",
117 'Content-Type': "application/json",
118 'Accept': "application/json",
119 }
120 response = requests.request("PATCH", url, data=payload, headers=headers)
121
122
123
124# poll StatSeeker for cdt_device and cdt_inventory_entity tables
125cdt_device, cdt_inventory_entity = poll_statseeker()
126
127# create a dictionary and merge the two lists of dictionaries from StatSeeker
128result = defaultdict(dict)
129for sequence in (cdt_inventory_entity, cdt_device):
130 for dictionary in sequence:
131 result[dictionary['deviceid']].update(dictionary)
132for dictionary in result.values():
133 dictionary.pop('deviceid')
134# enable pprint to debug
135# pprint.pprint(result)
136
137# set variables for each item in the merged dictionary
138for key, value in result.items():
139 ipaddress = value.get('ipaddress')
140 statseeker_model = value.get('model')
141 if statseeker_model.startswith('ASA'):
142 model = re.sub('ASA', 'ASA-', statseeker_model)
143 elif statseeker_model.startswith('PA'):
144 model = statseeker_model
145 else:
146 model = None
147 name = value.get('name')
148 serial = value.get('serial')
149 software = value.get('softwareRev')
150 if value.get('vendor') == "ciscoSystems":
151 vendor = "Cisco"
152 manufacturer_id = 1
153 elif value.get('vendor') == "PALO ALTO NETWORKS":
154 vendor = "Palo Alto Networks"
155 manufacturer_id = 2
156 else:
157 vendor = None
158 manufacturer_id = None
159 model_number = re.sub('[ASP-]', '', statseeker_model)
160
161
162 # if no serial is found, print no serial. Otherwise, check SnipeIT for the serial.
163 if not serial:
164 print("no serial")
165 else:
166 # check inventory site for serial numbers
167 myjson = query_snipeit(serial, "hardware")
168 # try to set snipeid from query_snipeit
169 try:
170 snipeid = myjson['rows'][0].get('id')
171 # if ID does not exist in snipe, add asset
172 except (IndexError, KeyError):
173 snipeid = 'NULL'
174 print(name, "is bad")
175 add_asset(serial, model, name)
176 if snipeid != "NULL" and software != "NULL":
177 update_asset(software, vendor, snipeid)