snmpclient.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #!/usr/bin/python2.7
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Sat Jul 28 12:34:00 2018
  5. @author: dufs
  6. """
  7. import sys
  8. import time
  9. import netsnmp
  10. import commands
  11. import logging
  12. import logging.config
  13. import ConfigParser
  14. import multiprocessing
  15. import databaseconn as dbcn
  16. #logging.config.fileConfig('conf/logging.conf')
  17. #logger = logging.getLogger(__name__)
  18. logger = logging.getLogger('autocheck.snmpclient')
  19. def snmp_query(host, oid, version=2):
  20. """
  21. snmpwalk
  22. """
  23. dev_ip=host[0]
  24. community=host[1]
  25. if oid[1]=='snmpdf':
  26. try:
  27. if version==2:
  28. v_version="2c"
  29. else:
  30. v_version=str(version)
  31. result = commands.getoutput("snmpdf -v " + v_version + " -c " + community + " " + dev_ip)
  32. logger.debug('exec snmpdf result: %s', str(result))
  33. result=tuple(result.split('\n'))
  34. status = 0
  35. except Exception as e:
  36. logger.error('get Exception : ' + str(e) , exc_info=True)
  37. result = None
  38. status = -1
  39. else:
  40. try:
  41. result = netsnmp.snmpwalk(oid[1], Version=version, DestHost=dev_ip, Community=community)
  42. logger.debug('exec snmpwalk oid[1] result: %s', str(result))
  43. result = tuple(result)
  44. status = 0
  45. except Exception, err:
  46. logger.error('get Exception : ' + str(e) , exc_info=True)
  47. result = None
  48. status = -1
  49. return (host, oid, status, result)
  50. def snmp_result(res):
  51. '''
  52. '''
  53. if res[2]==0:
  54. logger.debug("%s exec command '%s' success." %(res[0][0], res[1][1]))
  55. else:
  56. logger.debug("%s exec command '%s' failed." %(res[0][0], res[1][1]))
  57. snmp_resultSet.add(res)
  58. def snmp_result_save(resSet):
  59. '''
  60. '''
  61. if len(resSet)==0:
  62. return
  63. saveSet=set()
  64. for res in resSet:
  65. IP_ADDRESS=res[0][0]
  66. DEVICE_ID=res[0][2]
  67. oid=res[1][1]
  68. status=res[2]
  69. result=res[3]
  70. if status!=0:
  71. continue
  72. if len(result)==0:
  73. continue
  74. if oid=='ssCpuIdle':
  75. INSPECTION_INDEX='CPU_UTILIZATION'
  76. INSPECTION_OBJECT='cpu'
  77. INDEX_VALUE=100-int(result[0])
  78. TOTAL=''
  79. USED=''
  80. saveSet.add((IP_ADDRESS, DEVICE_ID, INSPECTION_INDEX, INSPECTION_OBJECT, INDEX_VALUE, TOTAL, USED))
  81. elif oid=='memTotalReal':
  82. INSPECTION_INDEX='MEM_UTILIZATION'
  83. INSPECTION_OBJECT=''
  84. INSPECTION_OBJECT='Mem'
  85. INDEX_VALUE=''
  86. TOTAL=int(result[0])
  87. USED=''
  88. for res1 in resSet:
  89. if IP_ADDRESS==res1[0][0] and DEVICE_ID==res1[0][2] and res1[1][1]=='memAvailReal':
  90. USED=TOTAL-int(res1[3][0])
  91. INDEX_VALUE=round(100*USED/TOTAL,2)
  92. saveSet.add((IP_ADDRESS, DEVICE_ID, INSPECTION_INDEX, INSPECTION_OBJECT, INDEX_VALUE, TOTAL, USED))
  93. elif oid=='snmpdf':
  94. INSPECTION_INDEX='DISK_UTILIZATION'
  95. for line in result:
  96. if line.startswith('Description'):
  97. continue
  98. if len(line.split())>5:
  99. INSPECTION_OBJECT=line.split()[0] + ' ' + line.split()[1]
  100. INDEX_VALUE=line.split()[5].replace('%','')
  101. TOTAL=line.split()[2]
  102. USED=line.split()[3]
  103. elif len(line.split())==5:
  104. INSPECTION_OBJECT=line.split()[0]
  105. INDEX_VALUE=line.split()[4].replace('%','')
  106. TOTAL=line.split()[1]
  107. USED=line.split()[2]
  108. else:
  109. continue
  110. saveSet.add((IP_ADDRESS, DEVICE_ID, INSPECTION_INDEX, INSPECTION_OBJECT, INDEX_VALUE, TOTAL, USED))
  111. logger.info('total %d result need to save', len(saveSet))
  112. if len(saveSet)==0:
  113. return 0
  114. v_sql='''insert into isp_autoinspection_test(ip_address,device_id,inspection_index,inspection_object,index_value,total,used,inspection_time,into_time) values(:x1, :x2, :x3, :x4, :x5, :x6, :x7, trunc(sysdate,'hh24'), sysdate)'''
  115. logger.info('exec result save sql : %s', v_sql)
  116. try:
  117. cf = ConfigParser.SafeConfigParser()
  118. cf.read('conf/autocheck.conf')
  119. db_url=cf.get('db', 'url')
  120. nls_lang=cf.get('db', 'nls_lang')
  121. except Exception as e:
  122. logger.error('parse config file error: ' + str(e) , exc_info=True)
  123. raise
  124. if len(nls_lang)==0:
  125. nls_lang='SIMPLIFIED CHINESE_CHINA.UTF8'
  126. try:
  127. dbclt=dbcn.DataBaseConn(db_url, nls_lang=nls_lang)
  128. except Exception as e:
  129. logger.error('connect db faild : ' + str(e) , exc_info=True)
  130. return -1
  131. for rlst in saveSet:
  132. try:
  133. dbclt.exec_sql(v_sql, rlst)
  134. except Exception as e:
  135. logger.error('connect db faild : ' + str(e) , exc_info=True)
  136. dbclt.conn.commit()
  137. dbclt.close_connect()
  138. logger.info('save result success')
  139. def snmp_batch_cmd(hostSet, oidSet):
  140. '''
  141. '''
  142. global snmp_resultSet
  143. snmp_resultSet=set()
  144. time_start=time.time()
  145. max_thread=100
  146. try:
  147. cf = ConfigParser.SafeConfigParser()
  148. cf.read('conf/autocheck.conf')
  149. max_thread=cf.getint('snmpclient', 'max_thread')
  150. except Exception as e:
  151. logger.error('parse config file error: ' + str(e) , exc_info=True)
  152. logger.debug('use defult : %d', max_thread)
  153. if len(hostSet)<=max_thread:
  154. pool_size=len(hostSet)
  155. else:
  156. pool_size=max_thread
  157. pool = multiprocessing.Pool(processes=pool_size)
  158. for host in hostSet:
  159. for oid in oidSet:
  160. pool.apply_async(snmp_query, (host, oid, ), callback=snmp_result)
  161. pool.close()
  162. pool.join()
  163. time_end=time.time()
  164. time_used=time_end-time_start
  165. logger.info("all sub-processes done, used time %d s" %time_used)
  166. snmp_result_save(snmp_resultSet)
  167. if __name__ == '__main__':
  168. logging.config.fileConfig("conf/logging.conf")
  169. #create logger
  170. logger = logging.getLogger("snmpclient")
  171. hostSet=set()
  172. hostSet.add(('183.222.102.82', 'SNMP_COMMUNITY', 100))
  173. hostSet.add(('183.222.102.14', 'SNMP_COMMUNITY', 101))
  174. oidSet=set()
  175. oidSet.add(('disk', 'snmpdf'))
  176. oidSet.add(('mem', 'memTotalReal'))
  177. oidSet.add(('mem', 'memAvailReal'))
  178. oidSet.add(('cpu', 'ssCpuIdle'))
  179. snmp_batch_cmd(hostSet, oidSet)