Changeset 8318 in genesis


Ignore:
Timestamp:
Aug 12, 2010, 1:50:06 PM (14 years ago)
Author:
rick
Message:
  • Restructuring to make the code 'flow' the way it should be
File:
1 edited

Legend:

Unmodified
Added
Removed
  • nodes/status-monitoring.py

    r8317 r8318  
    1515import time
    1616import yaml
    17 
    18 SCAN_RANGE='172.16.0.0/21'
     17from datetime import datetime
     18
     19# When force is used as argument, use this range
     20DEFAULT_SCAN_RANGE= ['172.16.0.0/21']
    1921
    2022#
     
    6971
    7072
    71 def _do_nmap_scan(command, iphosts, result_file=None):
     73def _do_nmap_scan(command, iphosts):
    7274  """ Run/Read nmap XML with various choices"""
    73   # Return stored file if exists
    74   if result_file and os.path.exists(result_file) and os.path.getsize(result_file) > 0:
    75     print "# Reading stored NMAP results from '%s'" % (result_file)
    76     dom = parse(result_file)
    77     return dom
    78 
    7975  command = "nmap -n -iL - -oX - %s" %(command)
    8076  print "# New run '%s', can take a while to complete" % (command)
     
    8480        stdin=subprocess.PIPE, bufsize=-1)
    8581
    86   (stdoutdata, stderrdata) = p.communicate("\n".join(iphosts.split(" ")))
     82  (stdoutdata, stderrdata) = p.communicate("\n".join(iphosts))
    8783  if p.returncode != 0:
    8884    print "# [ERROR] nmap failed to complete '%s'" % stderrdata
    8985    sys.exit(1)
    9086
    91   if result_file:
    92     print "# Saving results in %s" % (result_file)
    93     f = file(result_file,'w')
    94     f.write(stdoutdata)
    95     f.close()
    96 
    9787  dom = parseString(stdoutdata)
    98   return parse_nmap(dom)
    99 
    100 
    101 
    102 def do_nmap_scan(command, iphosts, result_file="-"):
     88  return (parse_nmap(dom),stdoutdata)
     89
     90
     91
     92def do_nmap_scan(command, iphosts, result_file=None):
    10393  """ Wrapper around _run_nmap to get listing of all hosts, the default nmap
    10494      does not return results for failed hosts"""
    10595  # Get all hosts to be processed
    106   status = _do_nmap_scan("-sL",iphosts)
    107   status.update(_do_nmap_scan(command, iphosts, result_file))
    108   return status
     96  (init_status, stdoutdata) = _do_nmap_scan(" -sL",iphosts)
     97
     98  # Return stored file if exists
     99  if result_file and os.path.exists(result_file) and os.path.getsize(result_file) > 0:
     100    print "# Reading stored NMAP results from '%s'" % (result_file)
     101    status = parse_nmap(parse(result_file))
     102  else:
     103    # New scan
     104    (status, stdoutdata) = _do_nmap_scan(command, iphosts)
     105
     106    # Store result if requested
     107    if result_file:
     108      print "# Saving results in %s" % (result_file)
     109      f = file(result_file,'w')
     110      f.write(stdoutdata)
     111      f.close()
     112
     113  init_status.update(status)
     114  return init_status
    109115
    110116
     
    124130
    125131
    126 def run_scan(host_filter=None):
    127   """ Big working processing all scanning work"""
    128   # Do a NMAP discovery
    129   if host_filter:
    130     iphosts = " ".join(host_filter)
    131     result_file = None
    132   else:
    133     iphosts = SCAN_RANGE
    134     result_file = '/tmp/test.xml'
    135 
    136   status = do_nmap_scan("-p T:ssh,U:domain,T:80,T:ntp,U:snmp,T:8080 -sU -sT ",iphosts, result_file)
     132def do_snmp_scan(iphosts, status, stored_status=dict()):
     133  """ SNMP scanning, based on results fould in NMAP scan"""
    137134  mac_to_host = dict()
    138135  host_processed = dict()
    139   stored_status = dict()
    140136
    141137  #
     
    146142   
    147143    # Filter set? use it
    148     if host_filter and not host in host_filter:
     144    if iphosts and not host in iphosts:
     145      print "## IP '%s' not in specified filter" % host
    149146      continue
    150147 
     
    237234  stored_status['host_processed'] = host_processed
    238235  stored_status['mac_to_host'] = mac_to_host
     236  stored_status['nmap_status'] = status
    239237  return stored_status
    240238 
    241239
    242 def usage():
    243     print "Usage: %s <all|force|stored|host HOST1 [HOST2 ...]>" % sys.argv[0]
    244     sys.exit(0)
    245 
    246 
    247 def generate_status(stored_status):
     240
     241
     242def generate_status(configs, stored_status):
    248243  """ Generate result file from stored_status """
    249244  host_processed = stored_status['host_processed']
    250245  mac_to_host = stored_status['mac_to_host']
     246  status = stored_status['nmap_status']
     247
     248  # List of hosts which has some kind of problem
     249  for host in list(set(configs.keys()) - set(host_processed.keys())):
     250     print "# Problem in host '%s'" % host
     251
    251252  # Correlation mapping
    252253  for host, details in host_processed.iteritems():
     
    262263
    263264
     265def usage():
     266    print "Usage: %s <all|force|stored|host HOST1 [HOST2 ...]>" % sys.argv[0]
     267    sys.exit(0)
     268
    264269
    265270def main():
     271  start_time = datetime.now()
     272  stored_status_file = '/tmp/stored_status.yaml'
     273  nmap_result_file = '/tmp/test.xml'
     274
    266275  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
    285     else:
    286       usage()
    287   else:
    288      usage()
     276  nmap_status = dict()
     277  snmp_status = dict()
     278
     279  opt_nmap_scan = True
     280  opt_store_scan = True
     281  opt_snmp_scan = True
     282  opt_force_snmp = False
     283  opt_force_scan = False
     284  opt_force_range = False
     285  if len(sys.argv) == 1:
     286    usage()
     287
     288  if sys.argv[1] == "all":
     289    pass
     290  elif sys.argv[1] == "nmap-only":
     291    opt_snmp_scan = False
     292  elif sys.argv[1] == "snmp-only":
     293    opt_nmap_scan = False
     294  elif sys.argv[1] == "force":
     295    opt_force_scan = True
     296  elif sys.argv[1] == "forced-snmp":
     297    opt_nmap_scan = False
     298    opt_force_snmp = True
     299  elif sys.argv[1] == "host":
     300    opt_force_range = True
     301    opt_force_scan = True
     302  elif sys.argv[1] == "stored":
     303    opt_snmp_scan = False
     304    opt_nmap_scan = False
     305    opt_store_scan = False
     306  else:
     307    usage()
     308
     309  # By default get all IPs defined in config, else own range
     310  if not opt_force_range:
     311    configs = gformat.get_all_configs()
     312    iplist = gformat.get_used_ips(configs)
     313  else:
     314    iplist = sys.argv[1:]
     315
     316  # Load data hints from previous run if exists
     317  if not opt_force_scan and os.path.exists(stored_status_file) and os.path.getsize(stored_status_file) > 0:
     318    print "## Loading stored data hints from '%s'" % stored_status_file
     319    stream = file(stored_status_file,'r')
     320    stored_status = yaml.load(stream)
     321  else:
     322    print "[ERROR] '%s' does not exists" % stored_status_file
     323
     324  # Do a NMAP discovery
     325  if opt_nmap_scan:
     326    if not opt_store_scan:
     327      nmap_result_file = None
     328    nmap_status = do_nmap_scan("-p T:ssh,U:domain,T:80,T:ntp,U:snmp,T:8080 -sU -sT ",iplist, nmap_result_file)
     329  else:
     330    nmap_status = stored_status['nmap_status']
     331
     332  # Do SNMP discovery
     333  if opt_snmp_scan:
     334    snmp_status = do_snmp_scan(iplist, nmap_status, stored_status)
     335  else:
     336    snmp_status = stored_status
     337 
     338  # Store changed data to disk
     339  if opt_store_scan:
     340    stream = file(stored_status_file,'w')
     341    yaml.dump(snmp_status, stream, default_flow_style=False)
     342    print "## Stored data hints to '%s'" % stored_status_file
     343
     344  # Finally generated status
     345  generate_status(configs, snmp_status)
     346  print "# Took %s seconds to complete" % (datetime.now() - start_time).seconds
    289347
    290348
Note: See TracChangeset for help on using the changeset viewer.