Skip to content

Instantly share code, notes, and snippets.

@hn3000
Last active July 24, 2021 08:22
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 hn3000/fb45e104d0f0861d4171dc67bb75c2ca to your computer and use it in GitHub Desktop.
Save hn3000/fb45e104d0f0861d4171dc67bb75c2ca to your computer and use it in GitHub Desktop.
qemu network hook script
#!/bin/bash
# this file wants to be called /etc/libvirt/hooks/qemu
# see https://wiki.libvirt.org/page/Networking
#!/bin/bash
echo "$0: ($(dirname $0) $(pwd)) $*" >> /var/log/qemu-nohop.out
export XML="$(cat)"
nohup $(dirname $0)/update-forwards.sh "$@" >> /var/log/qemu-nohop.out &
#!bin/bash
# this file needs to be called /etc/libvirt/hooks/update-forwards.sh
# (or the qemu script must be updated)
# the code in this file runs asynchronously after the qemu hook completes,
# to make sure the call(s) to virsh below don't block libvirtd
## NOTE: remember to create an entry in logrotate config
LOG='/var/log/qemu-hook.log'
function log {
echo "[$(date)]" "$*" >> $LOG
}
function update_forward {
GUEST_IP=$(virsh -q domifaddr $1|awk '{ split($4, x, "/"); print x[1]; }')
GUEST_PORT=$2
HOST_PORT=$3
EVENT=$4
log "$1 $GUEST_IP $2 $3 $4"
if [ "${EVENT}" = "stopped" ] || [ "${EVENT}" = "reconnect" ]; then
log "removing forward for $1: $3 --> ${GUEST_IP}:${GUEST_PORT}"
/sbin/iptables -D FORWARD -o virbr0 -p tcp -d $GUEST_IP --dport $GUEST_PORT -j ACCEPT 2>&1 >> $LOG
/sbin/iptables -t nat -D PREROUTING -p tcp --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT 2>&1 >> $LOG
fi
if [ "${EVENT}" = "start" ] || [ "${EVENT}" = "reconnect" ]; then
log "adding forward for $1: $3 --> ${GUEST_IP}:${GUEST_PORT}"
/sbin/iptables -I FORWARD -o virbr0 -p tcp -d $GUEST_IP --dport $GUEST_PORT -j ACCEPT 2>&1 >> $LOG
/sbin/iptables -t nat -I PREROUTING -p tcp --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT 2>&1 >> $LOG
fi
}
case "$1" in
"machine-name-here")
update_forward $1 2376 42376 $2
;;
*)
log "qemu hook not configured for $1 $2\nadd a line like\n'\"$1\"\)update_forward \$1 22 42022 \$2;;' to $0"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment