#!/bin/bash

# 获取用户输入的虚拟机IP和阻断时间
echo "Enter the IP address of the VM:"
read VM_IP
echo "Enter the duration in minutes for blocking the VM:"
read DURATION

# 检查用户输入
if [[ -z "$VM_IP" || -z "$DURATION" ]]; then
    echo "IP address and duration are required."
    exit 1
fi

# 创建执行网络控制的脚本
cat << EOF > block_restore_vm.sh
#!/bin/bash

# 阻断指定IP的流量
iptables -I FORWARD -d $VM_IP -j DROP
iptables -I FORWARD -s $VM_IP -j DROP
echo "Traffic for VM with IP $VM_IP has been blocked."

# 等待指定的时间
sleep ${DURATION}m

# 恢复流量
iptables -D FORWARD -d $VM_IP -j DROP
iptables -D FORWARD -s $VM_IP -j DROP
echo "Traffic for VM with IP $VM_IP has been restored."

# 删除脚本自身
rm -- "\$0"
EOF

# 给脚本执行权限
chmod +x block_restore_vm.sh

# 自动在后台执行block_restore_vm.sh脚本
./block_restore_vm.sh > /dev/null 2>&1 &

echo "The block_restore_vm.sh script is being executed in the background to block and then restore the VM's network traffic."
