Archived community.zenoss.org | full text search
Skip navigation
Currently Being Moderated

Import Devices from CSV with Location Information

VERSION 1 
Created on: Sep 14, 2009 11:21 AM by jshank - Last Modified:  Sep 14, 2009 11:21 AM by jshank

I needed to insert roughly 150 devices that do not support SNMP and wanted to do so with the location, manufacturer and model information. Here is a python script that reads a csv and can be easily modified to add many of the fields using xmlrpc.

 

#!/usr/bin/env python

from xmlrpclib import ServerProxy
import getopt, sys, string
def main():
        DEBUG = False
        try:
          opts, extraparams = getopt.getopt(sys.argv[1:], "i:vu:p:z:")
        except getopt.GetoptError, err:
          print str(err)
          usage()
          sys.exit(2)
        optdict = dict(opts)
        missingopts = [ opt for opt in ["-i", "-p", "-u", "-z"] if opt not in optdict ]
        if missingopts:
                missingopt(missingopts)
                usage()
                sys.exit(0)

        verbose = False
        for o,p in opts:
          if o == '-i':
                importfile = p
          elif o == "-v":
                verbose = True
          elif o == "-u":
                username = p
          elif o == "-p":
                password = p
          elif o == "-z":
                zenossurl = p
          elif o in ['-h','--help']:
                usage()
                sys.exit()
        if DEBUG == False:
          addServ = ServerProxy('http://%s:%s@%s:8080/zport/dmd/DeviceLoader' % (username, password, zenossurl))
          locationServ = ServerProxy('http://%s:%s@%s:8080/zport/dmd/Locations' % (username, password, zenossurl))
        else:
          print "Debug mode, not executing command"
        existingLocations = locationServ.getOrganizerNames()
        f = open(importfile)
        for line in f.readlines():
          # Remove quotes and split by comma
          devicedata = string.replace(line, '"', '').split(',')
          address, location, manufacturer, model, group, devicepath = devicedata[0:6]
          location = "/" + location
          group = "/" + group

          # Checking Locations
          if location not in existingLocations:
                if verbose == True: print "Location does not exist, adding"
                locationServ.manage_addOrganizer(location)

          if verbose == True:
                print "Adding Device"
                print "Address: ", address
                print "location: ", location
                print "Manufacturer: ", manufacturer
                print "Model: ", model
                print "Group: ", group
                print "Device Path: ", devicepath
          if DEBUG == False:
                addServ.loadDevice(address, devicepath,
                        "", "",         # tag="", serialNumber="",
                        "", "", "",     # zSnmpCommunity="", zSnmpPort=161, zSnmpVer=None,
                        0, 1000, "",    # rackSlot=0, productionState=1000, comments="",
                        manufacturer, model,         # hwManufacturer="", hwProductName="",
                        '', '',         # osManufacturer="", osProductName="",
                        location, [group], [],     # locationPath="", groupPaths=[], systemPaths=[],
                        ['localhost'],  # statusMonitors=["localhost"],
                        'localhost',    # performanceMonitor="localhost',
                        'none')         # discoverProto="snmp"

def usage():
        print """Usage: zencsvimport [OPTION]...
        Imports data from a CSV into Zenoss through Zen RPCXML Interface.

        Mandatory arguments to long options are mandatory for short options too.
          -h, --help                 display this help and exit
          -i                         full path to csv import file
          -p                         password with add device rights to zenoss site
          -u                         username with add device rights to zenoss site
          -z                         zenoss url; port 8080 is assumed just need the dns name or
                                                                 IP to zenoss
          -v                         verbose

        Example:
        zencsvimport -i mydevices.csv -u username -p verysecure -z zenosssrv

        import file example format, one device per line:
        ---begin file---
        "dnsdevicename","locationPath","hwManufacturer","hwProductName","groupPath","devicePath"
        "deviceipaddress","locationPath","hwManufacturer","hwProductName","groupPath","devicePath"
        --- end file ---
        """

def missingopt(missingopts):
        print "Missing required argument(s): " + ", ".join(map(str, missingopts))

if __name__ == "__main__":
    main()

 

You can edit this script for your needs. Just remember that you need to have already created the location, group, manufacturer, product, etc that you want to add.


Now you create a csv file with one device per line:

 

devices.csv

 

comments:

... --jcurry, Mon, 02 Feb 2009 12:08:58 -0600 reply

 

I have had a go at modifying and extending this.  Code is at http://www.zenoss.com/Members/jcurry/jc_batch_load.py/view #
Comments (0)

More Like This

  • Retrieving data ...