IT技術互(hu)動交流平jiao)/h4>

五分11选5官网

作者︰zhangke  發布日期︰2020-04-02 15:01:31

思路︰

python netsnmp模(mo)塊采集交換機SNMP信息(xi),通過pyzabbix 連(lian)接(jie)Zabbix API 自動生成帶有端口描述信息(xi)的graph

 

測試(shi)環境(jing) python2.7

軟件包(bao)︰

net-snmp-5.4.4.tar.gz

pyzabbix

net-snmp編(bian)譯(yi)參數

 

 

cd net-snmp-5.4.4./configure --with-python-modules --prefix=/usr/local/net-snmp --enable-developer-enable-sharedmake && make installcd pythonpython2.7 setup.py install

安裝pyzabbix

 

pip install pyzabbix

 

 

Zabbix API item.create 好像不支持創(chuang)建以(yi)SNMP的方法來chuang)唇 模(mo) yi)這(zhe)邊(bian)以(yi)以(yi)low level discovery方法來采集交換機的端口, 這(zhe)邊(bian)事先手動創(chuang)建以(yi)low level discove

wKioL1NObQDQyY4wAAC_U2hqLwo568.jpg

 

wKioL1NObWjAXRhsAAFavlmtkrI002.jpg

wKiom1NObt3RNKuGAAJuVLc4QE0336.jpg

wKioL1NOcRDi39KmAAOQoAxhRFI081.jpg

 

wKiom1NOcXXxE57xAAMOiT6KVm8401.jpg

 

 

#!/usr/bin/env python2.7import netsnmpimport osfrom pyzabbix import ZabbixAPIimport reimport sys#import itertoolsclass SnmpSession(object): #snmp采集的數據 def __init__(self,oid='ifDescr',Version=2,DestHost='lcoalhost',Community=''):                  a,b=os.popen4('snmpwalk -v 2c -c %s %s %s' % (Community,DestHost,oid)) oid_value=[] for x in b:# print x.split('.')[1].split(' ')[0]  oid_value.append(x.split('.')[1].split(' ')[0])# print oid_value ifDescr=[] ifAlias=[] ifHCInOctets=[] ifHCOutOctets=[] for x in oid_value:  ifDescr.append('ifDescr.%s' % x)  ifAlias.append('ifAlias.%s' % x)  ifHCInOctets.append('ifHCInOctets.%s' % x)  ifHCOutOctets.append('ifHCOutOctets.%s' % x)                 # print ifDescr# print ifAlias# print ifHCInOctets# print ifHCOutOctets if oid == 'ifDescr':  self.oids=ifDescr if oid == 'ifAlias':  self.oids=ifAlias if oid == 'ifHCInOctets':  slef.oids='ifHCInOctets' if oid == 'ifHCOutOctets':  self.oids=ifHCOutOctets# print self.oids self.oid=oid self.Version=Version self.DestHost=DestHost self.Community=Community                 def query(self): try:  result=netsnmp.snmpwalk(self.oid,Version=self.Version,DestHost=self.DestHost,Community=self.Community)  ifDescr_d={}  for x in zip(self.oids,list(result)):   ifDescr_d[x[0]]=x[1]#  print ifDescr_d  if len(ifDescr_d) == 0:   sys.exit(2)  return ifDescr_d except:  print 'switch Oid or ip is problem'  sys.exit(3)  #print sys.exc_info() # print result                 class zabbix(object): #連(lian)接(jie)zabbix的主(zhu)模(mo)塊 def __init__(self,hostname,Community,swich_ip,columns,name,graph,screen): self.server = 'http://10.0.100.10/zabbix' #填你zabbix server的uri  self.user = 'admin' #填你zabbix 的賬(zhang)號  self.passwd = 'admin' #填你zabbix 的密碼(ma)# self.ip = ip# self.host = host self.hostname = hostname# self.oid = oid self.Community = Community self.swich_ip = swich_ip  self.columns = columns self.dynamic = 0 self.name = name self.graph = graph self.screen = screen                                                    def __login(self): #登錄  zapi = ZabbixAPI(self.server)  zapi.login(self.user,self.passwd) return zapi def __get_host(self): #獲(huo)取主(zhu)機的id號 list_host=self.__login().host.get(output='extend',filter={'host':self.hostname,})  #print list_host return list_host[0]['hostid'] def __get_item(self): #獲(huo)取主(zhu)機的所有item  list_item=self.__login().item.get(output='extend',hostids=self.__get_host())  itemids={}  for x in list_item:#   print x['name'],x['itemid']   itemids[(x['name'])]=x['itemid']#  break#  print itemids  return itemids                 def __graph_create(self): #創(chuang)建繪圖 items=self.__get_item() #print items desc=SnmpSession(oid='ifDescr',DestHost=self.swich_ip,Community=self.Community).query() alias=SnmpSession(oid='ifAlias',DestHost=self.swich_ip,Community=self.Community).query()# print alias.values() port_desc={} for x in zip(desc.values(),alias.values()):  port_desc[x[0]]=x[1]# print port_desc                  group_items={}  for x in desc.values(): # print x  aa=[]  for y in items.keys():  #print y  if re.search(x,y):   aa.append(items[y])  group_items[x]=aa # print group_items desc_and_port={} for x in port_desc.keys():  for y in group_items.keys():  if re.search(x,y): #  print y,port_desc[x],group_items[y]   desc_and_port['%s (%s)' % ( y,port_desc[x] )]=group_items[y]                  #   self.__login().graph.create(# print desc_and_port for x in desc_and_port.keys():  self.__login().graph.create(gitems=[{    "itemid":desc_and_port[x][0], #下面你可以(yi)調整繪圖的大小和線條(tiao)的顏色,這(zhe)邊(bian)創(chuang)建了一(yi)個(ge)出去的流量和輸入(ru)的流量    "drawtype":"0",    "sortorder":"0",    "color":"0000CC",    "yaxisside":"0",    "calc_fnc":"2",    "type":"0",    "periods_cnt":"5"    },    {    "itemid":desc_and_port[x][1],    "drawtype":"0",    "sortorder":"1",    "color":"00CC00",    "yaxisside":"0",    "calc_fnc":"2",    "type":"0",    "periods_cnt":"5"    }],    name=x,    width="900",    height="200",    yaxismin="0.0000",    yaxismax="3.0000",   #  templateid="0",    show_work_period="1",    show_triggers="1",    graphtype="0",    show_legend="1",    show_3d="0",    percent_left="0.0000",    percent_right="0.0000",    ymin_type="0",    ymax_type="0",    ymin_itemid="0",    ymax_itemid="0") def __get_graph(self): #獲(huo)取所有的繪圖,過濾掉(diao)你不需要的繪圖,帶入(ru)下面的screen graphs=[] list_graph=self.__login().graph.get(output='extend',hostids=self. __get_host()) for x in list_graph: # print x['graphid']  if not re.search('Vlanif',x['name'].split(' ')[0]):  if not re.search('LoopBack',x['name'].split(' ')[0]):   if not re.search('NULL',x['name'].split(' ')[0]):   if not re.search('Ethernet0/0/0',x['name'].split(' ')[0]):    print x['name'].split(' ')[0],x['graphid']    graphs.append(x['graphid'])                                   graph_list=[] x = 0  y = 0 for graph in graphs:#   print "x is " + str(x)#   print "y is " + str(y)   graph_list.append({     "resourcetype":'0', #     "resourceid": graph,     "width": "500",     "height": "100",     "x": str(x),     "y": str(y),     "colspan": "0",     "rowspan": "0",     "elements": "0",     "valign": "0",     "halign": "0",     "style": "0",     "url": "",     "dynamic": str(self.dynamic)     })   x += 1#   print type(x)#   print type(self.columns)   if x == int(self.columns):    x = 0    y += 1 #print graph_list  return graph_list def __create_screen(self): #創(chuang)建screen 需要帶入(ru)上面的方法  graphids=self.__get_graph()  columns = int(self.columns)  if len(graphids) % self.columns == 0:   vsize = len(graphids) / self.columns  else:   vsize = (len(graphids) / self.columns) + 1#  print graphids  self.__login().screen.create(name=self.name,hsize=self.columns,vsize=vsize,screenitems=graphids)                  def __exists_screen(self): #判斷screen是否存在,存在就退出  list_exists=self.__login().screen.exists(name=self.name)  if list_exists:   print '%s is exists' % self.name   sys.exit(1) def __exists_host(self): #判斷host是否不存在 不存在就退出  list_exists=self.__login().host.exists(host=self.hostname)  if not list_exists:   print "%s is not exists" % self.hostname   sys.exit(1) #return graphs## def __del_graph(self): #刪jing)嬙急ㄈㄏ抻形侍餉揮惺迪 a=self.__get_graph()# self.__login().graph.delete(a) def main(self):  #主(zhu)函數 會調用上面的方法 self.__exists_host() self.__exists_screen()# self.__get_host()# self.__get_item() if self.graph:  self.__graph_create()# self.__get_graph()# self.__del_graph() if self.screen:  self.__create_screen()if __name__ == '__main__': from optparse import OptionParser #生成幫助文檔 parser = OptionParser() parser.add_option('-G', dest='graphname',   help='Zabbix Host create new screen ') parser.add_option('-H', dest='hostname',   help='Zabbix Host to create screen from') parser.add_option('-c', dest='columns', type=int,   help='number of columns in the screen') parser.add_option('-C', dest='Community',  help='switch SNMP community') parser.add_option('-s', dest='switch',  help='switch ip') parser.add_option('-x', dest='execute',action='store_true',default=False,  help='create host graph') parser.add_option('-n',dest='screen',action='store_true',default=False,  help='whether create zabbix screen')                  options,args=parser.parse_args() a=zabbix(hostname=options.hostname,Community=options.Community,swich_ip=options.switch,columns=options.columns,name=options.graphname,graph=options.execute,screen=options.screen) a.main()

 

wKioL1NOdZny-TucAAFit0XRoig699.jpg

-G 生成新(xin)的screen

-H 自己定義的主(zhu)機名

wKioL1NOdpWiw74yAADQWHN-1Es425.jpg

-c 需要生成的列

wKiom1NOdw7CpLI_AACeGKXmR9s899.jpg

-s 交換的ip地址(zhi), (這(zhe)邊(bian)交換的ip地址(zhi)可能會跟你的 Host name 不同)

 

-x 是否開(kai)啟創(chuang)建graph的功能

 

-n 是否開(kai)啟screen 功能

 

注意(yi) -C -s 如果沒有填正(zheng)確的信息(xi) 腳本會報錯,這(zhe)個(ge)後(hou)續改下

 

 

 

例子︰ ./switch_desc_port_and_create_screen.py -G tom -H 10.0.10.100 -c 2 -C tom -s 10.0.10.100 -x True -n True

 

 

wKioL1NOd3fAAbBYAAVwVLKmI20699.jpg

Graph出來啦

 

 

wKioL1NOd9_ThOEqAAAUoCa-WgA760.jpg

Screen 也出來了

 

 

wKiom1NOeE2hVwhVAAE79_Gr064142.jpg

 

這(zhe)邊(bian)出來的是你剛才low level discovery 定義的

 

wKiom1NOeKbRsxjpAACLnbJAi24783.jpg

 

 

現在你可以(yi)改name了

 

wKioL1NOeKvSUwxMAAEFHPvBK7Q147.jpg

 

wKiom1NOeRWAs27DAAFBJmSw0dE006.jpg

這(zhe)邊(bian)也就改變了

Tag標(biao)簽︰Zabbix  交換機  
  • 五分11选5官网

About IT165 - 廣告服務 - 隱私聲明 - 版(ban)權申明 - 免責條(tiao)款 - 網站jing)贗/a> - 網友投稿 - 聯系(xi)方式
本站內容來自于(yu)互(hu)聯網,僅供用于(yu)網絡(luo)技術學習,學習中請遵循相(xiang)關法律法規
五分11选5官网 | 下一页