一、通過查詢zabbix db的方式通過主機IP獲取到所需要的graphid(比如CPU監控圖、內存監控圖等,每個圖對應一個graphid),最后將圖片保存到本地
注:該graph必須要在 screen中存在才可以獲取到相應的graphid,否則graphid為空。
import urllib2,requests,cookielib,urllib #定義登錄地址 login_url = 'http://10.16.2.4/zabbix/index.php' #定義登錄所需要用的信息,如用戶名、密碼等,使用urllib進行編碼 login_data = urllib.urlencode({ "name": 'admin', "password": 'password', "autologin": 1, "enter": "Sign in"}) #設置一個cookie處理器,它負責從服務器下載cookie到本地,並且在發送請求時帶上本地的cookie cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) opener.open(login_url,login_data).read() #這部分沒有具體寫 sql_hostid = select hostid from hosts where host='10.16.3.2'; #通過host查詢hostid sql_itemid = select itemid,`name`,key_ from items where hostid='10251' #通過hostid查詢itemid,通過key_過濾性能監視器 sql_graphid = select graphid from graphs_items where itemid='33712' #通過itemid查詢對應的graphid graph_args = urllib.urlencode({ "graphid":'3346', "width":'400', "height":'156', "stime":'20160511000000', #圖形開始時間 "period":'86400'}) graph_url = 'http://10.16.2.4/zabbix/chart2.php' print graph_args #返回格式:width=400&screenid=28&graphid=4769&period=86400&height=156 data = opener.open(graph_url,graph_args).read() # print data file=open('d:\\zaa225.png','wb') file.write(data) file.flush() file.close()
二、通過zabbix API獲取graphID,最后將圖片保存到本地以當前日期為名的文件夾中,實現多線程並發:
# -*- coding: UTF-8 -*- import urllib2,json,cookielib,urllib,datetime,os,threading from urllib2 import Request, urlopen, URLError, HTTPError global auth_code,zabbix_url,zabbix_header,login_url,graph_url,login_data,pic_save_path_dir,yesterday9,opener #zabbix接口地址、登錄地址、圖片地址 zabbix_url="http://10.16.2.4/zabbix/api_jsonrpc.php" login_url = 'http://10.16.2.4/zabbix/index.php' graph_url = 'http://10.16.2.4/zabbix/chart2.php' zabbix_header = {"Content-Type":"application/json"} zabbix_user = "admin" zabbix_pass = "password" auth_code = "" auth_data = json.dumps({ "jsonrpc":"2.0", "method":"user.login", "params": { "user":zabbix_user, "password":zabbix_pass }, "id":0 }) #定義登錄所需要用的信息,如用戶名、密碼等,使用urllib進行編碼 login_data = urllib.urlencode({ "name": zabbix_user, "password": zabbix_pass, "autologin": 1, "enter": "Sign in"}) #新建以當天日期為名的文件夾保存圖片 today = datetime.datetime.now().date().strftime('%Y%m%d') pic_save_path_dir= os.path.join('d:\\pic',today ) #修改圖片保存位置 if not os.path.exists(pic_save_path_dir): os.makedirs(pic_save_path_dir) #定義graph的starttime參數,從前一天的9:00開始 yesterday = (datetime.datetime.now()-datetime.timedelta(days=1)) yesterday9 = datetime.datetime(yesterday.year,yesterday.month,yesterday.day,9).strftime('%Y%m%d%H%M%S') #登錄zabbix,設置一個cookie處理器,負責從服務器下載cookie到本地,並且在發送請求時帶上本地的cookie cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) opener.open(login_url,login_data)#.read() request = urllib2.Request(zabbix_url,auth_data) for key in zabbix_header: request.add_header(key,zabbix_header[key]) try: result = urllib2.urlopen(request) except HTTPError, e: print 'The server couldn\'t fulfill the request, Error code: ', e.code except URLError, e: print 'We failed to reach a server.Reason: ', e.reason else: response=json.loads(result.read()) #print response result.close() #判斷SESSIONID是否在返回的數據中 if 'result' in response: auth_code=response['result'] else: print response['error']['data'] def Http_access(data): request = urllib2.Request(zabbix_url,data) for key in zabbix_header: request.add_header(key,zabbix_header[key]) result = urllib2.urlopen(request) response = json.loads(result.read()) # print result.read() # print response result.close() if len(response['result']) > 0: return response['result'][0] def get_hostid(ip): get_host_data = '' if len(auth_code) <> 0: get_host_data = json.dumps({ "jsonrpc": "2.0", "method": "host.get", "params": { "output": "extend", "filter": { "host": [ ip, ] } }, "auth": auth_code, "id": 1 }) return get_host_data def get_itemid(hostid,itemtype): get_item_data = '' if (len(auth_code) <> 0) and (hostid is not None): get_item_data = json.dumps({ "jsonrpc": "2.0", "method": "item.get", "params": { "output": "extend", "hostids": hostid, "search":{ "name": itemtype }, "sortfield": "name" }, "auth": auth_code, "id": 1 }) return get_item_data def get_graphid(itemid): get_graph_data = '' if (len(auth_code) <> 0) and (itemid is not None): get_graph_data = json.dumps({ "jsonrpc": "2.0", "method": "graphitem.get", "params": { "output": "extend", "expandData": 1, "itemids": itemid }, "auth": auth_code, "id": 1 }) return get_graph_data def pic_save(ip,name,graphid): graph_args = urllib.urlencode({ "graphid":graphid, "width":'400', #定義圖片寬度 "height":'156', #定義圖片高度 "stime":yesterday9, #圖形開始時間 "period":'86400'}) #定義時長,取1天的數據 data = opener.open(graph_url,graph_args).read() #pic_save_path = pic_save_path_dir + ip + '-' + name +'.png' picname = ip + '-' + name +'.png' pic_save_path = os.path.join(pic_save_path_dir,picname) file=open(pic_save_path,'wb') file.write(data) #file.flush() file.close() #多線程並發調用該函數 def pic_save_th(ip): #根據ip獲取hostid host_data = get_hostid(ip) host_result = Http_access(host_data) if host_result is not None: #判斷該IP是否在zabbix中存在 hostid = host_result['hostid'] #根據監視器名稱獲取相應的itemid cpuname = 'CPU Usage' memoryname = 'Memory - Memory available' diskname = 'Disk - Current Disk Queue Length' netcard = 'Traffic for Public Receive' item_cpu = get_itemid(hostid,cpuname) item_memory = get_itemid(hostid,memoryname) item_disk = get_itemid(hostid,diskname) item_netcard = get_itemid(hostid,netcard) itemid_cpu = Http_access(item_cpu)['itemid'] itemid_memory = Http_access(item_memory)['itemid'] itemid_disk = Http_access(item_disk)['itemid'] itemid_netcard = Http_access(item_netcard)['itemid'] #根據itemid獲取相應的graphid graphdata_cpu = get_graphid(itemid_cpu) graphdata_memory = get_graphid(itemid_memory) graphdata_disk = get_graphid(itemid_disk) graphdata_netcard = get_graphid(itemid_netcard) graphid_cpu = Http_access(graphdata_cpu)['graphid'] graphid_memory = Http_access(graphdata_memory)['graphid'] graphid_disk = Http_access(graphdata_disk)['graphid'] graphid_netcard = Http_access(graphdata_netcard)['graphid'] print ip#,graphid_cpu,graphid_memory,graphid_disk,graphid_netcard #調用pic_save函數保存圖片到本地 pic_save(ip,cpuname,graphid_cpu) pic_save(ip,memoryname,graphid_memory) pic_save(ip,diskname,graphid_disk) pic_save(ip,netcard,graphid_netcard) else: print '%s doesnot exist in zabbix' %ip #定義線程數控制函數,num表示每次並發的線程數 def lstg(num,lst): #定義每段的個數num l = len(lst) g = l/num #取分成幾組 last = l%num #判斷是否有剩余的數 lstn = [] if num >= l: lstn.append(lst) else: for i in range(g): i=i+1 n=i*num m=n-num lstn.append(lst[m:n]) if last <> 0: lstn.append(lst[-last:]) return lstn # serverip=['10.160.26.30','10.160.26.31','10.160.26.32'] # for ip in serverip: # pic_save_th(ip) if __name__ =='__main__': #定義線程數量 tnum = 5 serverips=['10.160.26.30','10.160.26.31','10.160.26.32','10.160.31.31','10.160.31.32','10.160.31.36','10.160.34.250','10.160.34.251','192.168.200.250','192.168.200.251'] for ips in lstg(tnum,serverips): threads=[] for ip in ips: #創建並啟動進程 t = threading.Thread(target=pic_save_th,args=(ip,)) #t.setName('th-'+ ip) t.setDaemon(True) t.start() threads.append(t) #等待每個線程結束 for t in threads: #print t.name,t.is_alive(),ctime() t.join()