利用ZABBIX進行服務器自動巡檢並導出報表

實現思路

主要是利用zabbix的api來對數據進行獲取處理,實現思路以下:
利用ZABBIX進行服務器自動巡檢並導出報表git

  1. zabbix提供了豐富的api,能夠根據此api獲取zabbix得主機信息,監控項ID,監控項的趨勢數據和歷史數據
  2. 首先根據主機組ID獲取組內的全部主機信息,包括主機名和IP地址
  3. 循環主機組內的主機ID,並在循環裏再嵌套一個根據監控項鍵值獲取監控項ID的請求
  4. 根據獲取到的監控項ID分別獲取歷史數據和趨勢數據
  5. 將歷史數據和趨勢數據的值寫到一個字典裏,並把循環以後的全部字典添加到列表中
  6. 將列表中的信息寫入到Excel中,把腳本放到定時任務中定時執行

定義獲取的時間間隔

x=(datetime.datetime.now()-datetime.timedelta(minutes=120)).strftime("%Y-%m-%d %H:%M:%S")
y=(datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
def timestamp(x,y):
    p=time.strptime(x,"%Y-%m-%d %H:%M:%S")
    starttime = str(int(time.mktime(p)))
    q=time.strptime(y,"%Y-%m-%d %H:%M:%S")
    endtime= str(int(time.mktime(q)))
    return starttime,endtime

根據主機組ID獲取主機信息

def get_hosts(groupids,auth):
    data ={
            "jsonrpc": "2.0",
             "method": "host.get",
             "params": {
             "output": [ "name"],
             "groupids": groupids,
             "filter":{
                 "status": "0"
             },
             "selectInterfaces": [   
                        "ip"
                    ],
            },
            "auth": auth,  # theauth id is what auth script returns, remeber it is string
            "id": 1
        }
    gethost=requests.post(url=ApiUrl,headers=header,json=data)
    return json.loads(gethost.content)["result"]

根據獲取到的主機信息構建循環,獲取主機監控項的數據

獲取歷史數據

host=[]
    print(hosts)
    for i in hosts:
        item1=[]
        item2=[]
        #print(i)
        dic1={}
        for j in ['vfs.fs.size[C:,total]','vm.memory.size[total]','system.cpu.num']:
            data={
                "jsonrpc": "2.0",
                "method": "item.get",
                "params": {
                    "output": [
                        "itemid"

                    ],
                    "search": {
                        "key_": j  
                    },
                    "hostids": i['hostid']
                },
                "auth":auth,
                "id": 1
            }
            getitem=requests.post(url=ApiUrl,headers=header,json=data)
            item=json.loads(getitem.content)['result']

            hisdata={
                "jsonrpc":"2.0",
                "method":"history.get",
                "params":{
                    "output":"extend",                    
                    "time_from":timestamp[0],
                    #"time_till":timestamp[1],
                    "history":0,
                    "sortfield": "clock",
                    "sortorder": "DESC",
                    "itemids": '%s' %(item[0]['itemid']),
                    "limit":1
                },
                "auth": auth,
                "id":1
                }
            gethist=requests.post(url=ApiUrl,headers=header,json=hisdata)
            hist=json.loads(gethist.content)['result']
            item1.append(hist)

獲取趨勢數據

for j in ['vfs.fs.size[C:,used]','vm.memory.size[used]','system.cpu.load']:
            data={
                "jsonrpc": "2.0",
                "method": "item.get",
                "params": {
                    "output": [
                        "itemid"

                    ],
                    "search": {
                        "key_": j  
                    },
                    "hostids": i['hostid']
                },
                "auth":auth,
                "id": 1
            }
            getitem=requests.post(url=ApiUrl,headers=header,json=data)
            item=json.loads(getitem.content)['result']

            trendata={
                "jsonrpc":"2.0",
                "method":"trend.get",
                "params":{
                    "output": [
                        "itemid",
                        "value_max",
                        "value_avg"
                    ],                    
                    "time_from":timestamp[0],
                    "time_till":timestamp[1],
                    "itemids": '%s' %(item[0]['itemid']),
                    "limit":1
                },
                "auth": auth,
                "id":1
                }
            gettrend=requests.post(url=ApiUrl,headers=header,json=trendata)
            trend=json.loads(gettrend.content)['result']
            item2.append(trend)

對獲取到的數據進行處理,並導出到csv文件中

dic1['Hostname']=i['name']
        dic1['IP']=i['interfaces'][0]['ip']
        dic1['磁盤C:Total(B)']=round(float(item1[0][0]['value'])/1024**3,2)
        dic1['磁盤最大C:Used(B)']=round(float(item2[0][0]['value_max'])/1024**3,2)
        dic1['內存Total(B)']=round(float(item1[1][0]['value'])/1024**3,2)
        dic1['內存最大Used(B)']=round(float(item2[1][0]['value_max'])/1024**3,2)
        dic1['內存平均used(B)']=round(float(item2[1][0]['value_avg'])/1024**3,2)
        dic1['CPU負載最大值']=item2[2][0]['value_max']
        dic1['CPU負載平均值']=item2[2][0]['value_avg']
        dic1['CPU 核數']=item1[2][0]['value']
        x = time.localtime(int(item1[2][0]['clock']))
        item1[2][0]['clock'] = time.strftime("%Y-%m-%d %H:%M:%S", x)
        dic1['clock']=item1[2][0]['clock']
        host.append(dic1)  
        print(item)
    print(host)
    return host       
def writecsv(getitem1):
    with open('data.csv','w',encoding='utf-8-sig') as f:
        #f.write(codecs.BOM_UTF8)
        writer = csv.DictWriter(f,csvheader)
        writer.writeheader()
        for row in getitem1:
            writer.writerow(row)

實現效果以下:

利用ZABBIX進行服務器自動巡檢並導出報表

完整代碼能夠訪問github地址:「https://github.com/sunsharing-note/zabbix/blob/master/xunjian_auto.py
zabbix API地址:https://www.zabbix.com/documentation/4.0/zh/manual/api/reference/history/getgithub


歡迎各位關注我的公號「沒有故事的陳師傅」
利用ZABBIX進行服務器自動巡檢並導出報表json

相關文章
相關標籤/搜索