Skip to content

Instantly share code, notes, and snippets.

@e0ne
Created January 18, 2019 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save e0ne/0f9b83a549a2f39fc09230e98cab24e6 to your computer and use it in GitHub Desktop.
Save e0ne/0f9b83a549a2f39fc09230e98cab24e6 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
import glob
import json
DNSMASQ_PATH = '/var/lib/libvirt/dnsmasq/*.status'
HOSTS_PATH = '/etc/hosts'
COMMENT = '# libvirt instances\n'
vms = []
for f in glob.glob(DNSMASQ_PATH):
with open(f) as st_file:
data = json.load(st_file)
for vm in data:
if 'hostname' in vm:
vms.append((vm['ip-address'], vm['hostname']))
updated = False
hosts = []
with open(HOSTS_PATH, 'r') as f:
for line in f.readlines():
hosts.append(line)
if 'libvirt instances' in line:
updated = True
break
if not updated:
hosts.append('\n\n')
hosts.append(COMMENT)
for vm in vms:
hosts.append('{}\t{}\n'.format(vm[0], vm[1]))
with open(HOSTS_PATH, 'w') as f:
f.writelines(hosts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment