libvirtd-主机下虚拟机端口转发

参考地址:https://wiki.libvirt.org/page/Networking#Forwarding_Incoming_Connections
参考地址:https://www.centos.org/forums/viewtopic.php?t=61444


mkdir -p /etc/libvirt/hooks/

vim /etc/libvirt/hooks/qemu

#!/bin/bash

# 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.
if [ "${1}" = "VM NAME" ]; then

   # Update the following variables to fit your setup
   GUEST_IP=
   GUEST_PORT=
   HOST_PORT=

   if [ "${2}" = "stopped" ] || [ "${2}" = "reconnect" ]; then
      /sbin/iptables -D FORWARD -o virbr0 -d  $GUEST_IP -j ACCEPT
      /sbin/iptables -t nat -D PREROUTING -p tcp --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT
   fi
   if [ "${2}" = "start" ] || [ "${2}" = "reconnect" ]; then
      /sbin/iptables -I FORWARD -o virbr0 -d  $GUEST_IP -j ACCEPT
      /sbin/iptables -t nat -I PREROUTING -p tcp --dport $HOST_PORT -j DNAT --to $GUEST_IP:$GUEST_PORT
   fi
fi

#修改vm name、guest ip、guest port、host port
systemctl restart libvirtd
#开放对应的端口就可以访问了