Changeset 8317 in genesis for nodes


Ignore:
Timestamp:
Aug 12, 2010, 12:28:44 PM (14 years ago)
Author:
rick
Message:

Now with actually parsing and scanning WL specified IP addresses (no Nanostations yet)

Location:
nodes
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • nodes/gformat.py

    r8298 r8317  
    277277
    278278  return datadump
     279
     280
     281
     282def get_all_configs():
     283  """ Get dict with key 'host' with all configs present """
     284  configs = dict()
     285  for host in get_hostlist():
     286    datadump = get_yaml(host)
     287    configs[host] = datadump
     288  return configs
     289
     290
     291
     292def get_used_ips(configs):
     293    """ Return array of all IPs used in config files"""
     294    ip_list = []
     295    for host,config in configs.iteritems():
     296      ip_list.append(config['masterip'])
     297      iface_keys = [elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)]
     298      for iface_key in iface_keys:
     299        l = config[iface_key]['ip']
     300        addr, mask = l.split('/')
     301        # Special case do not process
     302        if addr not in ["0.0.0.0"]:
     303           ip_list.append(addr)
     304    return sorted(ip_list)
    279305
    280306
  • nodes/status-monitoring.py

    r8316 r8317  
    11#!/usr/bin/env python
     2# vim:ts=2:et:sw=2:ai
     3#
    24# Scan Wireless Leiden Network and report status of links and nodes
    35#
     
    68from pprint import pprint
    79from xml.dom.minidom import parse, parseString
     10import gformat
    811import os.path
    912import re
     
    1518SCAN_RANGE='172.16.0.0/21'
    1619
    17 
     20#
     21# BEGIN nmap XML parser
     22# XXX: Should properly go to seperate class/module
    1823def get_attribute(node,attr):
    1924  return node.attributes[attr].value
     
    5863      status[scan['addr']] = scan
    5964  return status
    60 
    61 
    62 def _run_nmap(command, result_file="-"):
     65#
     66# END nmap parser
     67#
     68
     69
     70
     71def _do_nmap_scan(command, iphosts, result_file=None):
    6372  """ Run/Read nmap XML with various choices"""
    64 
    65   command = "nmap -n -oX - %s" %(command)
    66   dom = None
    67   if result_file == "-":
    68     print "# New run '%s' results not saved" % (command)
    69     dom = parseString(subprocess.Popen(command.split(),
    70             stdout=subprocess.PIPE).communicate()[0])
    71   elif os.path.exists(result_file) and os.path.getsize(result_file) > 0:
     73  # Return stored file if exists
     74  if result_file and os.path.exists(result_file) and os.path.getsize(result_file) > 0:
    7275    print "# Reading stored NMAP results from '%s'" % (result_file)
    7376    dom = parse(result_file)
    74   else:
    75     print "# New run '%s' saving results in %s" % (command, result_file)
    76     print "# Waiting for nmap run to complete"
    77     f = open(result_file,'w')
    78     p = subprocess.Popen(command.split(),stdout=f)
    79     while p.poll() == None:
    80       print ".",
    81       sys.stdout.flush()
    82       time.sleep(1)
    83     print "DONE"
    84     if p.returncode != 0:
    85       print "# ERROR in nmap command"
    86       sys.exit(1)
     77    return dom
     78
     79  command = "nmap -n -iL - -oX - %s" %(command)
     80  print "# New run '%s', can take a while to complete" % (command)
     81  p = subprocess.Popen(command.split(),
     82        stdout=subprocess.PIPE,
     83        stderr=subprocess.PIPE,
     84        stdin=subprocess.PIPE, bufsize=-1)
     85
     86  (stdoutdata, stderrdata) = p.communicate("\n".join(iphosts.split(" ")))
     87  if p.returncode != 0:
     88    print "# [ERROR] nmap failed to complete '%s'" % stderrdata
     89    sys.exit(1)
     90
     91  if result_file:
     92    print "# Saving results in %s" % (result_file)
     93    f = file(result_file,'w')
     94    f.write(stdoutdata)
    8795    f.close()
    88     dom = parse(result_file)
     96
     97  dom = parseString(stdoutdata)
    8998  return parse_nmap(dom)
    9099
    91 def do_nmap(command, iphosts, result_file="-"):
    92   """ Wrapper around _run_nmap to get listing of all hosts"""
     100
     101
     102def do_nmap_scan(command, iphosts, result_file="-"):
     103  """ Wrapper around _run_nmap to get listing of all hosts, the default nmap
     104      does not return results for failed hosts"""
    93105  # Get all hosts to be processed
    94   status = _run_nmap("-sL " + iphosts)
    95   status.update(_run_nmap("%s %s" % (command, iphosts), result_file))
     106  status = _do_nmap_scan("-sL",iphosts)
     107  status.update(_do_nmap_scan(command, iphosts, result_file))
    96108  return status
     109
     110
    97111
    98112def do_snmpwalk(host, oid):
     
    108122
    109123
     124
     125
    110126def run_scan(host_filter=None):
    111127  """ Big working processing all scanning work"""
     
    113129  if host_filter:
    114130    iphosts = " ".join(host_filter)
    115     result_file = "-"
     131    result_file = None
    116132  else:
    117133    iphosts = SCAN_RANGE
    118134    result_file = '/tmp/test.xml'
    119135
    120   status = do_nmap("-p T:ssh,U:domain,T:80,T:ntp,U:snmp,T:8080 -sU -sT ",iphosts, result_file)
     136  status = do_nmap_scan("-p T:ssh,U:domain,T:80,T:ntp,U:snmp,T:8080 -sU -sT ",iphosts, result_file)
    121137  mac_to_host = dict()
    122138  host_processed = dict()
     
    228244    sys.exit(0)
    229245
    230 stored_status = dict()
    231 stored_status_file = '/tmp/stored_status.yaml'
    232 if len(sys.argv) > 1:
    233   if sys.argv[1] == "all":
    234     stored_status = run_scan()
    235     stream = file(stored_status_file,'w')
    236     print "##Stored data hints to '%' " % stored_status
    237     stored_status = yaml.dump(stored_status, stream, default_flow_style=False)
    238   elif sys.argv[1] == "force":
    239     stored_status = run_scan()
    240   elif sys.argv[1] == "host":
    241     stored_status = run_scan(sys.argv[2:])
    242   elif sys.argv[1] == "stored":
    243     # Load data hints from previous run if exists
    244     if os.path.exists(stored_status_file) and os.path.getsize(stored_status_file) > 0:
    245       stream = file(stored_status_file,'r')
    246       stored_status = yaml.load(stream)
     246
     247def generate_status(stored_status):
     248  """ Generate result file from stored_status """
     249  host_processed = stored_status['host_processed']
     250  mac_to_host = stored_status['mac_to_host']
     251  # Correlation mapping
     252  for host, details in host_processed.iteritems():
     253    print "# Working on %s" % host
     254    for ip, arpmac in details['arpmac'].iteritems():
     255      if arpmac in details['mac'].keys():
     256        # Local MAC address
     257        continue
     258      if not mac_to_host.has_key(arpmac):
     259        print "## [WARN] No parent host for MAC %s (%s) found" % (arpmac, ip)
     260      else:
     261        print "## Interlink %s - %s"  % (host, mac_to_host[arpmac])
     262
     263
     264
     265def main():
     266  stored_status = dict()
     267  stored_status_file = '/tmp/stored_status.yaml'
     268  if len(sys.argv) > 1:
     269    if sys.argv[1] == "all":
     270      stored_status = run_scan(gformat.get_used_ips(gformat.get_all_configs()))
     271      stream = file(stored_status_file,'w')
     272      print "##Stored data hints to '%' " % stored_status
     273      stored_status = yaml.dump(stored_status, stream, default_flow_style=False)
     274    elif sys.argv[1] == "force":
     275      stored_status = run_scan()
     276    elif sys.argv[1] == "host":
     277      stored_status = run_scan(sys.argv[2:])
     278    elif sys.argv[1] == "stored":
     279      # Load data hints from previous run if exists
     280      if os.path.exists(stored_status_file) and os.path.getsize(stored_status_file) > 0:
     281        stream = file(stored_status_file,'r')
     282        stored_status = yaml.load(stream)
     283      else:
     284        print "[ERROR] '%s' does not exists" % stored_status_file
    247285    else:
    248       print "[ERROR] '%s' does not exists" % stored_status_file
     286      usage()
    249287  else:
    250     usage()
    251 else:
    252    usage()
    253 
    254 
    255 host_processed = stored_status['host_processed']
    256 mac_to_host = stored_status['mac_to_host']
    257 # Correlation mapping
    258 for host, details in host_processed.iteritems():
    259   print "# Working on %s" % host
    260   for ip, arpmac in details['arpmac'].iteritems():
    261     if arpmac in details['mac'].keys():
    262       # Local MAC address
    263       continue
    264     if not mac_to_host.has_key(arpmac):
    265       print "## [WARN] No parent host for MAC %s (%s) found" % (arpmac, ip)
    266     else:
    267       print "## Interlink %s - %s"  % (host, mac_to_host[arpmac])
    268        
    269    
     288     usage()
     289
     290
     291
     292if __name__ == "__main__":
     293  main()
Note: See TracChangeset for help on using the changeset viewer.