PVE iptables映射端口管理脚本

查看 53|回复 1
作者:silence   
用gpt4.0写的,一次成功,没有报错,后面又让他小修小补了一下,gpt是真好用
使用脚本前先apt install iptables-persistent安装iptables持久化,否则iptables默认重启后配置消失
[ol]#!/bin/bash
# 定义公网接口变量,根据实际情况修改
PUBLIC_INTERFACE=vmbr0
# 保存iptables规则
save_iptables_rules() {
    iptables-save > /etc/iptables/rules.v4
    echo "Iptables rules saved."
}
# 添加端口映射
add_port_mapping() {
    echo "Enter the VM IP address:"
    read vm_ip
    echo "Enter the public port:"
    read public_port
    echo "Enter the VM port:"
    read vm_port
   
    iptables -t nat -A PREROUTING -i $PUBLIC_INTERFACE -p tcp --dport $public_port -j DNAT --to-destination $vm_ip:$vm_port
    iptables -A FORWARD -p tcp -d $vm_ip --dport $vm_port -j ACCEPT
    save_iptables_rules
    echo "Port mapping added: Public port $public_port to VM $vm_ip:$vm_port"
}
# 删除端口映射
delete_port_mapping() {
    echo "Enter the VM IP address:"
    read vm_ip
    echo "Enter the public port:"
    read public_port
    echo "Enter the VM port:"
    read vm_port
   
    iptables -t nat -D PREROUTING -i $PUBLIC_INTERFACE -p tcp --dport $public_port -j DNAT --to-destination $vm_ip:$vm_port
    iptables -D FORWARD -p tcp -d $vm_ip --dport $vm_port -j ACCEPT
    save_iptables_rules
    echo "Port mapping deleted: Public port $public_port to VM $vm_ip:$vm_port"
}
# 改进的查看当前的端口映射
list_port_mappings() {
    echo "Current port mappings:"
    iptables -t nat -L PREROUTING -n -v | grep DNAT | while read line; do
        # 提取公网端口
        public_port=$(echo "$line" | awk '{print $11}' | sed -n -e 's/^.*dpt://p')
        # 提取目标IP和端口
        target=$(echo "$line" | awk '{print $NF}')
        # 如果没有提取到公网端口,则显示为N/A
        if [ -z "$public_port" ]; then
            public_port="N/A"
        fi
        echo "$public_port -> $target"
    done
}
# 交互式选择操作
echo "Choose an operation:"
echo "1) Add port mapping"
echo "2) Delete port mapping"
echo "3) List port mappings"
read operation
case $operation in
    1)
        add_port_mapping
        ;;
    2)
        delete_port_mapping
        ;;
    3)
        list_port_mappings
        ;;
    *)
        echo "Invalid option selected."
        exit 1
        ;;
esac
exit 0
[/ol]复制代码

GPT 是真好用,其中list_port_mappings存在比较繁琐的取值,gpt也是顺利搞定

公网, 端口, 端口映射

gdtv   
谢谢分享,但是我更喜欢用rinetd
https://91ai.net/thread-1015056-1-1.html
啊啊啊,这个也是你发的。
您需要登录后才可以回帖 登录 | 立即注册

返回顶部