|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import json |
| 4 | + |
| 5 | +from cbapi.response.models import Sensor |
| 6 | + |
| 7 | +from cbapi.example_helpers import build_cli_parser, get_cb_response_object |
| 8 | +from cbapi.errors import ServerError |
| 9 | + |
| 10 | +import logging |
| 11 | + |
| 12 | +class InventoryProcessor(): |
| 13 | + |
| 14 | + def __init__(self,cbapi): |
| 15 | + self.cb = cbapi |
| 16 | + |
| 17 | + def sensor_lookup(self,line): |
| 18 | + sensor = None |
| 19 | + line_json = json.loads(line) |
| 20 | + if "sensor_id" in line_json: |
| 21 | + sensor = self.cb.select(Sensor,line_json['sensor_id']) |
| 22 | + elif 'ip' in line_json: |
| 23 | + sensor = self.cb.select(Sensor).where("ip:"+line_json['ip']).first() |
| 24 | + elif 'host' in line_json: |
| 25 | + sensor = self.cb.select(Sensor).where("hostname:"+line_json['host']).first() |
| 26 | + elif 'mac' in line_json: |
| 27 | + sensors = self.cb.select(Sensor) |
| 28 | + for s in sensors: |
| 29 | + for nic in s.network_interfaces: |
| 30 | + if nic.macaddr == line_json['mac']: |
| 31 | + sensor = s |
| 32 | + if sensor: |
| 33 | + line_json["sensor_id"]=sensor.id |
| 34 | + |
| 35 | + return json.dumps(line_json)+"\n" |
| 36 | + |
| 37 | + def process_inventory(self,inventory,verbose=False): |
| 38 | + writelines = [] |
| 39 | + with open(inventory,"r") as inventory_file: |
| 40 | + lines = inventory_file.readlines() |
| 41 | + writelines = map(self.sensor_lookup,lines) |
| 42 | + with open(inventory+".out","w") as inventory_file: |
| 43 | + inventory_file.writelines(writelines) |
| 44 | + |
| 45 | +def main(): |
| 46 | + parser = build_cli_parser() |
| 47 | + parser.add_argument("-i","--inventory",action="store",help="Inventory",dest="inventory",required=True) |
| 48 | + args = parser.parse_args() |
| 49 | + cb = get_cb_response_object(args) |
| 50 | + ip = InventoryProcessor(cbapi=cb) |
| 51 | + ip.process_inventory(inventory = args.inventory) |
| 52 | + |
| 53 | +if __name__=="__main__": |
| 54 | + main() |
| 55 | + |
0 commit comments