socat:比ncat(nc)更好的端口转发工具

最近在端口转发上遇到了问题,表现为使用ncat(nc)进行端口转发时总会自动断开。比如当笔者使用如下nc命令进行端口转发时,就总会报错,然后nc自动退出。

命令:

ncat -l 17676 0</tmp/dbfifo17676 | ncat 192.168.203.55 3306 1>/tmp/dbfifo17676

错误:

(UNKNOWN) [192.168.203.55] 3306 (mysql) : Connection refused
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0

搜了一下,网上有人问过这个问题,有一个回复说nc不支持keep-alive和fork模式导致,并推荐了socat【1】。试了一下果然好用,故记录一下。

socat是一个“netcat++”版多功能网络双向传输数据通道中继器(Bidirectional data relay between two data channels (‘netcat++’),SOcket CAT),在各大Linux发行版上都有已经编译好的二进制包,直接yum/apt等方式安装即可。如果没有,也可以从官网下载源码编译(地址见参考【3】和参考【4】)。

就笔者而言,要将远程192.168.203.55的MySQL端口3306转发到本地端口17676,其socat的命令如下:

socat tcp-l:17676,fork,reuseaddr tcp:192.168.203.55:3306

然后就可以在本地用数据库管理工具,连接本地17176端口进行管理了。

更详细的用法请参考Red Hat网站Enable Sysadmin板块的文章《Getting started with socat, a multipurpose relay tool for Linux》(地址见参考【2】)。

参考:

【1】https://unix.stackexchange.com/questions/293304/using-netcat-for-port-forwarding
【2】Evans Amoany,Getting started with socat, a multipurpose relay tool for Linux,2020-06-25,https://www.redhat.com/sysadmin/getting-started-socat
【3】http://www.dest-unreach.org/socat/
【4】https://linux.die.net/man/1/socat

本页永久链接:https://www.orztip.com/?p=556&article_title=socat-a-better-alternative-tool-for-port-forward-and-bidirectional-data-relay