1 #coding:utf-8 2 #给定主机IP获取一段时间内cpu的均值和峰值并写入文件(txt,可以跑完后直接把后缀名改为csv以表格形式打开);需要指定IP文件 3 import requests 4 import json 5 import csv 6 import time 7 8 def get_token(): 9 data = { 10 "jsonrpc": "2.0", 11 "method": "user.login", 12 "params": { 13 "user": username, 14 "password": password 15 }, 16 "id": 0 17 } 18 r = requests.get(zaurl, headers=header, data=json.dumps(data)) 19 auth = json.loads(r.text) 20 return auth["result"] 21 22 def item_get(token, host, itemkey): 23 data = { 24 "jsonrpc": "2.0", 25 "method": "item.get", 26 "params": { 27 "host": host, 28 "search": { 29 "key_": itemkey 30 }, 31 }, 32 "auth": token, 33 "id": 1 34 } 35 36 request = requests.post(zaurl, data=json.dumps(data), headers=header) 37 dict = json.loads(request.content) 38 # print(dict) 39 return dict['result'][0]['itemid'] 40 41 def getdata(token,itemid, start, stop): 42 data = { 43 "jsonrpc": "2.0", 44 "method": "history.get", 45 "params": { 46 "output": "extend", 47 "itemids": itemid, 48 "history": 0, 49 "time_from":start, 50 "time_till":stop 51 }, 52 "id": 2, 53 "auth": token, 54 55 } 56 request = requests.post(zaurl, headers=header, data=json.dumps(data)) 57 dict = json.loads(request.content) 58 print(dict) 59 return dict['result'] 60 61 def timecovert(stringtime): 62 timeArray = time.strptime(stringtime, "%Y-%m-%d %H:%M:%S") 63 timeStamp = int(time.mktime(timeArray)) 64 return timeStamp 65 66 67 68 if __name__ == "__main__": 69 zaurl = "http://xx.xx.xx.xx/zabbix/api_jsonrpc.php" 70 header = {"Content-Type": "application/json"} 71 username = "xxxx" 72 password = "xxxx" 73 hostfile="ip.txt" 74 token = get_token() 75 starttime = "2019-10-27 00:00:00" 76 stoptime = "2019-10-29 00:00:00" 77 start = timecovert(starttime) 78 stop = timecovert(stoptime) 79 #生成一个txt文件 80 datafile = "D:\生产\工作\IP\\data.txt" 81 fdata = open(datafile,'w') 82 with open(hostfile, "r") as f: 83 f1 = f.readlines() 84 for ips in f1: 85 host = ips.replace('\n', '').strip() 86 # 修改参数 87 #以下例子为cpu 88 itemkey = "system.cpu.util[,user]"]" 89 itemid = item_get(token, host, itemkey) 90 data = getdata(token,itemid,start,stop) 91 if data: 92 valuelist = [] 93 for i in data: 94 valuelist.append(float(i["value"])) 95 avge = sum(valuelist)/len(valuelist) 96 max1 = max(valuelist) 97 fdata.write(host + ',' + str(round(avge,2)) + ',' + str(round(max1,2)) + '\n') 98 # print (host, avge, max1) 99 else: 100 print (host) 101 fdata.close()