Skip to content

Instantly share code, notes, and snippets.

@Mhs-220
Created August 2, 2020 07:48
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 Mhs-220/39a3eb7291cac5ea3eac969b366ed114 to your computer and use it in GitHub Desktop.
Save Mhs-220/39a3eb7291cac5ea3eac969b366ed114 to your computer and use it in GitHub Desktop.
A Libvirt hook to auto setup a port on ip to access virtual machines.
#!/bin/bash
#
# Hook script for QEMU
#
# adds port forwards via IPtables and ARP to your VMs
#
# Implement: Erico Mendonca (erico.mendonca@suse.com)
# Change: Mohammadhossein Shahmohammadi (hos1377@gmail.com)
# 2020/Jul
#
log() {
logger -t addForward "$1"
}
addForward() {
IPTABLES="/sbin/iptables"
VM=$1
HOST_PORT=$2
GUEST_PORT=$3
if [ "${ACTION}" == "stopped" ]; then
IPTABLES_ACTION="-D"
fi
if [ "${ACTION}" == "started" ]; then
IPTABLES_ACTION="-I"
fi
if [ -z "${IPTABLES_ACTION}" ]; then
log "There is nothing to do. Maybe domain $VM is in prepare, started or stopped, ignoring."
exit 0
fi
if [ "${VM}" == "${VM_NAME}" ]; then
HOST_BRIDGE=$(echo "${MACHINEINFO%x}" | xpath -e /domain/devices/interface[1]/source | cut -d= -f3 | cut -d\" -f2)
if [ -z "$HOST_BRIDGE" ] && [ $IPTABLES_ACTION == "-I" ]; then
log "Could not identify bridge interface for ${VM}, skipping"
exit 0
fi
log "Trying to add rule in iptables for ${VM_NAME}"
MAC_ADDR=$(echo "${MACHINEINFO%x}" | xpath -e /domain/devices/interface[1]/mac/@address | cut -d '"' -f2)
timeout=0
while [ -z "${GUEST_IP}" ]
do
sleep 2
GUEST_IP=$(arp -an | grep "$MAC_ADDR" | cut -d "(" -f2 | cut -d ")" -f1)
((timeout+=1))
log "${timeout} times hit, still no GUEST_IP for ${VM}"
if [ "$timeout" == 30 ]; then
log "Could not get GUEST_IP for ${VM}, skipping"
exit 0
fi
done
log "Found an instance with ip ${GUEST_IP} and mac ${MAC_ADDR}"
log "adding ${IPTABLES_ACTION} forwarding rules for VM ${VM_NAME}: host port ${HOST_PORT} will be redirected to ${GUEST_IP}:${GUEST_PORT} on interface ${HOST_BRIDGE}"
$IPTABLES ${IPTABLES_ACTION} FORWARD -o "${HOST_BRIDGE}" -d "$GUEST_IP" -j ACCEPT
$IPTABLES -t nat ${IPTABLES_ACTION} PREROUTING -p tcp --dport "$HOST_PORT" -j DNAT --to "$GUEST_IP":"$GUEST_PORT"
fi
}
## main program
VM_NAME=${1}
ACTION=${2}
log "${VM_NAME} try to ${ACTION}"
# read the XML from stdin
MACHINEINFO=$(cat; echo x)
log "MACHINE_INFO: ${MACHINEINFO%x}"
### declare your port forwards here
### format: <VM> <host/extenral port> <guest/internal port>
addForward my-great-vm 31001 22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment