#/usr/bin/python

#coding=utf-8

import json,urllib2,time,os,re,shutil

from docx import Document

from docx.shared import Pt

from docx.shared import Inches

from docx.oxml.ns import qn

from selenium import webdriver


period='604800'#需要获取的监控周期,单位是秒

zabbix_server='http://zabbix.net'

url = "http://zabbix.net/api_jsonrpc.php"

header = {"Content-Type":"application/json"}

zabbix_user = 'xxxx'

zabbix_passwd = 'xxxx'

document = Document()


def http_access():

   data = json.dumps(

      {

      "jsonrpc": "2.0",

      "method": "user.login",

      "params": {

      "user": zabbix_user,

      "password": zabbix_passwd

   },

   "id": 0

   })

   # 将请求头部重新编码

   request = urllib2.Request(url,data)

   for key in header:

      request.add_header(key,header[key])

   # 获取登录认证密钥。

   try:

      result = urllib2.urlopen(request)

   except URLError as e:

      print "Auth Failed, Please Check Your Name AndPassword:",e.code

   else:

      response = json.loads(result.read())

      result.close()

   return response['result']

  

def get_groups():

   

   data = json.dumps(

   {

      "jsonrpc":"2.0",

      "method":"hostgroup.get",

      "params":{

          "output":["groupid","name"],

      },

      "auth":auth_code, # theauth id is what auth script returns, remeber it is string

      "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:

      if hasattr(e, 'reason'):

          print 'We failed to reach a server.'

          print 'Reason: ', e.reason

      elif hasattr(e, 'code'):

          print 'The server could not fulfill the request.'

          print 'Error code: ', e.code

   else:

      groups = {}

      response = json.loads(result.read())

      result.close()

      print "Number Of Hosts: ", len(response['result'])

      #print response

      for group in response['result']:

          print "ID",group['groupid'],"\t",group['name']  

          groups.update({group['groupid']:group['name']})

   return groups

  

def get_graphid():

   data = json.dumps(

   {

       "jsonrpc": "2.0",

       "method": "graph.get",

       "params": {

           "output": "graphid",

           "groupids": groupid

       },

       "auth": auth_code,

       "id": 1

   })

   request = urllib2.Request(url,data)

   for key in header:

      request.add_header(key,header[key])

# get graph list

   try:

      result = urllib2.urlopen(request)

   except URLError as e:

      if hasattr(e, 'reason'):

          print 'We failed to reach a server.'

          print 'Reason: ', e.reason

      elif hasattr(e, 'code'):

          print 'The server could not fulfill the request.'

          print 'Error code: ', e.code

   else:

      graphids=[]

      response = json.loads(result.read())

      for r in response['result']:

          graphids.append(r['graphid'])

      result.close()

      print "Number Of Graphs: ", len(response['result'])

   return graphids

  

if __name__ =='__main__':

   auth_code = http_access()

   groups = get_groups()

   groupid = raw_input("select wanted group:")

   date=raw_input('Input start time:') + '000000'#zabbix时间参数格式是20171123000000

   graphids = get_graphid()

   pic_save_path_dir= os.path.join('E:\\python\\report',groups[groupid]) #修改图片保存位置

   if not os.path.exists(pic_save_path_dir):

      os.makedirs(pic_save_path_dir)

  

   driver=webdriver.Chrome()

   for graph in graphids:

      driver.get('%s/charts.php?fullscreen=1&graphid=%s&stime=%s&period=%s'%(zabbix_server,graph,date,period))  

      time.sleep(1)

      driver.get_screenshot_as_file(pic_save_path_dir + "\\" + graph +".png") 

   

   for i in  os.listdir(pic_save_path_dir):#遍历目录下的图片,并全部添加到Word文件里面

     os.chdir(pic_save_path_dir)

     document.add_picture(i, width=Inches(6))#

   document.save(u'E:\\python\\report\\' + groups[groupid] +'.docx')

运行效果:

   

 我才学Python2个月,写得有点乱,大神勿喷。