内核层 DNAT/SNAT
把所有 TCP/UDP 端口内核级转发
一、准备信息
先查网卡名:
ip route get 8.8.8.8
看到类似:
dev eth0
那网卡就是 eth0。
信息为
公网 IP:1.1.1.1
网卡:eth0
SSH 端口:22
目标 IP:2.2.2.2
二、安装 nftables
apt update
apt install -y nftables
systemctl enable --now nftables
一键脚本自己修改ip,网卡
cat > /root/nft_to_hk.sh <<'EOF'
#!/bin/bash
set -e
HK_IP="xxx.xxx.xxx.x"
WAN_IF="eth0"
SSH_PORT="22"
echo "===================================="
echo " 本机 nftables 全端口转发到入口"
echo " 入口 IP: $HK_IP"
echo " 网卡: $WAN_IF"
echo " 保留 SSH 端口: $SSH_PORT"
echo "===================================="
apt update
apt install -y nftables conntrack
echo "[1/5] 开启 IPv4 转发..."
cat > /etc/sysctl.d/99-nft-hk-forward.conf <<SYSCTL
net.ipv4.ip_forward=1
net.ipv4.conf.all.rp_filter=0
net.ipv4.conf.default.rp_filter=0
net.netfilter.nf_conntrack_max=1048576
SYSCTL
sysctl --system
echo "[2/5] 备份原 nftables 配置..."
if [ -f /etc/nftables.conf ]; then
cp /etc/nftables.conf /etc/nftables.conf.bak.$(date +%F-%H%M%S)
fi
echo "[3/5] 写入 nftables 转发规则..."
cat > /etc/nftables.conf <<NFT
#!/usr/sbin/nft -f
flush ruleset
define WAN_IF = $WAN_IF
define HK_IP = $HK_IP
define SSH_PORT = $SSH_PORT
table ip nat {
chain prerouting {
type nat hook prerouting priority dstnat; policy accept;
# 保留 SSH,防止自己被锁外面
iifname \$WAN_IF tcp dport \$SSH_PORT accept
# TCP 全端口转发到入口
iifname \$WAN_IF ip protocol tcp dnat to \$HK_IP
# UDP 全端口转发到入口
iifname \$WAN_IF ip protocol udp dnat to \$HK_IP
}
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
# 强制回程经过前置,保证连接稳定
ip daddr \$HK_IP masquerade
}
}
table inet filter {
chain forward {
type filter hook forward priority filter; policy accept;
}
}
NFT
echo "[4/5] 检查 nftables 配置..."
nft -c -f /etc/nftables.conf
echo "[5/5] 启动 nftables..."
systemctl enable nftables
systemctl restart nftables
echo
echo "===================================="
echo "完成:已全端口转发到入口 $HK_IP"
echo "SSH 端口 $SSH_PORT 已保留,不会被转发"
echo "===================================="
echo
echo "当前规则:"
nft list ruleset
EOF
启动服务
chmod +x /root/nft_to_hk.sh
bash /root/nft_to_hk.sh
测试转发有没有生效:
tcpdump -ni eth0 host xxx.xxx.xxx.x
查看连接:
conntrack -L | grep xxx.xxx.xxx.x