学无止境linux批量设置nftables来进行转发
Riv3n前言
以前服务器转发一般用iptables ,内核自带性能好,同时可以使用tcp和udp。
但是iptables不支持域名ddns
项目
这里使用github的一个项目
项目地址:https://github.com/arloor/nftables-nat-rust
优势
- 实现动态nat:自动探测配置文件和目标域名IP的变化,除变更配置外无需任何手工介入
- 支持IP和域名
- 以配置文件保存转发规则,可备份或迁移到其他机器
- 自动探测本机ip
- 开机自启动
- 支持端口
劣势
- 不支持负载均衡
- 不能传递真实ip
- 没有直观的ui可以监测转发情况
安装
这里以debian10为例
清除iptables
之前用了iptables转发要执行下面的清理下
1 2 3 4
| iptables -P INPUT ACCEPT iptables -P OUTPUT ACCEPT iptables -P FORWARD ACCEPT iptables -F
|
如果你有ipv6的话 还要另外换成ip6tables
再执行一遍
安装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| # 安装nftables apt-get install -y nftables # 下载可执行文件 wget -O /usr/local/bin/nat http://cdn.arloor.com/tool/dnat chmod +x /usr/local/bin/nat # 创建systemd服务 cat > /lib/systemd/system/nat.service <<EOF [Unit] Description=dnat-service After=network-online.target Wants=network-online.target
[Service] ExecStart=/usr/local/bin/nat /etc/nat.conf LimitNOFILE=100000 Restart=always RestartSec=60
[Install] WantedBy=multi-user.target EOF
# 设置开机启动,并启动该服务 systemctl daemon-reload systemctl enable nat
# 生成配置文件,配置文件可按需求修改(请看下文) cat > /etc/nat.conf <<EOF SINGLE,49999,59999,baidu.com RANGE,50000,50010,baidu.com EOF
systemctl start nat
|
转发规则
转发规则配置文件在/etc/nat.conf
1 2
| SINGLE,49999,59999,baidu.com RANGE,50000,50010,baidu.com
|
- 每行代表一个规则;行内以英文逗号分隔为4段内容
- SINGLE:单端口转发:本机49999端口转发到baidu.com:59999
- RANGE:范围端口转发:本机50000-50010转发到baidu.com:50000-50010
- 请确保配置文件符合格式要求,否则程序可能会出现不可预期的错误,包括但不限于你和你的服务器炸掉(认真
如需修改转发规则,请vim /etc/nat.conf
以设定你想要的转发规则。修改完毕后,无需重新启动vps或服务,程序将会自动在最多一分钟内更新nat转发规则(PS:受dns缓存影响,可能会超过一分钟)
停止和卸载
1 2 3 4 5 6 7 8
| ## 停止定时监听域名解析地任务 service nat stop ## 清空nat规则 nft add table ip nat nft delete table ip nat ## 禁止开机启动 systemctl disable nat
|
单独转发udp
项目内有一个nat.py
,他实现了按需转发tcp、udp、tcp_and_udp的功能。使用方式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| wget https://raw.githubusercontent.com/arloor/nftables-nat-rust/master/nat.py -O /usr/local/bin/nat.py cat > /lib/systemd/system/nat.service <<EOF [Unit] Description=dnat-service After=network-online.target Wants=network-online.target
[Service] WorkingDirectory=/ ExecStart=/usr/bin/python3 /usr/local/bin/nat.py /etc/nat.conf LimitNOFILE=100000 Restart=always RestartSec=60
[Install] WantedBy=multi-user.target EOF systemctl daemon-reload systemctl enable nat
cat > /etc/nat.conf <<EOF SINGLE,49999,59999,baidu.com,tcp RANGE,50000,50010,baidu.com EOF
systemctl start nat
|
