Guest User

Untitled

a guest
Jul 23rd, 2020
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.57 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. import argparse
  4. import logging
  5. import time
  6. import os
  7. import json
  8. import xml.dom.minidom
  9. from zabbix.api import ZabbixAPI
  10. from sys import exit
  11. from datetime import datetime
  12. import subprocess
  13. import configparser
  14.  
  15. parser = argparse.ArgumentParser(description='This is a simple tool to export zabbix templates')
  16. parser.add_argument('--templates', help='Name of specific template to export',default='All')
  17. parser.add_argument('--out-dir', help='Directory to output templates to. You can set it to repopath in case of using copytogit',default='/zabbixconfigsbackup/templates/zabbix_sps_msk_templates_backup')
  18. parser.add_argument('--debug', help='Enable debug mode, this will show you all the json-rpc calls and responses', action="store_true")
  19. parser.add_argument('--url', help='URL to the zabbix server (example: https://monitor.example.com/zabbix)')
  20. parser.add_argument('--user', help='The zabbix api user')
  21. parser.add_argument('--password', help='The zabbix api password')
  22. parser.add_argument('--copytogit', help='Set No if you dont want to copy to git', default = 'Yes')
  23. parser.add_argument('--conf', help='Set config file for urls and password',default='/zabbixexternalscripts/apiscriptsconf.conf')
  24. args = parser.parse_args()
  25.  
  26. if args.debug:
  27. logging.basicConfig(level = logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
  28. logger = logging.getLogger(__name__)
  29.  
  30. def main():
  31. global args
  32. global parser
  33. config = configparser.ConfigParser()
  34. if args.conf != 'No' :
  35. if args.conf == '/zabbixexternalscripts/apiscriptsconf.conf' :
  36. config.read('/zabbixexternalscripts/apiscriptsconf.conf')
  37.  
  38. if (args.conf != '/zabbixexternalscripts/apiscriptsconf.conf'):
  39. conffile = args.conf
  40. if conffile.is_file() :
  41. config.read(conffile)
  42. else :
  43. print "Config file doesnt exists. Set --conf=Yes or create config file"
  44. exit(5)
  45. url = config.get("zabbix","zabbix_url")
  46. user = config.get("zabbix","zabbix_api_reader")
  47. password = config.get("zabbix","zabbix_api_reader_password")
  48. if args.conf == 'No':
  49. if None == args.url :
  50. print "Error: Missing --url\n\n"
  51. exit(2)
  52.  
  53. if None == args.user :
  54. print "Error: Missing --user\n\n"
  55. exit(3)
  56.  
  57. if None == args.password :
  58. print "Error: Missing --password\n\n"
  59. exit(4)
  60. url = args.url
  61. user = args.user
  62. password = args.password
  63.  
  64. if False == os.path.isdir(args.out_dir):
  65. os.mkdir(args.out_dir)
  66.  
  67. zabbix = ZabbixTemplates( url, user, password )
  68.  
  69. zabbix.exportTemplates(args)
  70.  
  71. if args.copytogit == "Yes" :
  72. now=datetime.now()
  73. commitcomment=now.strftime("%d.%m.%Y %H:%M")
  74. os.chdir(args.out_dir)
  75. subprocess.call(['git', 'add','-A'])
  76. subprocess.call(['git', 'commit','-am',commitcomment])
  77. subprocess.call(['git', 'push','origin','master'])
  78. if args.copytogit == "No" :
  79. print "Templates is not copying to git"
  80. class ZabbixTemplates:
  81.  
  82. def __init__(self,_url,_user,_password):
  83. self.zapi = ZabbixAPI(url=_url, user=_user, password=_password)
  84.  
  85. def exportTemplates(self,args):
  86. request_args = {
  87. "output": "extend"
  88. }
  89.  
  90. if args.templates != 'All':
  91. request_args.filter = {
  92. "host": [args.tempaltes]
  93. }
  94.  
  95. result = self.zapi.do_request('template.get',request_args)
  96. if not result['result']:
  97. print "No matching host found for '{}'".format(hostname)
  98. exit(-3)
  99.  
  100. if result['result']:
  101. for t in result['result']:
  102. dest = args.out_dir+'/'+t['host']+'.xml'
  103. self.exportTemplate(t['templateid'],dest)
  104.  
  105. def exportTemplate(self,tid,oput):
  106.  
  107. print "tempalteid:",tid," output:",oput
  108. args = {
  109. "options": {
  110. "templates": [tid]
  111. },
  112. "format": "xml"
  113. }
  114.  
  115. result = self.zapi.do_request('configuration.export',args)
  116. template = xml.dom.minidom.parseString(result['result'].encode('utf-8'))
  117. date = template.getElementsByTagName("date")[0]
  118. # We are backing these up to git, steralize date so it doesn't appear to change
  119. # each time we export the templates
  120. date.firstChild.replaceWholeText('2016-01-01T01:01:01Z')
  121. f = open(oput, 'w+')
  122. f.write(template.toprettyxml().encode('utf-8'))
  123. f.close()
  124.  
  125.  
  126. if __name__ == '__main__':
  127. main()
Add Comment
Please, Sign In to add comment