端口转发其实属于奇技淫巧,在大部分情况都不会用到的。但是紧急情况下有这么一个技能特别实用。
1.windows下端口转发(默认xp已死)
在windows下端口转发主要依靠netsh命令。
netsh interface portproxy show all #显示所有端口转发情况
netsh interface portproxy add v4tov4 listenport=107 connectaddress=127.0.0.1 connectport=11112 #增加从本地107端口转发到11112端口的转发规则
netsh interface portproxy del v4tov4 listenport=107 #删除107端口的转发规则
netsh interface portproxy reset #重置,相当于删除所有转发规则
netsh命令对端口转发的控制基本就是增删查,同时转发时支持v4tov4,v4tov6,v6tov4,v6tov6等不同协议。
2.linux下的端口转发
linux下的端口转发主要依赖ssh命令,其实相当烦,也异常强大。
①本地转发,远程转发和动态转发(原文讲的太好,舍不得翻译)
There are three types of port forwarding with SSH:
Local port forwarding: connections from the SSH client are forwarded via the SSH server, then to a destination server
Remote port forwarding: connections from the SSH server are forwarded via the SSH client, then to a destination server
Dynamic port forwarding: connections from various programs are forwarded via the SSH client, then via the SSH server, and finally to several destination servers
附上stackexchange上一幅图(http://unix.stackexchange.com/questions/115897/whats-ssh-port-forwarding-and-whats-the-difference-between-ssh-local-and-remot)
②参数的写法
本地转发和远程转发参数写法是一样的,基本后面都是跟 <local port>:<remote host>:<remote port> username@<ssh server>
无论是写本地转发和远程转发按这么一个顺序来:
你希望本机起监听端口则用-L参数,否则用-R。
<local port>
是指监听的端口号,这一点没有太多问题。
<remote host>:<remote port>
是流量转发后的目的地。需要注意的是这个地址是相对的。比如同样的127.0.0.1:123,在本地转发的情况下127.0.0.1是指本机,在远程转发的情况下127.0.0.1是指username@。
username@` server地址,在本地转发中它是流量的中转站,在远程转发中,它是流量的来源。
③使用ssh做端口转发的注意点总结
如果以上命令不加”-g”选项,第二个参数的监听端口默认只会绑定在127.0.0.1上,意味着假如你用-L参数做了本地端口映射,也只有你自己能用。(还有一种办法是设置服务器端的/etc/ssh/sshd_config中GatewayPorts选项设置为yes,并手动指定绑定端口号的ip地址能达到同样的效果。)
当不加-f -N参数时命令会生成一个shell,有时候并不符合我们的需要,因为多数时候我们只想要一个端口转发功能,挂一个shell是个累赘,而且shell一退出,端口转发也停了。-N 告诉ssh client,这个连接不需要执行任何命令,仅做端口转发。-f 告诉ssh client在后台运行。
为了避免长时间空闲导致ssh连接被断开,我们可以加上”-o ServerAliveInterval=60″选项,或者在/etc/ssh/ssh_config里面加一行ServerAliveInterval=60,意思是每60秒向ssh server发送心跳信号。还有一个TCPKeepAlive选项的作用是类似的,但是不如ServerAliveInterval 好,因为TCPKeepAlive在TCP层工作,发送空的TCP ACK packet,有可能会被防火墙丢弃;而ServerAliveInterval 在SSH层工作,发送真正的数据包,更可靠些。
如果不是以root身份设置端口转发的话,转发端口只能使用大于1024的端口号。
④实例
ssh -L 80:localhost:80 root@A #转发A服务器的80端口到本地80
ssh -R 80:localhost:80 root@A #转发本地的80端口到A服务器80
ssh -R 80:192.168.0.1:80 root@A #以本机服务器作为跳板,让A服务器80映射到局域网192.168.0.1的80端口