You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.5 KiB
49 lines
1.5 KiB
#!/bin/bash
|
|
|
|
set -Eeuo pipefail
|
|
|
|
# This script is called by libvirt when a VM is started or stopped.
|
|
# It is used to set up and tear down networking for the VM.
|
|
# The script takes two arguments: the VM name and the action (start or stop).
|
|
VM_NAME="$1"
|
|
ACTION="$2"
|
|
|
|
# Check if the networking configuration file exists for the VM
|
|
if [ ! -f "/etc/libvirt/hooks/qemu.d/${VM_NAME}/iptables" ]; then
|
|
echo "No networking configuration found for VM '$VM_NAME'. Skipping."
|
|
exit 0
|
|
fi
|
|
|
|
if [ "$ACTION" = "started" ] || [ "$ACTION" = "reconnect" ]; then
|
|
echo "Setting up networking for VM '$VM_NAME'..."
|
|
|
|
# Set up iptables rules
|
|
while read -r rule; do
|
|
if [ -z "$rule" ]; then
|
|
continue
|
|
fi
|
|
iptables $rule
|
|
done < "/etc/libvirt/hooks/qemu.d/${VM_NAME}/iptables"
|
|
|
|
echo "Networking setup complete for VM '$VM_NAME'."
|
|
elif [ "$ACTION" = "stopped" ] || [ "$ACTION" = "disconnect" ]; then
|
|
echo "Tearing down networking for VM '$VM_NAME'..."
|
|
|
|
# Tear down iptables rules
|
|
while read -r rule; do
|
|
if [ -z "$rule" ]; then
|
|
continue
|
|
fi
|
|
# Replace '-A'/'-I' with '-D' to delete the rule
|
|
rule="${rule/-A/-D}"
|
|
rule="${rule/-I/-D}"
|
|
iptables $rule || echo "Warning: Failed to delete iptables rule: iptables $rule"
|
|
done < "/etc/libvirt/hooks/qemu.d/${VM_NAME}/iptables"
|
|
|
|
echo "Networking teardown complete for VM '$VM_NAME'."
|
|
else
|
|
echo "Unknown action '$ACTION'. Supported actions are 'started', 'stopped', 'reconnect', and 'disconnect'."
|
|
echo "Skipping."
|
|
fi
|
|
|
|
exit 0
|
|
|