Skip to content

Instantly share code, notes, and snippets.

@patrickfuller
Last active August 4, 2024 05:00

Revisions

  1. patrickfuller revised this gist Jul 26, 2019. 1 changed file with 6 additions and 1 deletion.
    7 changes: 6 additions & 1 deletion alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -49,7 +49,12 @@
    r'mac-address ([:a-f0-9]+).*?}',
    re.MULTILINE | re.DOTALL)
    with sftp_client.open(paths['config']) as in_file:
    for match in regex.finditer(in_file.read()):
    cfg = in_file.read()
    try:
    cfg = cfg.decode('utf-8')
    except AttributeError:
    pass
    for match in regex.finditer(cfg):
    ip, mac = match.group(1), match.group(2)
    mac_map[mac] = ip

  2. patrickfuller revised this gist Jul 21, 2019. 1 changed file with 6 additions and 1 deletion.
    7 changes: 6 additions & 1 deletion alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -36,7 +36,12 @@
    r'hardware ethernet ([:a-f0-9]+);.*?}',
    re.MULTILINE | re.DOTALL)
    with sftp_client.open(paths['leases']) as in_file:
    for match in regex.finditer(in_file.read()):
    leases = in_file.read()
    try:
    leases = leases.decode('utf-8')
    except AttributeError:
    pass
    for match in regex.finditer(leases):
    ip, mac = match.group(1), match.group(2)
    mac_map[mac] = ip
    regex = re.compile(r'static-mapping [-a-f0-9]+ {.*' +
  3. patrickfuller revised this gist Dec 6, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -59,7 +59,7 @@
    current = in_file.read()
    except IOError:
    current = ''
    if conf and conf.strip() != current.strip():
    if conf.strip() != current.strip():
    print("Reloading dnsmasq.")
    with sftp_client.open('/tmp/dnsmasq', 'w') as out_file:
    out_file.write(conf)
  4. patrickfuller revised this gist Dec 6, 2017. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -58,8 +58,8 @@
    with sftp_client.open(paths['dnsmasq']) as in_file:
    current = in_file.read()
    except IOError:
    current = None
    if conf.strip() != current.strip():
    current = ''
    if conf and conf.strip() != current.strip():
    print("Reloading dnsmasq.")
    with sftp_client.open('/tmp/dnsmasq', 'w') as out_file:
    out_file.write(conf)
  5. patrickfuller revised this gist Aug 10, 2017. 1 changed file with 5 additions and 2 deletions.
    7 changes: 5 additions & 2 deletions alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -54,8 +54,11 @@
    if mac in mac_map])

    # Compare with current config. Update and reload if needed.
    with sftp_client.open(paths['dnsmasq']) as in_file:
    current = in_file.read()
    try:
    with sftp_client.open(paths['dnsmasq']) as in_file:
    current = in_file.read()
    except IOError:
    current = None
    if conf.strip() != current.strip():
    print("Reloading dnsmasq.")
    with sftp_client.open('/tmp/dnsmasq', 'w') as out_file:
  6. patrickfuller revised this gist Jun 27, 2017. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -18,10 +18,11 @@

    # Get alias-mac map through mongodb data store
    alias_map = {}
    db = pymongo.MongoClient(*paths['mongo']).ace
    for client in db.user.find({'name': {'$exists': True}}):
    db = pymongo.MongoClient(*paths['mongo'])
    for client in db.ace.user.find({'name': {'$exists': True}}):
    if re.sub(r'[-.]', '', client['name']).isalnum():
    alias_map[client['name']] = client['mac']
    db.close()

    # Connect to gateway to start configuration.
    client = paramiko.SSHClient()
  7. patrickfuller revised this gist Jun 27, 2017. 1 changed file with 2 additions and 3 deletions.
    5 changes: 2 additions & 3 deletions alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -20,7 +20,7 @@
    alias_map = {}
    db = pymongo.MongoClient(*paths['mongo']).ace
    for client in db.user.find({'name': {'$exists': True}}):
    if client['name'].replace('-', '').isalnum():
    if re.sub(r'[-.]', '', client['name']).isalnum():
    alias_map[client['name']] = client['mac']

    # Connect to gateway to start configuration.
    @@ -43,8 +43,7 @@
    r'mac-address ([:a-f0-9]+).*?}',
    re.MULTILINE | re.DOTALL)
    with sftp_client.open(paths['config']) as in_file:
    data = in_file.read()
    for match in regex.finditer(data):
    for match in regex.finditer(in_file.read()):
    ip, mac = match.group(1), match.group(2)
    mac_map[mac] = ip

  8. patrickfuller revised this gist Jun 27, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -10,7 +10,7 @@

    paths = {
    'mongo': ('localhost', 27117),
    'gateway': {'hostname': '192.168.1.1', 'username': 'patrickfuller'},
    'gateway': {'hostname': '192.168.1.1', 'username': 'user'},
    'leases': '/var/run/dhcpd.leases',
    'config': '/config/config.boot',
    'dnsmasq': '/etc/dnsmasq.d/dnsmasq.static.conf'
  9. patrickfuller revised this gist Jun 27, 2017. 1 changed file with 10 additions and 12 deletions.
    22 changes: 10 additions & 12 deletions alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -2,18 +2,15 @@
    When run in cron, automatically adds compliant alias names to local DNS.
    Use at your own risk.
    dhcpd.leases regex from
    https://stackoverflow.com/questions/36291553/
    parsing-dhcpd-leases-with-python-and-regex
    Patrick Fuller, 25 June 17
    """
    import re
    import paramiko
    import pymongo

    paths = {
    'mongo': ('localhost', 27117),
    'gateway': {'hostname': '192.168.1.1', 'username': 'user'},
    'gateway': {'hostname': '192.168.1.1', 'username': 'patrickfuller'},
    'leases': '/var/run/dhcpd.leases',
    'config': '/config/config.boot',
    'dnsmasq': '/etc/dnsmasq.d/dnsmasq.static.conf'
    @@ -23,7 +20,7 @@
    alias_map = {}
    db = pymongo.MongoClient(*paths['mongo']).ace
    for client in db.user.find({'name': {'$exists': True}}):
    if re.sub(r'[-.]', '', client['name']).isalnum():
    if client['name'].replace('-', '').isalnum():
    alias_map[client['name']] = client['mac']

    # Connect to gateway to start configuration.
    @@ -46,24 +43,25 @@
    r'mac-address ([:a-f0-9]+).*?}',
    re.MULTILINE | re.DOTALL)
    with sftp_client.open(paths['config']) as in_file:
    for match in regex.finditer(in_file.read()):
    data = in_file.read()
    for match in regex.finditer(data):
    ip, mac = match.group(1), match.group(2)
    mac_map[mac] = ip

    # Generate dnsmasq config file
    conf = '\n'.join(['address=/{}/{}'.format(alias, mac_map[mac])
    for alias, mac in sorted(alias_map.items())
    if mac in mac_map])
    conf = ''.join(['address=/{hn}/{ip}\n'.format(hn=alias, ip=mac_map[mac])
    for alias, mac in sorted(alias_map.items())
    if mac in mac_map])

    # Compare with current config. Update and reload if needed.
    with sftp_client.open(paths['dnsmasq']) as in_file:
    current = in_file.read()
    if conf != current.strip():
    if conf.strip() != current.strip():
    print("Reloading dnsmasq.")
    with sftp_client.open('/tmp/dnsmasq', 'w') as out_file:
    out_file.write(conf)
    client.exec_command('sudo cp /tmp/dnsmasq ' + paths['dnsmasq'])
    client.exec_command('sudo /etc/init.d/dnsmasq force-reload')
    finally:
    sftp_client.close()
    client.close()
    client.close()
  10. patrickfuller revised this gist Jun 27, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -23,7 +23,7 @@
    alias_map = {}
    db = pymongo.MongoClient(*paths['mongo']).ace
    for client in db.user.find({'name': {'$exists': True}}):
    if client['name'].replace('-', '').isalnum():
    if re.sub(r'[-.]', '', client['name']).isalnum():
    alias_map[client['name']] = client['mac']

    # Connect to gateway to start configuration.
  11. patrickfuller created this gist Jun 27, 2017.
    69 changes: 69 additions & 0 deletions alias_dns.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    """
    When run in cron, automatically adds compliant alias names to local DNS.
    Use at your own risk.
    dhcpd.leases regex from
    https://stackoverflow.com/questions/36291553/
    parsing-dhcpd-leases-with-python-and-regex
    """
    import re
    import paramiko
    import pymongo

    paths = {
    'mongo': ('localhost', 27117),
    'gateway': {'hostname': '192.168.1.1', 'username': 'user'},
    'leases': '/var/run/dhcpd.leases',
    'config': '/config/config.boot',
    'dnsmasq': '/etc/dnsmasq.d/dnsmasq.static.conf'
    }

    # Get alias-mac map through mongodb data store
    alias_map = {}
    db = pymongo.MongoClient(*paths['mongo']).ace
    for client in db.user.find({'name': {'$exists': True}}):
    if client['name'].replace('-', '').isalnum():
    alias_map[client['name']] = client['mac']

    # Connect to gateway to start configuration.
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(**paths['gateway'])
    sftp_client = client.open_sftp()
    try:
    # Get mac-ip map by reading DHCP leases and reservations from config files
    mac_map = {}
    regex = re.compile(r'lease ([0-9.]+) {.*?' +
    r'hardware ethernet ([:a-f0-9]+);.*?}',
    re.MULTILINE | re.DOTALL)
    with sftp_client.open(paths['leases']) as in_file:
    for match in regex.finditer(in_file.read()):
    ip, mac = match.group(1), match.group(2)
    mac_map[mac] = ip
    regex = re.compile(r'static-mapping [-a-f0-9]+ {.*' +
    r'?ip-address ([0-9.]+).*?' +
    r'mac-address ([:a-f0-9]+).*?}',
    re.MULTILINE | re.DOTALL)
    with sftp_client.open(paths['config']) as in_file:
    for match in regex.finditer(in_file.read()):
    ip, mac = match.group(1), match.group(2)
    mac_map[mac] = ip

    # Generate dnsmasq config file
    conf = '\n'.join(['address=/{}/{}'.format(alias, mac_map[mac])
    for alias, mac in sorted(alias_map.items())
    if mac in mac_map])

    # Compare with current config. Update and reload if needed.
    with sftp_client.open(paths['dnsmasq']) as in_file:
    current = in_file.read()
    if conf != current.strip():
    print("Reloading dnsmasq.")
    with sftp_client.open('/tmp/dnsmasq', 'w') as out_file:
    out_file.write(conf)
    client.exec_command('sudo cp /tmp/dnsmasq ' + paths['dnsmasq'])
    client.exec_command('sudo /etc/init.d/dnsmasq force-reload')
    finally:
    sftp_client.close()
    client.close()