Skip to content

Instantly share code, notes, and snippets.

@morsik
Created August 7, 2012 19:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save morsik/3288561 to your computer and use it in GitHub Desktop.
Save morsik/3288561 to your computer and use it in GitHub Desktop.
Perl libvirt net-edit with dhcp reload
#!/usr/bin/perl -w
# Author: Konrad "morsik" Mosoń <mosonkonrad@gmail.com>
# linked here: http://wiki.libvirt.org/page/Networking#Applying_modifications_to_the_network
use strict;
use warnings;
my $net = $ARGV[0];
if (!defined($net))
{
print "Usage: $0 <network>\n";
exit(1);
}
system('virsh', 'net-edit', $net);
my $re_mac = '[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}';
my $re_host = '[a-zA-Z0-9.-_]+';
my $re_ip4 = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}';
# format: <host mac='de:ad:be:ef:00:01' name='www.libvirt.org' ip='176.31.99.103' />
my $dhcpconf = "";
open(NET, "/etc/libvirt/qemu/networks/$net.xml");
foreach (<NET>)
{
if (/\s*<host\s+mac='($re_mac)'\s+name='($re_host)'\s+ip='($re_ip4)'\s*\/>/)
{
$dhcpconf .= "$1,$3,$2\n";
}
}
close(NET);
open(DHCP, ">", "/var/lib/libvirt/dnsmasq/$net.hostsfile");
print(DHCP $dhcpconf);
close(DHCP);
print "\033[1;32m>>\033[1;37m reloading dnsmasq...\033[0m\n";
my $pid;
open(DHCPPID, "/var/run/libvirt/network/$net.pid");
my @dhcppid = <DHCPPID>;
if ($dhcppid[0] =~ /([0-9]+)/)
{
$pid = $1;
}
close(DHCPPID);
system('kill', '-HUP', $pid);
print "\033[1;32m!!\033[1;37m done!\033[0m\n";
@artob
Copy link

artob commented Aug 5, 2014

There is a bug in the hostname matching, which makes the script ignore hosts named "foo-bar", i.e., that have a dash in the name. I've fixed this in a fork, here: https://gist.github.com/bendiken/032ea1bddb9ffafe98b4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment