Skip to content

Instantly share code, notes, and snippets.

@TrogloGeek
Created August 1, 2017 15:13
Show Gist options
  • Save TrogloGeek/0a12a8916bf2af81aed1dc5b96d4bb93 to your computer and use it in GitHub Desktop.
Save TrogloGeek/0a12a8916bf2af81aed1dc5b96d4bb93 to your computer and use it in GitHub Desktop.
Libvirt interactive script to add dhcp static host on managed networks
#!/bin/bash
set -u
COLOR_RED='\e[31m'
COLOR_GREEN='\e[31m'
RESET_FONT='\e[0m'
function printError() {
echo -e "${COLOR_RED}${1}${RESET_FONT}"
}
networks_raw=$(virsh net-list --all | tail -n +3 | awk '{print $1}')
netidx=0
declare -a networks
for net in $networks_raw; do
echo "$netidx"') '"$net"
networks[$netidx]="$net"
netidx=$(($netidx+1))
done
unset net
unset networks_raw
while true; do
read -r -p 'Which network? ' answer
[[ "$answer" =~ ^[0-9]+$ ]] && [ $((answer)) -lt $netidx ] && break
printError 'Wrong input, please type in one of the above networks index'
done
networkName="${networks[$((answer))]}"
echo "You selected ${networkName}"
unset netidx
unset networks
unset answer
# networkName: user selected network name
inDhcpBlock=false
virsh net-dumpxml "$networkName" | while IFS= read -r line; do
if [[ "$line" =~ '<dhcp>' ]]; then
inDhcpBlock=true
continue
fi
if [[ "$line" =~ '</dhcp>' ]]; then
break
fi
$inDhcpBlock && echo "$line"
done
unset line
unset inDhcpBlock
while true; do
while true; do
read -r -p 'Mac address? ' macAddress
[[ "$macAddress" =~ ^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$ ]] && break
printError 'Invalid mac address'
done
while true; do
read -r -p 'IP address? ' ipAddress
[[ "$ipAddress" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && break
printError 'Invalid ip address'
done
read -r -p 'Hostname? ' hostName
entry="<host mac='${macAddress}' name='${hostName}' ip='${ipAddress}'/>"
echo 'About to insert following entry:'
echo "$entry"
while true; do
read -r -p 'Accept? [Y/n]' answer
[[ ("$answer" = 'n') || ("$answer" = 'N') ]] && break
[[ (-z "$answer") || ("$answer" = 'y') || ("$answer" = 'Y') ]] && break 2
printError 'Invalid answer, please input "y" or "n"'
done
done
virsh net-update "$networkName" add-last ip-dhcp-host "$entry" --config --live
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment