2015-07-15-ssh-port-forward

layout title subtitle date author tags
post
ssh 端口轉發
遷移自 bandwagon vps
2015-07-15
cj
port-forward ssh

公司項目,服務器-客戶端模式,當服務器與客戶端跨運營商運行時(服務器使用移動專線,客戶端使用電信寬帶),容易出現頻繁斷線、斷線後不能重連的問題。而我所在的分公司環境爲,一個電信8M寬帶,一個電信2M獨立IP,一般情況下很難重現rst/retransmition等現象。

我想到自己有個VPS,是否可以利用一下呢?vps上有個shadowsocks服務器程序,平時用來翻牆,他就是用來轉發的嘛,那麼能不能自己搞一下,使用端口轉發的方式,將客戶端的鏈接通過vps轉發到我的服務器上呢?

然後搜索端口轉發,果然,已經有成熟的實現:ssh端口轉發。

基本原理就是兩個機子分別運行ssh客戶端與sshd服務器,2者建立加密連接後轉換爲普通tcp連接給指定的端口,該端口爲自己的服務端程序用來監聽的端口。

ssh命令中 -L / -R兩個選項就是用來幹這個事的,不過一個是本地轉發,一個是遠程轉發。看過一些資料後發現二者的區別爲:本地轉發時,本地爲ssh客戶端程序,sshd服務程序與服務端程序運行在遠程主機,其他地方的客戶端連接本地主機的端口A時,ssh客戶端將該連接加密後轉發給遠程sshd服務,sshd服務程序解密後交給服務端程序。

而遠程轉發恰好相反:本地運行的時ssh客戶端與服務器程序,遠程主機運行的是sshd服務程序,並在監聽端口A上的連接加密後轉發給本地ssh客戶端,本地ssh客戶端解密後轉交給服務器程序。

權衡後我選擇了遠程轉發,這樣可以免去先ssh登陸到vps,再在vps上執行本地轉發的麻煩。

只要在我的win7上安裝ssh客戶端,執行遠程轉發命令即可。 {% highlight shell %} ssh -R 12345:36.40.73.92:12345 [email protected] -p xxxxx {% endhighlight %}

36.40.73.92爲電信寬帶分配的IP,wangyapeng.net爲我的vps。安全起見,我的vps監聽端口號不是默認的22,而是xxxxx:)

上述命令的作用爲:wangyapeng.net監聽12345端口,接受到連接後加密並轉發給36.40.73.92的12345端口。由於我的開發機在路由器下,還需要在路由器上設置端口映射,將12345映射到我開發機的12345端口上。

linux manpage上關於ssh -R的說明爲:

−R

[bind_address:]port:host:hostport Specifies that the given port on the remote (server) host is to be forwarded to the given host and port on the local side. This works by allocating a socket to listen to port on the remote side, and when- ever a connection is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port hostport from the local machine.

Port forwardings can also be specified in the configuration file. Privileged ports can be forwarded only when logging in as root on the remote machine. IPv6 addresses can be specified by enclosing the address in square brackets.

By default, the listening socket on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. An empty bind_address, or the address ‘∗’, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server’s GatewayPorts option is enabled (see sshd_config(5)).

If the port argument is ‘0’, the listen port will be dynamically allocated on the server and reported to the client at run time. When used together with -O forward the allocated port will be printed to the standard output.

sh 的-g選項表示綁定監聽地址到ADDR_ANY,但我試過之後沒有效果。在vps上運行

telnet localhost 12345

本地服務器程序確實收到了連接,說明ssh端口轉發已經生效,只不過sshd只接受本機發起的連接而已。

再來看ssh -R的說明,需要sshd_config的選項GatewayPorts爲yes纔可以,相當於-g。修改之後,再在本機上執行

telnet wangyapeng.net 12345

成功!

參考資料:

實戰ssh端口轉發

SSH 隧道轉發實戰

SSH原理與運用(二):遠程操作與端口轉發

SSH 遠程端口轉發

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章