Skip to content

Instantly share code, notes, and snippets.

@ryanc-me
Last active September 5, 2024 05:05
Show Gist options
  • Save ryanc-me/e2c1fe62cd95a7df449e81a5dff3fe64 to your computer and use it in GitHub Desktop.
Save ryanc-me/e2c1fe62cd95a7df449e81a5dff3fe64 to your computer and use it in GitHub Desktop.
KVM Port-Forward Script
#!/bin/bash
#
# INSTRUCTIONS
#
# 1. Place this script at /etc/libvirt/hooks/qemu
# 2. Make it executable: $ sudo chmod +x /etc/libvirt/hooks/qemu
# 3. Add your forwarding rules at the bottom of this file
# 4. Restart the VM, or restart the libvirtd service
#
# Author: Ryan Cole
# Link: https://gist.github.com/ryanc-me/e2c1fe62cd95a7df449e81a5dff3fe64
logfile="/var/log/libvirt/hook-port-fwd.log"
service="$1"
action="$2"
# note: if outbound traffic is not working, you may need to fill the host's WAN IP
# here. Example is: you've forwarded host:22 -> vm:22, but now the VM can't connect
# *out* to other_server:22.
#
#host_ip="123.123.123.123"
#
# you may also need to add the masquerade rule below (check the subnet is correct):
#
#sudo iptables -t nat -A POSTROUTING -s 192.168.122.0/24 -j MASQUERADE
function log() {
echo "$@" >> "$logfile"
}
function forward() {
vm_name="$1"
vm_ip="$2"
port_vm="$3"
port_host="$4"
dest_filter=""
if [ -n "$host_ip" ]; then
dest_filter=" -d $host_ip"
fi
if [ "$service" != "$vm_name" ]; then
return 0
fi
if [ "$action" = "stopped" ] || [ "$action" = "reconnect" ]; then
log "$(date -Iseconds): [${service}][${action}] Del host:${port_host} -> ${vm_name}:${port_vm} (${vm_ip})"
/sbin/iptables -D FORWARD -o virbr0 -d ${vm_ip} -j ACCEPT
/sbin/iptables -t nat -D PREROUTING -p tcp --dport ${port_host} ${dest_filter} -j DNAT --to ${vm_ip}:${port_vm}
fi
if [ "$action" = "start" ] || [ "$action" = "reconnect" ]; then
log "$(date -Iseconds): [${service}][${action}] Add host:${port_host} -> ${vm_name}:${port_vm} (${vm_ip})"
/sbin/iptables -I FORWARD -o virbr0 -d ${vm_ip} -j ACCEPT
/sbin/iptables -t nat -I PREROUTING -p tcp --dport ${port_host} ${dest_filter} -j DNAT --to ${vm_ip}:${port_vm}
fi
}
# NOTE: The VM name must match exactly (including spaces/etc)!
#
# VM Name VM IP VMPort HostPort
forward "my-vm" "192.168.122.123" "8080" "80" # host:80 -> vm:8080
forward "my-vm" "192.168.122.123" "443" "443"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment