Skip to content

Instantly share code, notes, and snippets.

@keyboardcrunch
Last active February 6, 2022 01:33
Show Gist options
  • Select an option

  • Save keyboardcrunch/56f4cda4532fe4bf72ac6d714f4b4b70 to your computer and use it in GitHub Desktop.

Select an option

Save keyboardcrunch/56f4cda4532fe4bf72ac6d714f4b4b70 to your computer and use it in GitHub Desktop.
helper script for netmaker, to inject netmaker peers into /etc/hosts
#!/usr/bin/python3
'''
script to merge netmaker clients from all bound networks into the
local system's hosts file.
'''
import subprocess
import json
HOST_FILE = '/etc/hosts'
NETCLIENT = '/usr/local/bin/netclient'
def get_netclient():
''' runs the netclient list command and creates a dict '''
client_config = {}
process = subprocess.Popen([NETCLIENT, 'list'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if stderr:
print(stderr)
else:
output = stdout.decode("utf-8")
nc_config = json.loads(output)
for item in nc_config["networks"]:
for client in item["peers"]:
client_config[client["private_ipv4"]] = client["name"]
return client_config
def write_config(netclient_config):
''' write new netclient data to hosts file '''
if isinstance(netclient_config, dict):
# clear netclient host data
host_config = open(HOST_FILE, 'r')
host_lines = host_config.readlines()
host_config.close()
try:
# check for previous config
start = host_lines.index('############ netclient_hosts ############\n')
try:
finish = host_lines.index('#########################################')
except ValueError:
finish = host_lines.index('#########################################\n') + 1
del host_lines[start:finish]
clean_config = host_lines
except ValueError:
clean_config = host_lines
# cleanup end of file spacing
cleaned = False
while cleaned is False:
if clean_config[-1] == ('\n'):
del clean_config[-1]
else:
cleaned = True
# append netclient current config
client_data = ['\n', '############ netclient_hosts ############\n']
for key, val in netclient_config.items():
line = "%s %s\n" % (key, val)
client_data.append(line)
client_data.append('#########################################\n')
new_config = clean_config + client_data
# write changes
host_config = open(HOST_FILE, 'w')
host_config.writelines(new_config)
host_config.close()
new_clients = get_netclient()
write_config(new_clients)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment