利用iptables实现端口映射(支持动态域名)
将下列代码保存到/bin/ddns_portmap.sh
#!/bin/bash
# 检查参数
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <domain> <local_port1:remote_port1,local_port2:remote_port2,...>"
exit 1
fi
# 从参数获取动态域名和端口映射
domain=$1
port_mappings=$2
# 获取当前解析的IP地址
new_ip=$(getent ahosts $domain | awk '{print $1}' | head -n 1)
# 如果无法解析域名,退出
if [ -z "$new_ip" ]; then
echo "Failed to resolve domain: $domain"
exit 1
fi
# 循环处理每个端口映射
IFS=',' read -ra mappings <<< "$port_mappings"
for mapping in "${mappings[@]}"; do
local_port=$(echo $mapping | cut -d ':' -f 1)
remote_port=$(echo $mapping | cut -d ':' -f 2)
# 获取当前iptables中配置的目标IP和端口
current_mapping=$(iptables -t nat -L PREROUTING -n --line-numbers | grep "dpt:$local_port" | awk '{print $9}')
# 提取当前的目标IP和目标端口
current_ip=$(echo $current_mapping | cut -d ':' -f 2)
current_port=$(echo $current_mapping | cut -d ':' -f 3)
# 如果新IP或远程端口和现有的不一致,则更新iptables规则
if [ "$new_ip" != "$current_ip" ] || [ "$remote_port" != "$current_port" ]; then
# 删除旧规则
if [ -n "$current_ip" ]; then
iptables -t nat -D PREROUTING -p tcp --dport $local_port -j DNAT --to-destination $current_ip:$current_port
iptables -t nat -D POSTROUTING -p tcp -d $current_ip --dport $current_port -j MASQUERADE
fi
# 添加新规则
iptables -t nat -A PREROUTING -p tcp --dport $local_port -j DNAT --to-destination $new_ip:$remote_port
iptables -t nat -A POSTROUTING -p tcp -d $new_ip --dport $remote_port -j MASQUERADE
echo "Updated iptables rules for $domain: $local_port -> $new_ip:$remote_port"
else
echo "No change in IP address or remote port for $domain on port $local_port."
fi
done
crontab -e
贴入下列代码即可完成端口映射
* * * * * /bin/ddns_portmap.sh 39.172.91.235 201:201
* * * * * /bin/ddns_portmap.sh dx11.fm20.cn 1110:1110,1112:1112,1161:1161
本文来自博客园,作者:项希盛,转载请注明原文链接:https://www.cnblogs.com/xiangxisheng/p/18475730