update_dhcp.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. #!/usr/local/bin/python2
  2. #
  3. # Copyright (c) 2017-2019 Joe Clarke <jclarke@cisco.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. # 1. Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. # notice, this list of conditions and the following disclaimer in the
  13. # documentation and/or other materials provided with the distribution.
  14. #
  15. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  16. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  19. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25. # SUCH DAMAGE.
  26. import json
  27. import requests
  28. from requests.packages.urllib3.exceptions import InsecureRequestWarning
  29. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  30. import sys
  31. import re
  32. from netaddr import IPAddress
  33. import CLEUCreds
  34. IDF_CNT = 98
  35. FIRST_IP = 31
  36. LAST_IP = 253
  37. DHCP_BASE = 'https://dc1-dhcp.ciscolive.network:8443/web-services/rest/resource/Scope'
  38. DHCP_TEMPLATE = {
  39. "optionList": {
  40. "OptionItem": []
  41. }
  42. }
  43. HEADERS = {
  44. 'authorization': CLEUCreds.JCLARKE_BASIC,
  45. 'accept': 'application/json',
  46. 'content-type': 'application/json'
  47. }
  48. def mtoc(mask):
  49. return IPAddress(mask).netmask_bits()
  50. if __name__ == '__main__':
  51. if len(sys.argv) != 2:
  52. sys.stderr.write("usage: {} INPUT_FILE\n".format(sys.argv[0]))
  53. sys.exit(1)
  54. contents = None
  55. try:
  56. fd = open(sys.argv[1], 'r')
  57. contents = fd.read()
  58. fd.close()
  59. except Exception as e:
  60. sys.stderr.write("Failed to open {}: {}\n".format(sys.argv[1], str(e)))
  61. sys.exit(1)
  62. for row in contents.split('\n'):
  63. row = row.strip()
  64. if re.search(r'^#', row):
  65. continue
  66. if row == '':
  67. continue
  68. [vlan, mask, name, policy] = row.split(',')
  69. if vlan == '' or mask == '' or name == '' or policy == '':
  70. sys.stderr.write("Skipping malformed row '{}'\n".format(row))
  71. continue
  72. start = 1
  73. cnt = IDF_CNT
  74. if mask == '255.255.0.0':
  75. start = 0
  76. cnt = 0
  77. for i in range(start, cnt + 1):
  78. prefix = 'IDF-{}'.format(str(i).zfill(3))
  79. if i == 0:
  80. prefix = 'CORE'
  81. scope = ('{}-{}'.format(prefix, name)).upper()
  82. ip = '10.{}.{}.0'.format(vlan, i)
  83. octets = ['10', vlan, str(i), '0']
  84. roctets = list(octets)
  85. roctets[3] = '254'
  86. url = '{}/{}'.format(DHCP_BASE, scope)
  87. response = requests.request(
  88. 'GET', url, headers=HEADERS, verify=False)
  89. if response.status_code != 404:
  90. sys.stderr.write("Scope {} already exists: {}\n".format(
  91. scope, response.status_code))
  92. continue
  93. template = {'optionList': {'OptionItem': []}}
  94. if mask == '255.255.0.0':
  95. roctets[2] = '255'
  96. template['optionList']['OptionItem'].append(
  97. {'number': '3', 'value': '.'.join(roctets)})
  98. sipa = list(octets)
  99. sipa[3] = str(FIRST_IP)
  100. eipa = list(octets)
  101. eipa[3] = str(LAST_IP)
  102. if mask == '255.255.0.0':
  103. eipa[2] = '255'
  104. sip = '.'.join(sipa)
  105. eip = '.'.join(eipa)
  106. rlist = {'RangeItem': [{'end': eip, 'start': sip}]}
  107. cidr = mtoc(mask)
  108. payload = {'embeddedPolicy': template, 'name': scope, 'policy': policy,
  109. 'rangeList': rlist, 'subnet': '{}/{}'.format(ip, cidr), 'tenantId': '0', 'vpnId': '0'}
  110. try:
  111. response = requests.request('PUT', url, data=json.dumps(
  112. payload), headers=HEADERS, verify=False)
  113. response.raise_for_status()
  114. except Exception as e:
  115. sys.stderr.write("Error adding scope {} ({}/{}) with range sip:{} eip:{}: {} ({})\n".format(
  116. scope, ip, cidr, sip, eip, response.text, str(e)))
  117. sys.stderr.write("Request: {}\n".format(
  118. json.dumps(payload, indent=4)))
  119. continue