From :https://www.ibm.com/developerworks/cn/linux/l-cn-sshforward/
一. 概念
SSH能夠將其他 TCP 端口的網絡數據通過 SSH 鏈接來轉發,並且自動提供了相應的加密及解密服務。這一過程有時也被叫做“隧道”(tunneling)
二. 兩功能
- 加密 SSH Client 端至 SSH Server 端之間的通訊數據。
- 突破防火牆的限制完成一些之前無法建立的 TCP 連接。
三. 分類
1. 本地端口轉發
命令格式 : ssh -L <
local
port>:<
remote
host>:<
remote
port> <
SSH
hostname>
case 1: 雙機 (只有兩臺機器LDAP Client 和 LDAP Server)
LDAP server沒有被牆
只有LDAP 服務器上部署的應用才能直接連接此 LDAP 服務器
LdapClientHost 執行:
$
ssh -L 7001:localhost:389 LdapServerHost (將遠程機器(LdapClientHost)上的應用直接配置到本機的 7001 端口上)
注意:
1. 在建立 SSH 連接的同時創建端口轉發
2. <remote host> 指向 LdapServertHost, 用 localhost 而不是 IP 地址或者主機名, 因限制LDAP只有本機才能訪問(只允許 lookback 接口訪問)。
3. LdapClientHost建立的7001端口轉發不可以被其他機器使用。
本地端口轉發綁定的是lookback接口,只能本機應用次啊能訪問。其他機器連接會有"connection refused"錯誤。
GatewayPorts 關鍵字可以解決這個問題
ssh -g -L <local port>:<remote host>:<remote port> <SSH hostname>
case 2: 四機
LDAP Server 被牆
SSH Client(C) 執行:
$ ssh -g -L 7001:<
B
>:389 <
D
>
注意:
1. -g
2. (A)<-> (C) 以及 (B)<->(D) 之間的連接並不是安全連接,它們之間沒有經過 SSH 的加密及解密
2. 遠程端口轉發
命令格式 : ssh -R <
local
port>:<
remote
host>:<
remote
port> <
SSH
hostname>
case:LdapClientHost SSH不到 LdapServertHost
LdapServertHost SSH 到 LdapClientHost OK
LdapServertHost 執行
$ ssh -R 7001:localhost:389 LdapClientHost
本地端口轉發和遠程端口轉發區別
本地:
LdapClientHost app client-> LdapClientHost SSH Client -> LdapServertHost SSH Server -> LdapServertHost app server
遠程:
LdapClientHost app client-> LdapServertHost SSH Server -> LdapClientHost SSH Client -> LdapServertHost app server
3. 動態端口轉發
服務器端口不固定, 如瀏覽器進行 Web 瀏覽,可能是80,可能是443,可能是...
命令格式 : $ ssh -D <
local
port> <
SSH
Server>
sample 1: SSH Client執行:
ssh -D 7001 <
SSH
Server>
選擇了 7001 作爲本地的端口號,SH 是創建了一個 SOCKS 代理服務。
Sample 2:
A機器執行
ssh-D 1080 root@sshserver
A機器firefox設置代理socket proxy:127.0.0.1:1080
A機器測試
root@ubuntu:~# curl --socks5 127.0.0.1:1080 www.google.com
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-PH"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png
root@ubuntu:~# netstat -anp | grep 1080
tcp 0 0 127.0.0.1:1080 0.0.0.0:* LISTEN 15287/ssh
tcp 0 0 127.0.0.1:51592 127.0.0.1:1080 TIME_WAIT -
tcp6 0 0 ::1:1080 :::* LISTEN 15287/ssh
A windows, 也可如下設置瀏覽器代理