1. #!/bin/python3
    2. import xlrd, os, json, requests, sys
    3. 参考zabbix API 4.0版本:https://www.zabbix.com/documentation/4.0/zh/manual/api
    4. class zabbixtools:
    5. url = 'http://xxx.xxx.xxx.xx/zabbix/api_jsonrpc.php'
    6. head = {'Content-Type': 'application/jsonrequest'}
    7. # 获取认证id
    8. def user_login(self):
    9. data = {
    10. "jsonrpc": "2.0",
    11. "method": "user.login",
    12. "params": {
    13. "user": "Admin",
    14. "password": "zabbix"
    15. },
    16. "id": 1,
    17. "auth": None
    18. }
    19. try:
    20. request_auth = requests.post(self.url, headers=self.head, data=json.dumps(data))
    21. request_auth_json = request_auth.json()
    22. auth = request_auth_json['result']
    23. except Exception as e:
    24. return '0'
    25. return auth
    26. ##创建主机组
    27. def hostgroup_create(self):
    28. file = sys.argv[2]
    29. with xlrd.open_workbook(file) as fb:
    30. sheet = fb.sheet_by_name('Sheet1')
    31. for i in range(1, sheet.nrows):
    32. group = sheet.row_values(i)[2]
    33. data = json.dumps({
    34. "jsonrpc": "2.0",
    35. "method": "hostgroup.create",
    36. "params": {
    37. "name": group
    38. },
    39. "auth": self.user_login(),
    40. "id": 1
    41. })
    42. groups_create = requests.post(self.url, headers=self.head, data=data)
    43. result = groups_create.json()
    44. print(result)
    45. # 获取主机组id
    46. def hostgroup_get(self, hostGroupName):
    47. data = json.dumps({
    48. "jsonrpc": "2.0",
    49. "method": "hostgroup.get",
    50. "params": {
    51. "output": "extend",
    52. "filter": {
    53. "name": hostGroupName
    54. }
    55. },
    56. "auth": self.user_login(),
    57. "id": 1,
    58. })
    59. response = requests.get(url=self.url, headers=self.head, data=data)
    60. return response.json()
    61. # 获取监控主机列表
    62. def get_hosts(self):
    63. data = {
    64. "jsonrpc": "2.0",
    65. "method": "host.get",
    66. "params": {
    67. "output": ["hostid", "host"], "selectInterfaces": ["interfaceid", "ip"]},
    68. "id": 2,
    69. "auth": self.user_login()
    70. }
    71. request_host = requests.post(self.url, headers=self.head, data=json.dumps(data))
    72. request_host_json = request_host.json()
    73. return request_host_json
    74. # 创建主机
    75. def create_hosts(self):
    76. file = sys.argv[2]
    77. print("创建主机")
    78. with xlrd.open_workbook(file) as fb:
    79. sheet = fb.sheet_by_name('Sheet1')
    80. for i in range(1, sheet.nrows):
    81. hostname = sheet.row_values(i)[0]
    82. hostip = sheet.row_values(i)[1]
    83. groupid_list = self.hostgroup_get(sheet.row_values(i)[2])['result']
    84. for groupid in groupid_list:
    85. templateid = int(sheet.row_values(i)[3])
    86. ####################################
    87. data = {
    88. "jsonrpc": "2.0",
    89. "method": "host.create", "params": {"host": hostip, "interfaces": [
    90. {"type": 1, "main": 1, "useip": 1, "ip": hostip, "dns": "", "port": "10050"}],
    91. "groups": [{"groupid": groupid['groupid']}],
    92. "templates": [{"templateid": templateid}],
    93. "inventory_mode": 0,
    94. "inventory": {"macaddress_a": "01234",
    95. "macaddress_b": "56768"},
    96. "name": hostname
    97. },
    98. "auth": self.user_login(),
    99. "id": 1
    100. }
    101. request_create = requests.post(self.url, headers=self.head, data=json.dumps(data))
    102. request_create_json = request_create.json()
    103. print(request_create_json)
    104. # 导入模板
    105. def zbx_export(self):
    106. fb = open(sys.argv[2], encoding='utf8').read()
    107. data_export = {
    108. "jsonrpc": "2.0",
    109. "method": "configuration.import",
    110. "params": {
    111. "format": "xml",
    112. "rules": {
    113. "applications": {"createMissing": True, "deleteMissing": True},
    114. "valueMaps": {"createMissing": True, "updateExisting": True},
    115. "groups": {"createMissing": True},
    116. "graphs": {"createMissing": True},
    117. "screens": {"createMissing": True},
    118. "templateScreens": {"createMissing": True},
    119. "triggers": {"createMissing": True, "updateExisting": True},
    120. "templates": {"createMissing": True},
    121. "items": {"createMissing": True,
    122. "updateExisting": True, "deleteMissing": True}
    123. },
    124. "source": fb},
    125. "auth": self.user_login(),
    126. "id": 1
    127. }
    128. request_export = requests.post(self.url, headers=self.head, data=json.dumps(data_export))
    129. request_export_json = request_export.json()
    130. return request_export_json
    131. def main():
    132. if len(sys.argv) == 3:
    133. if (sys.argv[1] == 'delete' or sys.argv[1] == 'create' or sys.argv[1] == 'export') and os.path.isfile(
    134. sys.argv[2]):
    135. auths = zabbixtools()
    136. if auths == 0:
    137. print('获取认证令牌失败..请检查提交数据的准确性')
    138. return '0'
    139. # 获取认证令牌
    140. print('-------------')
    141. print('获取用户认证令牌auth:%s' % auths.user_login())
    142. if sys.argv[1] == 'create':
    143. #添加主机组
    144. print('添加主机log:%s' % auths.hostgroup_create())
    145. # 添加监控主机
    146. print('-------------')
    147. print('添加主机log:%s' % auths.create_hosts())
    148. if sys.argv[1] == 'export':
    149. # 导入模板
    150. print('-------------')
    151. print('导入模板log:%s' % auths.zbx_export())
    152. else:
    153. pass
    154. #获取线上监控主机列表
    155. print('--------------')
    156. hostlist = auths.get_hosts()['result']
    157. for i in hostlist:
    158. i['ip'] = i['interfaces'][0]['ip']
    159. del i['interfaces']
    160. print('目前监控主机列表:%s' % (i))
    161. else:
    162. print('执行失败.Usage: /bin/python3 %s delete/create/export target_file' % (sys.argv[0]))
    163. else:
    164. print('执行失败.Usage: /bin/python3 %s delete/create/export target_file' % (sys.argv[0]))
    165. return '0'
    166. if __name__ == '__main__':
    167. main()

    xlsx文件:

    image.png

    执行:
    image.png