snmp discovery with

2023-01-31 04:01:18 snmp discovery

 snmp discovery with python

  1. #!/usr/bin/env Python 
  2. from processing import Process, Queue, Pool 
  3. import time 
  4. import subprocess 
  5. from IPy import IP 
  6. import sys 
  7. from snmp import Snmp 
  8.  
  9. q = Queue() 
  10. oq = Queue() 
  11. #ips = IP("10.0.1.0/24") 
  12. ips = ["10.10.10.28","10.10.10.29","10.10.10.30","10.10.10.31","10.10.10.32","10.10.10.33","10.10.10.34","10.10.10.35","10.10.10.36","10.10.10.37","10.10.10.38","10.10.10.39"] 
  13. num_workers = 10 
  14.  
  15. class HostRecord(object): 
  16.     """Record for Hosts""" 
  17.     def __init__(self, ip=None, Mac=None, snmp_response=None): 
  18.         self.ip = ip 
  19.         self.mac = mac 
  20.         self.snmp_response = snmp_response 
  21.     def __repr__(self): 
  22.         return "[Host Record('%s','%s','%s')]" % (self.ip, 
  23.                                             self.mac, 
  24.                                             self.snmp_response) 
  25.  
  26. def f(i,q,oq): 
  27.     while True: 
  28.         time.sleep(.1) 
  29.         if q.empty(): 
  30.             sys.exit() 
  31.             print "Process Number: %s Exit" % i 
  32.         ip = q.get() 
  33.         print "Process Number: %s" % i 
  34.         ret = subprocess.call("ping -c 1 %s" % ip, 
  35.                         shell=True, 
  36.                         stdout=open('/dev/null', 'w'), 
  37.                         stderr=subprocess.STDOUT) 
  38.         if ret == 0: 
  39.             print "%s: is alive" % ip 
  40.             oq.put(ip) 
  41.         else: 
  42.             print "Process Number: %s didn't find a response for %s " % (i, ip) 
  43.             pass 
  44.  
  45. def snmp_query(i,out): 
  46.     while True: 
  47.         time.sleep(.1) 
  48.         if out.empty(): 
  49.             sys.exit() 
  50.             print "Process Number: %s" % i 
  51.         ipaddr = out.get() 
  52.         s = Snmp() 
  53.         h = HostRecord() 
  54.         h.ip = ipaddr 
  55.         h.snmp_response = s.query() 
  56.         print h 
  57.         return h 
  58. try: 
  59.     q.putmany(ips) 
  60.  
  61. finally: 
  62.     for i in range(num_workers): 
  63.         p = Process(target=f, args=[i,q,oq]) 
  64.         p.start() 
  65.     for i in range(num_workers): 
  66.         pp = Process(target=snmp_query, args=[i,oq]) 
  67.         pp.start() 
  68.  
  69. print "main process joins on queue" 
  70. p.join() 
  71. #while not oq.empty(): 
  72. #    print "Validated", oq.get() 
  73.  
  74.  
  75. print "Main Program finished" 

 

相关文章