Skip to content

Instantly share code, notes, and snippets.

@tachang
Created April 10, 2015 19:37
Show Gist options
  • Save tachang/24b72d613faa19f76cfa to your computer and use it in GitHub Desktop.
Save tachang/24b72d613faa19f76cfa to your computer and use it in GitHub Desktop.
Cleanly restart the default libvirt network
#!/bin/bash
#
# Yury V. Zaytsev <[email protected]> (C) 2011
#
# This work is herewith placed in public domain.
#
# Use this script to cleanly restart the default libvirt network after its
# definition have been changed (e.g. added new static MAC+IP mappings) in order
# for the changes to take effect. Restarting the network alone, however, causes
# the guests to lose connectivity with the host until their network interfaces
# are re-attached.
#
# The script re-attaches the interfaces by obtaining the information about them
# from the current libvirt definitions. It has the following dependencies:
#
# - virsh (obviously)
# - tail / head / grep / awk / cut
# - XML::XPath (e.g. perl-XML-XPath package)
#
# Note that it assumes that the guests have exactly 1 NAC each attached to the
# given network! Extensions to account for more (or none) interfaces etc. are,
# of course, most welcome.
#
# ZYV
#
set -e
set -u
NETWORK_NAME=default
NETWORK_HOOK=/etc/libvirt/hooks/qemu
#virsh net-define /opt/config/libvirt/network-$NETWORK_NAME.xml
virsh net-destroy $NETWORK_NAME
virsh net-start $NETWORK_NAME
MACHINES=$( virsh list | tail -n +3 | head -n -1 | awk '{ print $2; }' )
for m in $MACHINES ; do
echo "$m"
MACHINE_INFO=$( virsh dumpxml "$m" | xpath -e /domain/devices/interface[1] 2> /dev/null )
echo "$MACHINE_INFO"
MACHINE_MAC=$( echo "$MACHINE_INFO" | grep "mac address" | cut -d '"' -f 2 )
echo "$MACHINE_MAC"
MACHINE_MOD=$( echo "$MACHINE_INFO" | grep "model type" | cut -d '"' -f 2 )
set +e
virsh detach-interface "$m" network --mac "$MACHINE_MAC" && sleep 3
virsh attach-interface "$m" network $NETWORK_NAME --mac "$MACHINE_MAC" --model "$MACHINE_MOD"
set -e
#$NETWORK_HOOK "$m" stopped && sleep 3
#$NETWORK_HOOK "$m" start
done
@Alex-1357
Copy link

Unfortunately, this script don't working.
Registry_01112022_230623

And secondary, in production server restart virtual machine is impossible.

@pdostal
Copy link

pdostal commented May 28, 2022

The script works like a charm for me 🤩 Thank you

I just had to install xpath which on my openSUSE Leap: sudo zypper in perl-XML-XPath

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