# SSH Tunnel 應用二三事 參考文件:https://johnliu55.tw/ssh-tunnel.html 因為安全性的關係,我們在防火牆上會限制只有特定 IP 才能夠直接連線存取,其他外部電腦無法直接存取,然而,若想要在本機電腦直接連線的話,這時候就能使用 SSH Tunnel 來透過 SSH 將資料從代理伺服器上的服務掛到自己電腦指定的 port 上。 ![](https://i.imgur.com/TYYfWY8.png) 下面依狀況列出作法: ### 1. 將內部伺服器(Server)的服務, 透過中轉機(Proxy), 綁定到 PC 上 ![](https://i.imgur.com/vKXKo1I.png) > PC(192.168.10.3) --ssh--> (192.168.10.1)Proxy(192.168.20.1) --mysql--> (192.168.20.3)Server 如上,想要在PC上直接存取 Server 上的 MySQL(TCP 3306PORT),由於 PC 沒有route 可以連到 Server,或是 MySQL 僅允許192.168.20.0/24存取,但 PC 可以 SSH 到 Proxy(192.168.10.3->192.168.10.1), 而 Proxy 也可以連到 Server(192.168.20.1->192.168.20.3) 的3306 PORT。 作法為,使用sshtunnel,將Proxy當作中轉,代為連接到 Server 的3306 PORT。 ``` [root@PC]# ssh -N -L 0.0.0.0:3305:192.168.20.3:3306 user@Proxy ``` 說明: PC上以 ssh 登入 Proxy,並在 Proxy 建立一個到 192.168.20.3:3306 的通道,再將這個通道 轉到 PC 本機的3305 PORT,於是在 PC 上, 執行 ``` [root@PC]# mysql -h localhost -P 3305 -u user -p ``` 即可連到 Server 上的 MySQL 服務(TCP3306)。 ### 2. 將內部伺服器(Server)的服務, 透過中轉機(Proxy), 綁定到 PC 上。但此時Proxy 無法連進 Server, 故改由 Server 建立反向通道(-R) 到 Proxy, 將 Server的服務轉到 Proxy 上的某個 port ![](https://i.imgur.com/OV5PLst.png) > PC(192.168.10.3) --ssh--> (192.168.10.1)Proxy(192.168.20.1) <--ssh--(192.168.20.3)Server 這種情況是,Server的防火牆只出不進,亦即不可由 Proxy 直接連入 Server,必須由Server先建立一條通道: ``` a.在 Server 先建立一條通道到 Proxy,將 Server 上的 3306 PORT 轉到 Proxy 上的 1234 PORT [user@Server]# ssh -NfR 1234:localhost:3306 avata@Proxy ``` ``` b.在 PC 上再建立一條通道到 Proxy,將 Proxy 的 1234 PORT 轉到 PC 的 3305 PORT [user2@PC]# ssh -N -L 0.0.0.0:3305:localhost:1234 avata@Proxy ``` 步驟 b 仿照第 1 種情形,將目的主機的 PORT 轉到 PC 本機,只是此時目的主機為 Proxy 的 1234 PORT,因為 Proxy:1234, 此時已透通到 Server 的 3306 PORT。 最後,在PC上執行: ``` [root@PC]# mysql -h localhost -P 3305 -u user -p ``` 就可以直接連到 Server 上的 MySQL 服務(TCP3306)。 ### 3. 透過 Proxy 的線路上網 > PC(192.168.10.3) ---> (192.168.10.1)Proxy(192.168.20.1) ---> Internet 這種情況是,Proxy 出國有比較大的頻寛,但 PC 出國的頻寛比較小,想藉由 Proxy 的線路上網。 ``` [user@PC]# ssh -D 8088 avata@Proxy ``` 然後,在 PC 上的 browser 設定掛上代理伺服器設定![](https://i.imgur.com/7HsJIl9.jpg)