You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

localhostgen.py 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. #! /usr/bin/env python3
  2. import argparse
  3. import json
  4. import os
  5. from time import time
  6. import psycopg2
  7. import sys
  8. import re
  9. class LocalHostGen:
  10. db_config = None
  11. db_instance = None
  12. dhcpd_replace_string = "# %%HOST%%"
  13. def __init__(self, db_config):
  14. self.db_config = db_config
  15. def connect(self):
  16. self.db_instance = psycopg2.connect("dbname='%s' user='%s' host='%s' password='%s' port='%s'" %
  17. (self.db_config['database'], self.db_config['username'],
  18. self.db_config['host'], self.db_config['password'],
  19. self.db_config['port']))
  20. def disconnect(self):
  21. if self.db_instance is not None:
  22. self.db_instance.close()
  23. self.db_instance = None
  24. def get_domain_id(self, domain):
  25. cur = self.db_instance.cursor()
  26. cur.execute("SELECT id FROM domains WHERE name='%s'" % domain)
  27. id = cur.fetchone()
  28. cur.close()
  29. if id is not None:
  30. return id[0]
  31. return None
  32. def get_record_id(self, record):
  33. cur = self.db_instance.cursor()
  34. cur.execute("SELECT id FROM records WHERE name='%s'" % record)
  35. id = cur.fetchone()
  36. cur.close()
  37. if id is not None:
  38. return id[0]
  39. return None
  40. def get_record_content(self, record):
  41. cur = self.db_instance.cursor()
  42. cur.execute("SELECT content FROM records WHERE name='%s'" % record)
  43. content = cur.fetchone()
  44. cur.close()
  45. if content is not None:
  46. return content[0]
  47. return None
  48. def get_reversed_ip(self, ip):
  49. return '.'.join(reversed(ip.split(".")))
  50. def get_reverse_domain_record(self, reverse_domain, ip):
  51. reversed_ip = self.get_reversed_ip(ip)
  52. reverse_domain_part = reversed_ip
  53. while not reverse_domain.startswith(reverse_domain_part):
  54. reverse_domain_part = reverse_domain_part[reverse_domain_part.index('.') + 1:]
  55. return reversed_ip[0:len(reversed_ip) - len(reverse_domain_part) - 1]
  56. def insert_host(self, domain, record, content, ttl, type):
  57. record_full = "%s.%s" % (record, domain)
  58. record_id = self.get_record_id(record_full)
  59. if record_id is None:
  60. domain_id = self.get_domain_id(domain)
  61. cur = self.db_instance.cursor()
  62. cur.execute("INSERT INTO records (domain_id, name, type, content, ttl, prio, change_date,"
  63. "disabled, ordername, auth) VALUES ('%s', '%s', '%s', '%s', '%s', '0', '%s', 'f', NULL, 't')"
  64. "RETURNING id" % (domain_id, record_full, type, content, ttl, int(time())))
  65. record_id = cur.fetchone()[0]
  66. cur.close()
  67. self.db_instance.commit()
  68. return record_id
  69. def delete_host(self, record):
  70. cur = self.db_instance.cursor()
  71. cur.execute("DELETE FROM records WHERE name='%s' RETURNING id" % record)
  72. record_id = cur.fetchone()
  73. cur.close()
  74. self.db_instance.commit()
  75. if record_id is not None:
  76. return record_id[0]
  77. return None
  78. def remove_host_dhcp(self, host, dhcpd_file_content):
  79. return re.sub(" *host +%s +\{[^}]+} *\n" % host, "", dhcpd_file_content)
  80. def create_host(self, domain, reverse_domain, host, ip, mac, ttl, dhcpd_file_path, wildcard):
  81. record_full = "%s.%s" % (host, domain)
  82. host_wildcard = "*.%s" % host
  83. reverse_domain_record = self.get_reverse_domain_record(reverse_domain, ip)
  84. self.insert_host(domain, host, ip, ttl, 'A')
  85. if wildcard:
  86. self.insert_host(domain, host_wildcard, record_full, ttl, 'CNAME')
  87. self.insert_host(reverse_domain, reverse_domain_record, record_full, ttl, 'PTR')
  88. with open(dhcpd_file_path, "r") as f:
  89. dhcpd_file_content = f.read()
  90. dhcpd_host_config = "host %s {\n" \
  91. " hardware ethernet %s;\n" \
  92. " fixed-address %s;\n" \
  93. " }" % (host, mac, record_full)
  94. dhcpd_file_content = self.remove_host_dhcp(host, dhcpd_file_content)
  95. dhcpd_file_content = dhcpd_file_content.replace(self.dhcpd_replace_string, "%s\n %s" %
  96. (dhcpd_host_config, self.dhcpd_replace_string))
  97. with open(dhcpd_file_path, "w") as f:
  98. f.write(dhcpd_file_content)
  99. def remove_host(self, domain, reverse_domain, host, dhcpd_file_path):
  100. record_full = "%s.%s" % (host, domain)
  101. record_full_wildcard = "*.%s" % record_full
  102. ip = self.get_record_content(record_full)
  103. if ip is not None:
  104. reverse_domain_record = self.get_reverse_domain_record(reverse_domain, ip)
  105. reverse_domain_record_full = "%s.%s" %(reverse_domain_record, reverse_domain)
  106. self.delete_host(record_full_wildcard)
  107. self.delete_host(record_full)
  108. self.delete_host(reverse_domain_record_full)
  109. with open(dhcpd_file_path, "r") as f:
  110. dhcpd_file_content = f.read()
  111. dhcpd_file_content = self.remove_host_dhcp(host, dhcpd_file_content)
  112. with open(dhcpd_file_path, "w") as f:
  113. f.write(dhcpd_file_content)
  114. def eprint(*args, **kwargs):
  115. print(*args, file=sys.stderr, **kwargs)
  116. def main():
  117. parser = argparse.ArgumentParser(description='Manage local hosts for PowerDNS and isc-dhcp-server')
  118. parser.add_argument('--host', help='The host to manage', required=True)
  119. parser.add_argument('--config', dest='config', default='/etc/localhostgen/localhostgen.json',
  120. help='Configuration file path')
  121. parser.add_argument('--create', help='Create a host', action='store_true')
  122. parser.add_argument('--remove', help='Remove the host', action='store_true')
  123. parser.add_argument('--mac', help='The MAC address of the new host')
  124. parser.add_argument('--ip', help='The IP address of the new host')
  125. args = parser.parse_args()
  126. with open(args.config, "r") as f:
  127. config = json.load(f)
  128. host = args.host
  129. ip = args.ip
  130. mac = args.mac
  131. local_host_gen = LocalHostGen(config['database'])
  132. local_host_gen.connect()
  133. if args.create:
  134. if ip is None or mac is None:
  135. eprint("IP and MAC are required to create a host")
  136. exit(1)
  137. local_host_gen.create_host(config['dns']['domain'], config['dns']['reverseDomain'], host, ip, mac,
  138. config['dns']['recordTTL'], config['dhcpd']['filePath'], config['dns']['wildcard'])
  139. elif args.remove:
  140. local_host_gen.remove_host(config['dns']['domain'], config['dns']['reverseDomain'], host,
  141. config['dhcpd']['filePath'])
  142. local_host_gen.disconnect()
  143. os.system(config['dhcpd']['reloadCommand'])
  144. main()