基于Rinetd实现Centos跳板机端口转发
前言
虽然Linux本身自带的iptables可以实现端口转发功能,但其配置相对复杂。因此本文介绍另一个端口转发工具rinetd,其安装和配置都更为简单。
关于rinetd使用你看这一篇就够了。
rinetd部署环境
本文是基于Centos7系统部署rinetd端口转发工具。
rinetd安装
到官网下载最新版,得到安装包rinetd.tar.gz
注:rinetd 后来迁移到 Github 了, Github 的版本与本文叙述的安装方式是不同的。
下载后上传到Linux,本文上传位置为:
/usr/local/
解压安装包:
tar -zxvf rinetd.tar.gz
由于rinetd需要编译安装,先安装gcc编译环境:
yum install gcc gcc-c++
若安装 gcc 失败,则需要先替换源并更新
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo sed -i ‘s/$releasever/7/g’ /etc/yum.repos.d/CentOS-Base.repo yum repolist
进入rinetd安装目录:
cd /usr/local/rinetd
检查安装配置文件:
vi Makefile
注意配置文件中涉及到两处安装路径,一般情况下保持默认值即可:
CFLAGS=-DLINUX -g rinetd: rinetd.o match.o gcc rinetd.o match.o -o rinetd install: rinetd install -m 700 rinetd /usr/sbin install -m 644 rinetd.8 /usr/man/man8
但是若 /usr/man/man8 目录不存在,需要先手建:
mkdir -p /usr/man/man8
如果你使用的是 Github 上的最新版本,这里还需要多执行两条命令去创建 makefile 文件:
./bootstrap ./configure
编译并安装:
make && make install
至此rinetd安装完成。
rinetd配置
配置端口转发规则(该文件可能不存在,直接创建即可):
vi /etc/rinetd.conf
该文件每行一个转发规则,配置格式为:
[source_address] [source_port] [destination_address] [destination_port] 即 [本机IP(若非多网卡直接设为0.0.0.0)] [转发端口] [服务IP] [服务端口] 如 0.0.0.0 9527 192.168.64.22 9527
官方完整配置文件参考:
# # this is the configuration file for rinetd, the internet redirection server # # you may specify global allow and deny rules here # only ip addresses are matched, hostnames cannot be specified here # the wildcards you may use are * and ? # # allow 192.168.2.* # deny 192.168.2.1? # allow fe80:* # deny 2001:618:*:e43f # # forwarding rules come here # # you may specify allow and deny rules after a specific forwarding rule # to apply to only that forwarding rule # # bindadress bindport connectaddress connectport options... # 0.0.0.0 80 192.168.1.2 80 # ::1 80 192.168.1.2 80 # 0.0.0.0 80 fe80::1 80 # 127.0.0.1 4000 127.0.0.1 3000 # 127.0.0.1 4000/udp 127.0.0.1 22 [timeout=1200] # 127.0.0.1 8000/udp 192.168.1.2 8000/udp [src=192.168.1.2,timeout=1200] # logging information logfile /var/log/rinetd.log # uncomment the following line if you want web-server style logfile format # logcommon
注:非必要不建议启用日志选项,会消耗大量磁盘空间
rinetd使用
默认情况下,rinetd的启动需要指定规则配置文件,而停止需要杀掉进程:
启动:rinetd -c /etc/rinetd.conf 停止:killall rinetd
查看端口转发状态
netstat -tanulp|grep rinetd
为了便于使用,可以把rinetd托管到systemd:
创建systemd服务文件:vi /etc/systemd/system/rinetd.service
[Unit] Description=rinetd After=network.target [Service] Type=forking ExecStart=/usr/sbin/rinetd -c /etc/rinetd.conf [Install] WantedBy=multi-user.target
重载daemon使其生效:systemctl daemon-reload尔后就可以通过systemd管理rinetd了:
# 启动 systemctl start rinetd # 停止 systemctl stop rinetd # 重启 systemctl restart rinetd # 设置开机自启 systemctl enable rinetd # 取消开机自启 systemctl disable rinetd
评论