python 调用zabbix api接口实现主机的增删改查

python

python程序调用zabbix系统的api接口实现对zabbix_server端主机的增删改查,使用相关功能时候,需要打开脚本中的相关函数。

函数说明:

zabbixtools()  调用zabbix api

template_get()  获取zabbix  server端已经配置的模板信息

hostgroup_get()  获取已经添加的主机组列表信息

host_get()   单个主机信息

host_del()  删除主机

host_create()  新建主机

get_grouphost()  获取某个组下面所有的主机信息

  1 #!/usr/bin/env python

2 # -*- coding: utf-8 -*-

3 import json

4 import urllib2

5 import sys

6 class zabbixtools:

7 def __init__(self):

8 self.url = "http://x.x.x.x/zabbix/api_jsonrpc.php"

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

10 self.authID = self.user_login()

11 def user_login(self):

12 data = json.dumps(

13 {

14 "jsonrpc": "2.0",

15 "method": "user.login",

16 "params": {

17 "user": "Admin",

18 "password": "xxxx"

19 },

20 "id": 0

21 })

22 request = urllib2.Request(self.url,data)

23 for key in self.header:

24 request.add_header(key,self.header[key])

25 try:

26 result = urllib2.urlopen(request)

27 except URLError as e:

28 print "Auth Failed, Please Check Your Name And Password:",e.code

29 else:

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

31 result.close()

32 authID = response['result']

33 return authID

34 def get_data(self,data,hostip=""):

35 request = urllib2.Request(self.url,data)

36 for key in self.header:

37 request.add_header(key,self.header[key])

38 try:

39 result = urllib2.urlopen(request)

40 except URLError as e:

41 if hasattr(e, 'reason'):

42 print 'We failed to reach a server.'

43 print 'Reason: ', e.reason

44 elif hasattr(e, 'code'):

45 print 'The server could not fulfill the request.'

46 print 'Error code: ', e.code

47 return 0

48 else:

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

50 result.close()

51 return response

52 def host_get(self,hostip):

53 #hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')

54 data = json.dumps(

55 {

56 "jsonrpc": "2.0",

57 "method": "host.get",

58 "params": {

59 "output":["hostid","name","status","host"],

60 "filter": {"host": [hostip]}

61 },

62 "auth": self.authID,

63 "id": 1

64 })

65 res = self.get_data(data)['result']

66 if (res != 0) and (len(res) != 0):

67 #for host in res:

68 host = res[0]

69 if host['status'] == '1':

70 print "\t","\033[1;31;40m%s\033[0m" % "Host_IP:","\033[1;31;40m%s\033[0m" %host['host'].ljust(15),'\t',"\033[1;31;40m%s\033[0m" % "Host_Name:","\033[1;31;40m%s\033[0m"% host['name'].encode('GBK'),'\t',"\033[1;31;40m%s\033[0m" % u'unmonitor'.encode('GBK')

71 return host['hostid']

72 elif host['status'] == '0':

73 print "\t","\033[1;32;40m%s\033[0m" % "Host_IP:","\033[1;32;40m%s\033[0m" %host['host'].ljust(15),'\t',"\033[1;32;40m%s\033[0m" % "Host_Name:","\033[1;32;40m%s\033[0m"% host['name'].encode('GBK'),'\t',"\033[1;32;40m%s\033[0m" % u'monitor'.encode('GBK')

74 return host['hostid']

75 print

76 else:

77 print '\t',"\033[1;31;40m%s\033[0m" % "Get Host Error or cannot find this host,please check !"

78 return 0

79 def get_grouphost(self):

80 groupid = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your groupid:')

81 data = json.dumps(

82 {

83 "jsonrpc":"2.0",

84 "method":"host.get",

85 "params":{

86 "output":["hostid","name","status","host"],

87 #"output": "extend",

88 "groupids":groupid,

89 },

90 "auth": self.authID,

91 "id":1,

92 })

93 res = self.get_data(data)

94 if 'result' in res.keys():

95 res = res['result']

96 if (res !=0) or (len(res) != 0):

97 print "\033[1;32;40m%s\033[0m" % "Number Of Hosts: ","\033[1;31;40m%d\033[0m" % len(res)

98 for host in res:

99 print "Host ID:",host['hostid'],"Visible name:",host['name'],"Host-status:",host['status'],"HostName:",host['host']

100 else:

101 print "The groupid does not exist, please check!"

102

103

104

105

106

107 def host_del(self):

108 hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')

109 hostid = self.host_get(hostip)

110 print hostid

111 if hostid == 0:

112 print '\t',"\033[1;31;40m%s\033[0m" % "This host cannot find in zabbix,please check it !"

113 sys.exit()

114 data = json.dumps(

115 {

116 "jsonrpc": "2.0",

117 "method": "host.delete",

118 "params": [hostid],

119 "auth": self.authID,

120 "id": 1

121 })

122 res = self.get_data(data)['result']

123 if 'hostids' in res.keys():

124 print "\t","\033[1;32;40m%s\033[0m" % "Delet Host:%s success !" % hostip

125 else:

126 print "\t","\033[1;31;40m%s\033[0m" % "Delet Host:%s failure !" % hostip

127 def hostgroup_get(self):

128 data = json.dumps(

129 {

130 "jsonrpc": "2.0",

131 "method": "hostgroup.get",

132 "params": {

133 "output": "extend",

134 },

135 "auth": self.authID,

136 "id": 1,

137 })

138 res = self.get_data(data)

139 if 'result' in res.keys():

140 res = res['result']

141 if (res !=0) or (len(res) != 0):

142 print "\033[1;32;40m%s\033[0m" % "Number Of Group: ","\033[1;31;40m%d\033[0m" % len(res)

143 for host in res:

144 print"\t","HostGroup_id:",host['groupid'],"\t","HostGroup_Name:",host['name'].encode('GBK')

145 else:

146 print "Get HostGroup Error,please check !"

147 def template_get(self):

148 data = json.dumps(

149 {

150 "jsonrpc": "2.0",

151 "method": "template.get",

152 "params": {

153 "output": "extend",

154 },

155 "auth": self.authID,

156 "id": 1,

157 })

158 res = self.get_data(data)#['result']

159 if 'result' in res.keys():

160 res = res['result']

161 if (res !=0) or (len(res) != 0):

162 print "\033[1;32;40m%s\033[0m" % "Number Of Template: ","\033[1;31;40m%d\033[0m" % len(res)

163 for host in res:

164 print"\t","Template_id:",host['templateid'],"\t","Template_Name:",host['name'].encode('GBK')

165 print

166 else:

167 print "Get Template Error,please check !"

168 def host_create(self):

169 hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Host_ip :')

170 #Visible_name = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Visible name :')

171 groupid = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Group_id :')

172 templateid = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Tempate_id :')

173 g_list=[]

174 t_list=[]

175 for i in groupid.split(','):

176 var = {}

177 var['groupid'] = i

178 g_list.append(var)

179 for i in templateid.split(','):

180 var = {}

181 var['templateid'] = i

182 t_list.append(var)

183 if hostip and groupid and templateid:

184 data = json.dumps(

185 {

186 "jsonrpc": "2.0",

187 "method": "host.create",

188 "params": {

189 "host": hostip,

190 "interfaces": [

191 {

192 "type": 1,

193 "main": 1,

194 "useip": 1,

195 "ip": hostip,

196 "dns": "",

197 "port": "10050"

198 }

199 ],

200 "groups": g_list,

201 "templates": t_list,

202 },

203 "auth": self.authID,

204 "id": 1,

205 })

206 res = self.get_data(data,hostip)

207 if 'result' in res.keys():

208 res = res['result']

209 if 'hostids' in res.keys():

210 print "\033[1;32;40m%s\033[0m" % "Create host success"

211 else:

212 print "\033[1;31;40m%s\033[0m" % "Create host failure: %s" % res['error']['data']

213 else:

214 print "\033[1;31;40m%s\033[0m" % "Enter Error: ip or groupid or tempateid is NULL,please check it !"

215 def main():

216 test = zabbixtools()

217 test.template_get()

218 test.hostgroup_get()

219 #test.host_get()

220 #test.host_del()

221 test.host_create()

222 #test.get_grouphost()

223 if __name__ == "__main__":

224 main()

以上是 python 调用zabbix api接口实现主机的增删改查 的全部内容, 来源链接: utcz.com/z/389393.html

回到顶部