├── util ├── __init__.py ├── checkpkg.py └── ianaparse.py ├── README.md ├── icinga-autod.py └── LICENSE /util/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # icinga2-autod 2 | 3 | ## Purpose: 4 | The purpose of icinga2-autod is to bring basic auto-discovery Icinga2 (or Icinga/Nagios Core with minor modifications) in an effort to take some of the pain away from discovering and adding a bunch of devices on new or existing networks. The focus of this tool is to quickly generate a fairly suitable host config with custom vars to tie them to HostGroups. 5 | 6 | ## Requirements 7 | This utility requires Linux packages 'nmap' and 'snmp' (or 'net-snmp + net-snmp-utils' on RHEL). It will not run until any missing requirements are satisfied. 8 | 9 | ## Installation 10 | ```bash 11 | git clone https://github.com/hobbsh/icinga2-autod.git 12 | cd icinga2-autod 13 | 14 | ./icinga-autod.py -n 192.168.1.0/24 15 | ``` 16 | Will output discovered_hosts.conf to current directory. 17 | 18 | ## Usage: 19 | This utility is meant to serve as a way to quickly generate a base hosts config for a given network. The host objects it creates (depending on the information it can gather) provide enough data to use HostGroups to do most of your check manangement. It's by no means a catch-all or the only way to do it, but I figured people might have a use for it. 20 | 21 | ``` 22 | usage: icinga-autod.py [-h] -n NETWORK [-L LOCATION] [-c COMMUNITIES] 23 | [-d DEBUG] 24 | 25 | required arguments 26 | -n NETWORK, --network NETWORK 27 | Network segment to iterate through for live 28 | IP addresses in CIDR IPv4 Notation (accepts single IPv4 address too) 29 | optional arguments: 30 | -h, --help show this help message and exit 31 | -L LOCATION, --location LOCATION 32 | Location alias of the network - will be appended to 33 | the hosts config (i.e. hosts_location.conf) 34 | -c COMMUNITIES, --communities COMMUNITIES 35 | Specify comma-separated list of SNMP communities to 36 | iterate through (to override default public,private) 37 | -d DEBUG, --debug DEBUG 38 | Use '-d True' to turn debug on 39 | ``` 40 | Add your own sys_descriptor matches in the compile_hvars method to add custom variables. Hoping to add a better way of handling this soon 41 | 42 | ## TODO: 43 | - More options 44 | - Allow user to input hostname FQDN format (should it come to that) 45 | - Specify SNMP timeout/retries 46 | - Allow different hostype definitions (maybe parse templates.conf) 47 | - Allow more in-depth host objects in general 48 | - Integrate with icingaweb2 49 | - Add SNMPv3 Support 50 | - Handle bad user input better 51 | -------------------------------------------------------------------------------- /util/checkpkg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ''' 3 | This module checks for the existence of a given package on the host OS 4 | Currently only RHEL/Debian based systems supported 5 | 6 | Usage: 7 | import checkpkg 8 | checkpkg.check(['package1', 'package2', 'package3']) 9 | 10 | Note that this is not completely universal and customizations for some packages might need to be added 11 | 12 | Copyright Wylie Hobbs 2015 13 | 14 | This program is free software; you can redistribute it and/or 15 | modify it under the terms of the GNU General Public License 16 | as published by the Free Software Foundation; either version 2 17 | of the License, or (at your option) any later version. 18 | 19 | This program is distributed in the hope that it will be useful, 20 | but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | GNU General Public License for more details. 23 | 24 | You should have received a copy of the GNU General Public License 25 | along with this program; if not, write to the Free Software 26 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 27 | 28 | ''' 29 | import subprocess 30 | import os 31 | import platform 32 | import sys 33 | 34 | def check(packages): 35 | 36 | dependencies = True 37 | 38 | for package in packages: 39 | pkg, installed = _find(package) 40 | if not installed: 41 | sys.stderr.write('Package '+package+' is not installed! Please install it and try again\n') 42 | dependencies = False 43 | 44 | if dependencies: 45 | return 46 | else: 47 | sys.exit(1) 48 | 49 | def _find(package): 50 | 51 | #Try with which first 52 | ret, out, err = exec_command('which '+package) 53 | 54 | if not ret and not err: 55 | return [package, True] 56 | else: 57 | 58 | #Get distro name 59 | distro = platform.dist()[0].lower() 60 | 61 | #Debian or RedHat based? 62 | if distro in ['centos', 'redhat']: 63 | if package == 'snmp': 64 | command = 'rpm -qa | grep -e ^net-snmp-[0-9].*$' 65 | elif package == 'net-snmp-utils': 66 | command = 'rpm -qa | grep -e ^net-snmp-utils-.*$' 67 | else: 68 | command = 'rpm -qa | grep -e '+package 69 | 70 | ret, out, err = exec_command(command) 71 | 72 | elif distro in ['ubuntu', 'debian']: 73 | if 'net-snmp' not in package: 74 | ret, out, err = exec_command("dpkg --list | awk '{print $2}' | grep -e ^"+package+"$") 75 | else: 76 | return [package, True] 77 | 78 | else: 79 | sys.stderr.write('Unsupported distribution! You will have to resolve missing requirements yourself.') 80 | sys.exit(1) 81 | 82 | if len(out) > 0: 83 | return [package, True] 84 | else: 85 | return [package, False] 86 | 87 | 88 | def exec_command(command): 89 | """Execute command. 90 | Return a tuple: returncode, output and error message(None if no error). 91 | """ 92 | sub_p = subprocess.Popen(command, 93 | shell=True, 94 | stdout=subprocess.PIPE, 95 | stderr=subprocess.PIPE) 96 | output, err_msg = sub_p.communicate() 97 | return (sub_p.returncode, output, err_msg) 98 | 99 | -------------------------------------------------------------------------------- /util/ianaparse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # iana_enterprise_numbers_convert.py 4 | # a script to convert the IANA "enterprise-numbers" to a JSON file 5 | # 6 | # Ch. Bueche 7 | # 22.7.2014 8 | # 9 | # https://raw.githubusercontent.com/cbueche/Agent-Jones/master/util/iana_enterprise_numbers_convert.py 10 | # 11 | # Modified for use in icinga-autod.py 12 | # 13 | 14 | import sys 15 | import os 16 | import re 17 | import json 18 | import urllib2 19 | import tempfile 20 | 21 | class IanaParser(object): 22 | # -------------------------------------------------------------------------------- 23 | def parse(self): 24 | # -------------------------------------------------------------------------------- 25 | 26 | # script parameters 27 | input_url = 'http://www.iana.org/assignments/enterprise-numbers/enterprise-numbers' 28 | output_file = 'iana_numbers.json' 29 | 30 | global debug 31 | debug = False 32 | 33 | temp_file = self.get_from_url(input_url) 34 | if debug: 35 | print "IF=<%s>, TMP=<%s>, OUT=<%s>" % (input_url, temp_file, output_file) 36 | 37 | # conversion 38 | entries = self.iana_to_json(temp_file, output_file) 39 | #print "found %s entries" % entries 40 | if debug: 41 | print "deleting tmp file %s" % temp_file 42 | os.unlink(temp_file) 43 | #print "End" 44 | return entries 45 | 46 | 47 | # -------------------------------------------------------------------------------- 48 | def iana_to_json(self, temp_file, output_file): 49 | # -------------------------------------------------------------------------------- 50 | 51 | # temp file 52 | try: 53 | fp = open(temp_file, 'r') 54 | except (IOError, OSError) as e: 55 | print "ERROR : cannot open input file, exit : %s" % e 56 | sys.exit(1) 57 | 58 | # header parsing 59 | # -------------- 60 | 61 | # read until the data start (0 - Reserved) 62 | while True: 63 | line = fp.readline() 64 | if not line: break 65 | 66 | # remove end of line 67 | line = line.rstrip() 68 | 69 | # check for the usual IANA header in 1st line 70 | if re.search(r'PRIVATE ENTERPRISE NUMBERS', line): 71 | if debug: 72 | print "found header" 73 | 74 | # last updated stamp 75 | regex = re.compile(r'\(last updated (\d{4}-\d{2}-\d{2})\)') 76 | match = regex.search(line) 77 | if match: 78 | last_update = match.group(1) 79 | #print "updated = %s" % last_update 80 | 81 | # stop right before the data records 82 | if line == '| | | |': 83 | break 84 | 85 | if debug: 86 | print "header done" 87 | 88 | # and now the data 89 | # ------------------------------------- 90 | 91 | valid_entries = 0 92 | enterprises = {} 93 | block = [] 94 | while True: 95 | 96 | line = fp.readline().strip('\n') 97 | 98 | # skip blank lines 99 | if line == '': 100 | continue 101 | 102 | # try to extract a record 103 | # idea is to read from one decimal to the next 104 | # and send the read block to a function to parse it 105 | 106 | # get decimal 107 | if re.search(r'^\d+$', line): 108 | # before creating the new block, send the existing one to analysis 109 | # skip the first, empty block 110 | if len(block) > 0: 111 | valid_entries += 1 112 | status, decimal, organization, contact, email = self.analyze_block(block) 113 | if status: 114 | enterprises[decimal] = {'o': organization, 'c': contact, 'e': email} 115 | # and now start a new block 116 | block = [] 117 | decimal = line.strip() 118 | block.append(decimal) 119 | 120 | else: 121 | 122 | # now add to current block until next decimal 123 | block.append(line) 124 | 125 | # check for the usual IANA footer in last line 126 | if re.search(r'End of Document', line): 127 | # and stores the last found block 128 | block.pop() 129 | valid_entries += 1 130 | status, decimal, organization, contact, email = self.analyze_block(block) 131 | if status: 132 | enterprises[decimal] = {'o': organization, 'c': contact, 'e': email} 133 | 134 | if debug: 135 | print "found footer, exit read loop" 136 | break 137 | 138 | fp.close 139 | # write data structure to output file 140 | with open(output_file, 'w') as of: 141 | json.dump(enterprises, of) 142 | 143 | return enterprises 144 | 145 | 146 | # -------------------------------------------------------------------------------- 147 | def analyze_block(self, block): 148 | # -------------------------------------------------------------------------------- 149 | 150 | if debug: 151 | print "analyzing block %s" % block 152 | 153 | decimal = 0 154 | organization = '' 155 | contact = '' 156 | email = '' 157 | 158 | # first element must be the decimal number. If not, we are doing something wrong 159 | if re.search(r'^\d+$', block[0]): 160 | decimal = block[0] 161 | else: 162 | print "ERROR: first element of block is not a valid decimal" 163 | return False, -1, 'na', 'na', 'na' 164 | 165 | # now loop over the other elements 166 | last_element_found = '' 167 | for element in block[1:]: 168 | if debug: 169 | print "working on element <%s>" % element 170 | 171 | # get line addition 172 | # any non-blank text starting at beginning of line, but not a number 173 | if re.search(r'^[^\d\s]', element): 174 | if debug: 175 | print "line continuation" 176 | if last_element_found == 'organization': 177 | organization = organization + ' ' + element 178 | elif last_element_found == 'contact': 179 | contact = contact + ' ' + element 180 | elif last_element_found == 'email': 181 | email = email + ' ' + element 182 | else: 183 | print "ERROR: don't know how to add this line to unknown block element" 184 | return False, -1, 'na', 'na', 'na' 185 | continue 186 | 187 | # organization 188 | if last_element_found == '': 189 | organization = element 190 | last_element_found = 'organization' 191 | continue 192 | 193 | # contact 194 | if last_element_found == 'organization': 195 | contact = element 196 | last_element_found = 'contact' 197 | continue 198 | 199 | # email 200 | if last_element_found == 'contact': 201 | email = element.replace('&', '@') 202 | last_element_found = 'email' 203 | continue 204 | 205 | # something after email, shall not happen 206 | if last_element_found == 'email': 207 | print "ERROR: nothing should come after the email element" 208 | continue 209 | 210 | return True, decimal, self.clean(organization), self.clean(contact), self.clean(email) 211 | 212 | 213 | # -------------------------------------------------------------------------------- 214 | def clean(self, input): 215 | # -------------------------------------------------------------------------------- 216 | 217 | output = input.strip() 218 | output = re.sub(r'\s+', ' ', output) 219 | return output 220 | 221 | 222 | # -------------------------------------------------------------------------------- 223 | def get_from_url(self, url): 224 | # -------------------------------------------------------------------------------- 225 | 226 | tmp = tempfile.NamedTemporaryFile(prefix = 'iana_en_', suffix = '.tmp', delete = False) 227 | urldata = urllib2.urlopen(url) 228 | while True: 229 | line = urldata.readline() 230 | if not line: break 231 | tmp.write(line) 232 | 233 | tmp.close() 234 | return tmp.name 235 | 236 | -------------------------------------------------------------------------------- /icinga-autod.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import util.checkpkg as checkpkg 3 | 4 | checkpkg.check(['nmap', 'snmp', 'net-snmp-utils']) 5 | 6 | import sys 7 | import subprocess 8 | import json 9 | 10 | try: 11 | import argparse 12 | except ImportError: 13 | checkpkg.check(['python-argparse']) 14 | 15 | import time 16 | import socket 17 | import util.ianaparse as ianaparse 18 | 19 | """ 20 | This discovery script will scan a subnet for alive hosts, 21 | determine some basic information about them, 22 | then create a hosts.conf in the current directory for use in Nagios or Icinga 23 | 24 | required Linux packages: python-nmap and nmap 25 | 26 | Copyright Wylie Hobbs - 08/28/2015 27 | 28 | This program is free software; you can redistribute it and/or 29 | modify it under the terms of the GNU General Public License 30 | as published by the Free Software Foundation; either version 2 31 | of the License, or (at your option) any later version. 32 | 33 | This program is distributed in the hope that it will be useful, 34 | but WITHOUT ANY WARRANTY; without even the implied warranty of 35 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 36 | GNU General Public License for more details. 37 | 38 | You should have received a copy of the GNU General Public License 39 | along with this program; if not, write to the Free Software 40 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 41 | """ 42 | 43 | USAGE = './icinga-autod.py -n 192.168.1.0/24' 44 | 45 | def build_parser(): 46 | 47 | parser = argparse.ArgumentParser(description='Device AutoDiscovery Tool') 48 | 49 | parser.add_argument('-n', '--network', required=True, 50 | help='Network segment (only /24) to iterate through for live IP addresses in CIDR IPv4 Notation') 51 | 52 | parser.add_argument('-L', '--location', default=None, 53 | help='Location alias of the network - will be appended to the hosts config (i.e. hosts_location.conf)') 54 | 55 | parser.add_argument('-c', '--communities', default="public,private", 56 | help='Specify comma-separated list of SNMP communities to iterate through (to override default public,private)') 57 | 58 | parser.add_argument('-d', '--debug', default=False, 59 | help='Specify comma-separated list of SNMP communities to iterate through (to override default public,private)') 60 | 61 | #The following two arguments have no effect currently 62 | parser.add_argument('-r', '--reparse-iana', default=False, 63 | help='Whether icinga-autod should grab a fresh version of the sysObjectIDs from the IANA URL') 64 | 65 | parser.add_argument('-t', '--thorough', default=0, 66 | help='Thorough scan mode (will take longer) - will try additional SNMP versions/communities to try to gather as much information as possible') 67 | 68 | return parser 69 | 70 | def main(): 71 | 72 | global debug 73 | 74 | parser = build_parser() 75 | args = parser.parse_args() 76 | 77 | '''Check arguments''' 78 | if check_args(args) is False: 79 | sys.stderr.write("There was a problem validating the arguments supplied. Please check your input and try again. Exiting...\n") 80 | sys.exit(1) 81 | 82 | if args.debug: 83 | debug = True 84 | else: 85 | debug = False 86 | 87 | start_time = time.time() 88 | 89 | cidr = args.network 90 | 91 | location = args.location 92 | 93 | credential = dict() 94 | credential['version'] = '2c' 95 | credential['community'] = args.communities.split(',') 96 | 97 | #Hostname and sysDescr OIDs 98 | oids = '1.3.6.1.2.1.1.5.0 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.2.0' 99 | 100 | #Scan the network 101 | hosts = handle_netscan(cidr) 102 | 103 | all_hosts = {} 104 | 105 | print("Found {0} hosts - gathering more info (can take up to 2 minutes)".format(get_count(hosts))) 106 | 107 | try: 108 | with open('iana_numbers.json', 'r') as f: 109 | numbers = json.load(f) 110 | except Exception, e: 111 | try: 112 | numbers = ianaparse.IanaParser().parse() 113 | except: 114 | sys.exit("Unable to open iana_numbers.json or read from the URL. Exiting...") 115 | 116 | sys.stderr.write('Unable to open iana_numbers.json, trying URL method. Please wait\n') 117 | 118 | 119 | for host in hosts: 120 | host = str(host) 121 | 122 | '''If your communities/versions vary, modify credentials here. I've used last_octet to do this determination 123 | octets = host.split('.') 124 | last_octet = str(octets[3]).strip() 125 | Otherwise, grab the data 126 | ''' 127 | 128 | hostname = '' 129 | 130 | if ',' in host: 131 | hostname, host = host.split(',') 132 | 133 | data = snmpget_by_cl(host, credential, oids) 134 | 135 | '''TODO: clean up this logic...''' 136 | try: 137 | output = data['output'].split('\n') 138 | community = data['community'] 139 | 140 | hostname = output[0].strip('"') 141 | sysdesc = output[1].strip('"') 142 | sysobject = output[2].strip('"') 143 | 144 | except: 145 | community = 'unknown' 146 | output = '' 147 | 148 | sysdesc = '' 149 | sysobject = '' 150 | 151 | v_match = vendor_match(numbers, sysobject) 152 | 153 | if v_match: 154 | vendor = v_match['o'].strip('"') 155 | else: 156 | vendor = None 157 | 158 | all_hosts[host] = { 159 | 'community': community, 'snmp_version': credential['version'], 'hostname': hostname, 'sysdesc': sysdesc, 'vendor' : vendor } 160 | 161 | if debug: 162 | print host, sysobject, all_hosts[host] 163 | 164 | print "\n" 165 | print("Discovery took %s seconds" % (time.time() - start_time)) 166 | print "Writing data to config file. Please wait" 167 | 168 | outfile = compile_hosts(all_hosts, location) 169 | print "Wrote data to "+outfile 170 | 171 | def vendor_match(numbers, sysobject): 172 | if sysobject: 173 | #Possible prefixes in sysObjectID OID largely dependent on MIB used 174 | prefixes = ['SNMPv2-SMI::enterprises.', 'iso.3.6.1.4.1.', '1.3.6.1.4.1.', 'NET-SNMP-MIB::netSnmpAgentOIDs.'] 175 | 176 | for prefix in prefixes: 177 | if sysobject.startswith(prefix): 178 | sysobject = sysobject[len(prefix):] 179 | 180 | values = sysobject.split('.') 181 | #first value will be the enterprise number 182 | vendor_num = values[0] 183 | 184 | try: 185 | vendor_string = numbers[vendor_num] 186 | return vendor_string 187 | 188 | except Exception, e: 189 | sys.stderr.write('Unknown sysObjectID prefix encountered - you can add it to the prefix list in vendor_match(), but please report this on GitHub\n'+str(e)) 190 | return False 191 | else: 192 | return False 193 | 194 | def check_args(args): 195 | '''Exit if required arguments not specified''' 196 | ''' 197 | if args.network == None: 198 | sys.stderr.write("Network and/or location are required arguments! Use -h for help\n") 199 | sys.exit(1) 200 | ''' 201 | check_flags = {} 202 | '''Iterate through specified args and make sure input is valid. TODO: add more flags''' 203 | for k,v in vars(args).iteritems(): 204 | if k == 'network': 205 | network = v.split('/')[0] 206 | if len(network) > 7: 207 | if is_valid_ipv4_address(network) is False: 208 | check_flags['is_valid_ipv4_address'] = False 209 | else: 210 | check_flags['is_valid_ipv4_format'] = False 211 | 212 | last_idx = len(check_flags) - 1 213 | last_key = '' 214 | 215 | '''Find last index key so all the violated flags can be output in the next loop''' 216 | for idx, key in enumerate(check_flags): 217 | if idx == last_idx: 218 | last_key = key 219 | 220 | for flag, val in check_flags.iteritems(): 221 | if val is False: 222 | sys.stderr.write("Check "+flag+" failed to validate your input.\n") 223 | if flag == last_key: 224 | return False 225 | 226 | def is_valid_ipv4_address(address): 227 | '''from http://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python''' 228 | try: 229 | socket.inet_pton(socket.AF_INET, address) 230 | except AttributeError: # no inet_pton here, sorry 231 | try: 232 | socket.inet_aton(address) 233 | except socket.error: 234 | return False 235 | return address.count('.') == 3 236 | except socket.error: # not a valid address 237 | return False 238 | 239 | return True 240 | 241 | def get_count(hosts): 242 | count = len(hosts) 243 | if count == 0: 244 | print "No hosts found! Is the network reachable? \nExiting..." 245 | sys.exit(0) 246 | else: 247 | return count 248 | 249 | def compile_hosts(data, location): 250 | if location: 251 | loc = location.lower() 252 | filename = 'hosts_'+loc+'.conf' 253 | else: 254 | filename = 'discovered_hosts.conf' 255 | 256 | f = open(filename, 'w') 257 | 258 | for ip, hdata in data.iteritems(): 259 | hostvars = compile_hvars(hdata['sysdesc']) 260 | 261 | if not hdata['hostname']: 262 | hostname = ip 263 | else: 264 | hostname = hdata['hostname'] 265 | 266 | host_entry = build_host_entry(hostname, str(ip), location, hdata['vendor'], str(hostvars)) 267 | 268 | f.write(host_entry) 269 | 270 | f.close() 271 | 272 | return filename 273 | 274 | def build_host_entry(hostname, ip, location, vendor, hostvars): 275 | host_entry = ( 'object Host "%s" {\n' 276 | ' import "generic-host"\n' 277 | ' address = "%s"\n' 278 | ) % (hostname, ip) 279 | 280 | if location: 281 | host_entry += ' vars.location = "{0}"\n'.format(location) 282 | if vendor: 283 | host_entry += ' vars.vendor = "{0}"\n'.format(vendor) 284 | if hostvars: 285 | host_entry += ' {0}\n'.format(hostvars) 286 | 287 | host_entry += '}\n' 288 | 289 | return host_entry 290 | 291 | def compile_hvars(sysdesc): 292 | sys_descriptors = { 293 | 'RouterOS': 'vars.network_mikrotik = "true"', 294 | 'Linux':'vars.os = "Linux"', 295 | 'APC Web/SNMP': 'vars.ups_apc = "true"', 296 | } 297 | 298 | hostvars = '' 299 | 300 | '''Append hostvars based on sysDescr matches''' 301 | for match, var in sys_descriptors.iteritems(): 302 | if match in sysdesc: 303 | hostvars += var +'\n ' 304 | 305 | return hostvars 306 | 307 | def handle_netscan(cidr): 308 | ''' 309 | Scan network with nmap using ping only 310 | ''' 311 | start = time.time() 312 | 313 | print "Starting scan for "+cidr 314 | 315 | ret, output, err = exec_command('nmap -sn -sP {0}'.format(cidr)) 316 | if ret and err: 317 | sys.stderr.write('There was a problem performing the scan - is the network reachable?') 318 | sys.exit(1) 319 | else: 320 | print ("Scan took %s seconds" % (time.time() - start)) 321 | data = parse_nmap_scan(output) 322 | if data: 323 | return data 324 | else: 325 | sys.stderr.write('Unable to parse nmap scan results! Please report this issue') 326 | sys.exit(1) 327 | 328 | def parse_nmap_scan(data): 329 | data_list = data.split('\n') 330 | match = 'Nmap scan report for ' 331 | hosts = [] 332 | for line in data_list: 333 | if match in line and line is not None: 334 | line = line[len(match):].strip(' ') 335 | 336 | if '(' in line: 337 | remove = '()' 338 | for c in remove: 339 | line = line.replace(c, '') 340 | 341 | line = ','.join(line.split(' ')) 342 | 343 | hosts.append(line) 344 | 345 | return hosts 346 | 347 | def snmpget_by_cl(host, credential, oid, timeout=1, retries=0): 348 | ''' 349 | Slightly modified snmpget method from net-snmp source to loop through multiple communities if necessary 350 | ''' 351 | 352 | data = {} 353 | version = credential['version'] 354 | communities = credential['community'] 355 | com_count = len(communities) 356 | 357 | for i in range(0, com_count): 358 | cmd = '' 359 | community = communities[i].strip() 360 | cmd = "snmpget -Oqv -v %s -c %s -r %s -t %s %s %s" % ( 361 | version, community, retries, timeout, host, oid) 362 | 363 | returncode, output, err = exec_command(cmd) 364 | 365 | #print returncode, output, err 366 | if returncode and err: 367 | if i < com_count: 368 | continue 369 | else: 370 | data['error'] = str(err) 371 | else: 372 | try: 373 | data['output'] = output 374 | data['community'] = community 375 | #Got the data, now get out 376 | break 377 | except Exception, e: 378 | print "There was a problem appending data to the dict " + str(e) 379 | 380 | return data 381 | 382 | def exec_command(command): 383 | """Execute command. 384 | Return a tuple: returncode, output and error message(None if no error). 385 | """ 386 | sub_p = subprocess.Popen(command, 387 | shell=True, 388 | stdout=subprocess.PIPE, 389 | stderr=subprocess.PIPE) 390 | output, err_msg = sub_p.communicate() 391 | return (sub_p.returncode, output, err_msg) 392 | 393 | 394 | if __name__ == "__main__": 395 | main() 396 | sys.exit(0) 397 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | --------------------------------------------------------------------------------