CentOS和Ubuntu16.04下使用iptables实现端口转发

以前都是在 CentOS 环境下使用 iptables 或者 Nginx 实现端口转发,这两天接手了一个系统是 Ubuntu16.04 的服务器,下午被老师要求把一个跑在这个服务器上的项目的端口号给隐藏掉,依然按照 CentOS 的配置方式来配置 iptables 的端口转发。发现好使是好使,但是用过 iptables 的朋友应该也知道 iptables 规则设置后都是即时生效的,在机器重启后,iptables 中的配置信息会被清空,所以我们一般把这些配置保存下来,让 iptables 在系统启动时自动加载,省得每次都得重新输入。但是问题就出在了设置重启生效上,看了几篇博客才知道,Ubuntu 和 CentOS/RedHat 配置上有不少不同的地方,iptables 就是一个。遂特意写个文章记录一下,以后用到的时候再回来看。
 

CentOS 下使用 iptables 进行端口转发

 
这里先要注意一点的是, CentOS7 及以上版本使用 firewalld 取代了 iptables,如果想要使用 iptables 需要手动停止 firewalld,并且需要重新安装 iptables。

前两个步骤是停止 firewalld.service 以及重新安装 iptables 的步骤,CentOS7 版本以下的可以直接跳到第三步。

1.停止 firewalld.service (注意:两条命令都要执行,并且需要 root 权限)

systemctl stop firewalld.service
systemctl disable firewalld.service

2.重新安装 iptables

yum install iptables

3.接下来,就是使用 iptables 实现端口转发了(这里以将对 80 端口的请求导向 8080端口为例子)

iptables -t -nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

4.之后保存该设置

service iptables save

还没完,为了使重启之后还是生效的,我们还要执行下面两条命令

systemctl restart iptables .service
systemctl enable iptables .service

Ubuntu 下使用 iptables 进行端口转发

首先,转发请求的命令同 CentOS 一样(这里以将对 80 端口的请求导向 8080端口为例子)

iptables -t -nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

之后,保存配置信息就跟 CentOS 不一样了,这里我们需要把防火墙规则保存到 /etc/iptables.up.rules 文件中

iptables-save > /etc/iptables.up.rules

然后,修改这个脚本 /etc/network/interfaces ,在末尾添加一行,在网络启动时应用防火墙规则:

pre-up iptables-restore < /etc/iptables.up.rules

猜你喜欢

转载自blog.csdn.net/u013568373/article/details/91590938