Created
January 18, 2019 20:26
-
-
Save e0ne/0f9b83a549a2f39fc09230e98cab24e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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