Zabbix Python API 應用實戰

    做監控的同學應該知道,公司IDC機房經常有上架、下架、報修和報廢的服務器。如果服務器數量很多的時候很容易造成監控遺漏。
    大的互聯網公司把監控系統和CMDB(資產管理系統|配置管理數據庫系統)集成在一起,當上架一臺新機器的時候CMDB裏面會記錄相關的信息,Zabbix根據CMDB裏面信息自動Link相關的模塊,添加|刪除監控。很多小的公司沒有資產管理系統,但作爲監控的負責人應該每天知道上架了哪些新的機器,確保能添加到Zabbix監控裏面。
    首先給大家說一下腳本思路:
1)通過Nmap工具掃描網段,掃描出已經使用的IP地址。
2)通過Nmap檢測已經掃描IP的3389或者22端口是否開放,可以判斷那些事windows機器,那些是Linux機器。
3)Linux下面通過ssh + hostname命令找出Linux主機名。
4)Windows下面通過nmblookup -A 命令找出Windows主機名。
5)用Python腳本讀掃描結果文件,把主機名寫到列表裏面。
6)用Zabbix python API 調用已經監控的主機名,寫到列表裏面。
7)兩個列表取交集,用for循環判斷哪些主機名沒有監控。
8)發郵件通知監控負責人。

    下面我分享一下我寫的Python寫的腳本,其中scan_machine.sh是我調用的用Shell寫的關於Nmap掃描的腳本,scan_hostname.log是Nmap掃描的結果,裏面內容是IP 主機名。

#!/usr/bin/env python
#create by:sfzhang 20140820
#coding=utf-8
import os,sys
import json
import urllib2
import datetime,time
from urllib2 import URLError
nmap_cmd = "/shell/machine/scan_machine.sh"
def runCmd(command):
    global mail_cmd
    mail_cmd = '''mail -s "Report on not monitor Hosts of Zabbix" shifeng_zhang88 < /shell/machine/result/result.txt'''
    return os.system(command)
runCmd(nmap_cmd)
def nmap_host():
    hostiplst = []
    hostnamelst = []
    f = file('/shell/machine/result/scan_hostname.log')
    for line in f.readlines():
        hostip = line.split()[0]
        hostname = line.split()[1]
        hostiplst.append(hostip)
        hostnamelst.append(hostname)
    hostnamelst.sort()
    #print hostiplst
    return hostnamelst
    f.close()
def zabbix_host():
    zabbixhostlst= []
    #based url and required header
    url = "http://192.168.161.128/api_jsonrpc.php"
    header = {"Content-Type": "application/json"}
    #request json
    data = json.dumps(
    {  
    "jsonrpc": "2.0",
      "method": "host.get",
      "params":{
          "output":["hostid","name"],
         "filter":{"host":""}
    },    
    #auth id
    "auth":"Zabbix Auth ID",
    "id": 1,
    })
    #create request object
    request = urllib2.Request(url,data)
    for key in header:    
    request.add_header(key,header[key])
    #get host list
    try:
    result = urllib2.urlopen(request)
    except URLError as e:
    print "The server could not fulfill the request.",e.reason
    else:
        reponse = json.loads(result.read())
    result.close()
    #print "Number of Hosts:",len(reponse['result'])
    for host in reponse['result']:
            #print "Host ID:",host['hostid'],"Host Name:",host['name']
            zbxhosts=host['name']
            zabbixhostlst.append(zbxhosts)
        zabbixhostlst.sort()
        return zabbixhostlst    
def main():
    nmaphostlst = nmap_host()  
    zbxhostlst = zabbix_host()  
    diff = list(set(nmaphostlst) ^ set(zbxhostlst))  
    content = "\n"
    nomonitorlst = [] 
    if len(diff) != 0:  
        for host in diff:  
            if host in nmaphostlst:  
                nomonitorlst.append(host)
                
    else:  
        sys.exit()
    #print zbxhostlst
    string = '\n'.join(nomonitorlst)
    f = file('/shell/machine/result/result.txt','w')
    f.write(string)
    f.flush()
    f.close()
    runCmd(mail_cmd)
if __name__ == "__main__":  
    main()

   把腳本添加到crontab,每臺會收到關於那些主機沒有添加監控的信息。

wKiom1QWnH2TqA4TAACr-PgcC_U866.jpg    

    總結:

     1)Zabbix API相關信息可以查看官方詳細資料,看不懂英文的可以參考下面這篇文檔。http://paperplane.ruhoh.com/zabbix/intro-to-zabbix-api/

     2)通過該腳本可以知道那些主機沒有添加監控,希望對大家有幫助,如果有更好的解決方法歡迎多多交流。    
    






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章