歡迎轉(zhuǎn)載,但請在開頭或結(jié)尾注明原文出處【blog.chaosjohn.com】
前言
筆者準備寫一個 端口轉(zhuǎn)發(fā) 系列文章,涉及計多個工具和命令。
本文為篇一,介紹一個大家常用的工具,rinetd。
簡介A: 端口轉(zhuǎn)發(fā)
英文:Port forwarding
將一臺 主機A 的 端口x 轉(zhuǎn)發(fā)到另一臺 主機B 的 端口y 并由 主機B 提供轉(zhuǎn)發(fā)的網(wǎng)絡服務。
即通過訪問 主機B:端口y 來訪問部署在 主機A:端口x 上的服務。
簡介B: rinetd
rinetd是為在一個Unix和Linux操作系統(tǒng)中為重定向傳輸控制協(xié)議(TCP)連接的一個工具。
rinetd是單一過程的服務器,它處理任何數(shù)量的連接到在配置文件etc/rinetd中指定的地址/端口對。
盡管rinetd使用非閉鎖I/O運行作為一個單一過程,它可能重定向很多連接而不對這臺機器增加額外的負擔。
場景
最早接觸到這個工具,是幾年前購買了阿里云的Redis實例,當初該服務未推出公網(wǎng)連接地址,只能通過內(nèi)網(wǎng)訪問,即只在同一個區(qū)域的VPC內(nèi)可達,在當初的業(yè)務環(huán)境下,只能從阿里云的ECS訪問Redis實例。
這就很惱怒了,在筆者本地的開發(fā)環(huán)境,也要連接改Redis實例,咋辦哩。
于是就在阿里云在線文檔里找到了這個工具,我還依稀記得那篇文檔里,介紹的是如何在CentOS下載rinetd源碼(還提供了tar.gz的鏈接地址),然后編譯安裝它。(不過伴隨著阿里云Redis實例開始支持公網(wǎng)連接后,該文檔已經(jīng)消失在了歷史長河里了。)
安裝
- 編譯安裝(適用于任何Linux環(huán)境,但個人不推薦,因為還得手動配置開機自啟)
$ curl -LO 'http://www.rinetd.com/download/rinetd.tar.gz'
$ tar xvzf rinetd.tar.gz
$ cd rinetd
$ sed -i 's/65536/65535/g' rinetd.c (修改端口范圍,否則會報錯)
$ make
$ sudo make install
(提示:官方下載的源碼包無法在macOS下完成編譯,報錯 error: implicit declaration of function 'inet_addr' is invalid in C99)
- 在
macOS上借助Homebrew安裝
$ brew install rinetd
- 在
Debian / Ubuntu上借助apt安裝
$ sudo apt update
$ sudo apt install rinetd
- 在
RHEL / CentOS上借助yum安裝
官方源中無rinetd,所以需要先安裝三方源
$ sudo vim /etc/yum.repos.d/nux-misc.repo
[nux-misc]
name=Nux Misc
baseurl=http://li.nux.ro/download/nux/misc/el6/x86_64/
enabled=0
gpgcheck=1
gpgkey=http://li.nux.ro/download/nux/RPM-GPG-KEY-nux.ro
然后再安裝rinetd
$ sudo yum --enablerepo=nux-misc install rinetd
配置
配置文件路徑為 /etc/rinetd.conf,并附上那臺轉(zhuǎn)發(fā)Redis的配置內(nèi)容
#
# 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?
#
# 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
0.0.0.0 6379 r-ly25ac35fxxxxx.redis.rds.aliyuncs.com 6379
# logging information
logfile /var/log/rinetd.log
# uncomment the following line if you want web-server style logfile format
# logcommon
-
allow和deny是配置 允許和阻止 的 IP地址/IP段 - 轉(zhuǎn)發(fā)規(guī)則一行一個,可配置多行
bindadress bindport connectaddress connectport,如示例里配置為:監(jiān)聽本網(wǎng)卡地址的6379端口號,并且轉(zhuǎn)發(fā)到VPC內(nèi)網(wǎng)Redis實例的6379端口號。
運行和自啟
- 如果是通過源碼編譯安裝的,命令行直接執(zhí)行
rinetd;自啟的話,得手動編寫Systemd的Unit文件來管理或者通過Supervisor來管理。 - 如果是
apt或yum安裝的,并且init程序是Systemd- 啟動服務:
$ sudo systemctl start rinetd - 停止服務:
$ sudo systemctl stop rinetd - 重啟服務:
$ sudo systemctl restart rinetd - 開機自啟:
$ sudo systemctl enable rinetd - 禁用自啟:
$ sudo systemctl disable rinetd
- 啟動服務: