指令與參數解析
ssh -L username -P 22 -D 7070 IP
修正後的標準語法 (原文參數順序有誤):
ssh -D 7070 -p 22 username@IP
# 或
ssh -D 7070 username@IP # 預設 22 埠
參數詳細說明
| 參數 | 功能 | 範例 |
-D [bind_address:]port | 動態應用層埠轉發 (SOCKS 4/5 代理),本機監聽指定埠,流量經 SSH 隧道轉發至遠端 | -D 7070 或 -D 127.0.0.1:7070 |
-p port | 指定遠端 SSH 服務埠 (預設 22) | -p 2222 |
-L local_port:remote_host:remote_port | 本地埠轉發 (固定目標) | -L 8080:localhost:80 |
-R remote_port:local_host:local_port | 遠端埠轉發 (反向隧道) | -R 8080:localhost:80 |
-N | 不執行遠端指令,僅建立隧道 (常搭配 -D/-L/-R) | ssh -N -D 7070 user@host |
-f | 背景執行 (需搭配 -N) | ssh -fN -D 7070 user@host |
-C | 壓縮傳輸資料 | -C |
實戰場景:瀏覽器配置 SOCKS5 代理
- 建立隧道:
ssh -fN -D 7070 user@centos-server
- 瀏覽器 (Chrome/Firefox) 設定代理:
- 類型:SOCKS v5
- 主機:127.0.0.1
- 埠:7070
- 驗證:訪問
https://ip.sb 顯示應為 CentOS 伺服器公網 IP
進階:系統層級透明代理 (Linux/macOS)
# 使用 proxychains (需安裝)
proxychains4 curl ip.sb
# 或 redsocks + iptables 實現全域透明代理
常見問題
- Connection refused:確認遠端
/etc/ssh/sshd_config 有 AllowTcpForwarding yes (預設開啟)
- 斷線重連:搭配
autossh 自動維持隧道 autossh -M 0 -fN -D 7070 user@host
- Windows 客戶端:PuTTY → Connection → SSH → Tunnels → Add D7070 (Dynamic) → Open
安全建議
- 僅綁定
127.0.0.1:7070 避免區域網其他機器存取:-D 127.0.0.1:7070
- 使用金鑰認證禁用密碼登入
- 防火牆限制 SSH 埠僅允許信任 IP