Last active
November 30, 2021 22:47
-
-
Save golubov-andrey/865ac9b93f514f247e61b5925518c210 to your computer and use it in GitHub Desktop.
Forward qemu port to host machine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # More information on https://www.libvirt.org/hooks.html | |
| # and https://wiki.libvirt.org/page/Networking | |
| GUEST_NAME=$1 | |
| GUEST_STATE=$2 | |
| function forward { | |
| INTERFACE=$1 | |
| PROTOCOL=$2 | |
| HOST_PORT=$3 | |
| GUEST_IP=$4 | |
| GUEST_PORT=$4 | |
| if [ "${GUEST_STATE}" = "start" ] || [ "${GUEST_STATE}" = "reconnect" ]; then | |
| echo "$(date) -- FORWARD ${GUEST_NAME} ${INTERFACE} FROM 0.0.0.0:${HOST_PORT} TO ${GUEST_IP}:${GUEST_PORT}" >> /var/log/libvirt/qemu/hook-${GUEST_NAME}.log | |
| /sbin/iptables -I FORWARD -o $INTERFACE -p $PROTOCOL -d $GUEST_IP --dport $GUEST_PORT -j ACCEPT | |
| /sbin/iptables -t nat -I PREROUTING -p $PROTOCOL --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT | |
| fi | |
| if [ "${GUEST_STATE}" = "stopped" ] || [ "${GUEST_STATE}" = "reconnect" ]; then | |
| echo "$(date) -- REMOVE FORWARD ${GUEST_NAME} ${INTERFACE} FROM 0.0.0.0:${HOST_PORT} TO ${GUEST_IP}:${GUEST_PORT}" >> /var/log/libvirt/qemu/hook-${GUEST_NAME}.log | |
| /sbin/iptables -D FORWARD -o $INTERFACE -p $PROTOCOL -d $GUEST_IP --dport $GUEST_PORT -j ACCEPT | |
| /sbin/iptables -t nat -D PREROUTING -p $PROTOCOL --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT | |
| fi | |
| } | |
| # IMPORTANT: Change the "VM NAME" string to match your actual VM Name. | |
| # In order to create rules to other VMs, just duplicate the below block and configure | |
| # it accordingly. | |
| case "${GUEST_NAME}" in | |
| "VirtualMachineName") | |
| forward virbr0 tcp 10080 192.168.122.152 80 | |
| forward virbr0 tcp 10443 192.168.122.152 443 | |
| ;; | |
| esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment