Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Rules for vm names matching "{vm-name}"
- if [ "${1}" = "{vm-name}" ]; then
- # IP of the {vm-name} vm on the nat "network"
- GUEST_IP="192.168.122.2"
- # Addresses (ipv4 separated with spaces) that should be allowed access
- SOURCES=""
- # Ports (separated with spaces that should be forwarded 1:1 (port 443 forwards to port 443 etc.)
- PORTS=""
- # Name of the network interface (usually virbr#)
- INTERFACE="virbr0"
- COMMENT="added by libvirt hook"
- # When the machine is stopped or restarted
- if [ "${2}" = "stopped" ] || [ "${2}" = "reconnect" ]; then
- # Remove the rule for new traffic in the FORWARD chain
- /sbin/iptables -D FORWARD -o $INTERFACE -d $GUEST_IP -m comment --comment "$COMMENT" -j ACCEPT
- # Remove rules for each source with each port
- for SOURCE in $SOURCES; do
- for PORT in $PORTS; do
- /sbin/iptables -t nat -D PREROUTING -s $SOURCE -p tcp --dport $PORT -m comment --comment "$COMMENT" -j DNAT --to $GUEST_IP:$PORT
- done
- done
- fi
- # When the machine is started
- if [ "${2}" = "start" ] || [ "${2}" = "reconnect" ]; then
- # Check if a RELATED,ESTABLISHED rule exists for the interface
- iptables -vnL FORWARD --line-numbers |grep "RELATED,ESTABLISHED" |grep "${INTERFACE}" |awk -F ' ' '{print $1}' > /dev/null 2>&1
- # Set count variable to 1 (it will be used later explicitly as 1 if test condition fails otherwise I'd use 0)
- LINE_NUMBER=1
- # If the RELATED,ESTABLISHED rule exists for the interface, set the LINE_NUMBER to the line number of that line plus 1
- if [ $? -eq 0 ]; then
- LINE_NUMBER=$(($(iptables -vnL FORWARD --line-numbers |grep "RELATED,ESTABLISHED" |grep "${INTERFACE}" |awk -F ' ' '{print $1}') + 1))
- fi
- # Create the appropriate forward rule on the correct line number
- /sbin/iptables -I FORWARD $LINE_NUMBER -o $INTERFACE -d $GUEST_IP -m comment --comment "$COMMENT" -j ACCEPT
- # Create a rule to allow each source address on each 1:1 forwarded port
- for SOURCE in $SOURCES; do
- for PORT in $PORTS; do
- /sbin/iptables -t nat -I PREROUTING -s $SOURCE -p tcp --dport $PORT -m comment --comment "$COMMENT" -j DNAT --to $GUEST_IP:$PORT
- done
- done
- fi
- fi
- exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement