外網通過ssh代理連接內網服務器

內網服務器通過公網ssh代理實現內網穿透

前言

有時需要通過外網連接到內網的服務器。

  • 前提:需要有廣域網服務器,服務器之間免密。

1 環境

服務器類型 系統 主機名 用戶名 IP 說明
客戶端 Window 10 node1 本機 ssh連接工具(例如:Xshell)
中轉服務器 ubuntu 16.04 node2 user2 8.8.8.8 有廣域網IP
目標服務器 ubuntu 16.04 node3 user3 172.16.156.101 局域網IP,可以訪問外網

2 配置目標服務器

2.1 安裝autossh服務

sudo apt install -y autossh

autossh命令參數解釋如下:

  • -f 後臺運行
  • -C 允許壓縮數據
  • -N 不執行任何命令
  • -R 將端口綁定到遠程服務器,反向代理
  • -L 將端口綁定到本地客戶端,正向代理
  • -p 轉發服務器B的SSH登錄端口號,默認爲22

結合:

  • ssh -fCNR 反向代理
  • ssh -fCNL 正向代理

2.2 命令行配置連接中轉服務器--臨時有效

建立目標服務器到中轉服務器的反向代理,具體指令爲

autossh -M 中轉服務器端口 -fCNR [中轉服務器IP]:中轉服務器端口:目標服務器IP:目標服務器端口 中轉服務器用戶名@IP

例如:

autossh -M 5000 -o "ServerAliveInterval 30" -CNR 6000:localhost:22 [email protected]

說明:端口可以自定義,

  • 第一次連接時不加-f後臺運行,需要測試;
  • -M 5000:中轉服務器用來接收目標服務器的信息,如果隧道不正常而返回給目標服務器讓他實現重新連接,相當於會話保持;
  • -o "ServerAliveInterval 30":保持會話時間間隔,autossh中應該可以省略;
  • -CNR 6000:6000爲中轉服務器的反向代理端口;
  • localhost:22:目標Linux服務器的ssh端口,默認22。

3 配置中轉服務器

3.1 測試連接目標服務器

ssh $user3@localhost -p 6000

如果可以執行表示成功!

3.2 建立中轉服務器的正向代理

建立中轉服務器的正向代理,用來做轉發,具體指令爲

ssh -fCNL [目標Linux服務器IP]:目標Linux服務器端口:中轉服務器IP:中轉服務器端口 中轉服務器用戶名@中轉服務器IP

例:

ssh -fCNL "*:3000:localhost:6000" $user2@localhost

輸入目標服務器的密碼

3.3 客戶端

直接配置Xshell

IP:8.8.8.8

端口:3000

用戶名:$user3

密碼:XXXXXXX

或者任意服務器登陸;

ssh -p 3000 [email protected]

輸入目標服務器的密碼

4 配置自啓動

4.1 適用於CentOS6 和 CentOS7

輸入

vim /etc/rc.d/rc.local

追加如下內容

autossh -M 5000 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 5" -fCNR 6000:localhost:22 [email protected]

ServerAliveInterval:保持活力時間
ServerAliveCountMax:允許的最大會話數

授予執行權限

chmod +x /etc/rc.d/rc.local

4.2 適用於system管理的服務,如:CentOS 7 / Ubuntu 16 / Ubuntu 18

4.2.1 編寫autossh自啓動腳本

vim /lib/systemd/system/autossh.service

添加如下內容

[Unit]
Description=AutoSSH service
After=network.target
[Service]
Type=forking
ExecStart=/etc/autossh.local
[Install]
WantedBy=multi-user.target
Alias=autossh.service

4.2.2 編輯調用的普通腳本

vim /etc/autossh.local

添加如下內容

#!/bin/bash -e
sudo -u $user3 autossh -M 5000 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 5" -fCNR 6000:localhost:22 $user2@B_ip &

4.2.3 設置開機自啓動

sudo systemctl enable autossh # 加入自啓動
sudo systemctl start autossh # 啓動服務
sudo systemctl status autossh # 查看服務狀態

參考

https://www.cnblogs.com/kwongtai/p/6903420.html

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