摘要
ssh可以实现内网穿透,将对方的某个端口的数据转到自己指定的端口,或者将自己的某个端口转到另一个端口。
主机情况
A ——-> B ——-> C
手头的电脑 服务器 不在手头的电脑
C 电脑执行
sudo apt install -y autossh
autossh -M 5000 -o "ServerAliveInterval 30" -NR 6000:localhost:22 B_user@B_ip &
命令含义:用本地的5000端口接收B服务器的6000端口发送回来的数据并转发到本地的22端口
B 电脑执行
ssh C_user@localhost -p 6000
如果可以执行表示成功!
autossh命令命令参数解释如下:
-f 后台运行
-C 允许压缩数据
-N 不执行任何命令
-R 将端口绑定到远程服务器,反向代理
-L 将端口绑定到本地客户端,正向代理
-p 转发服务器B的SSH登录端口号,默认为22
如果想从A直接连接C
B 电脑执行
ssh -fCNL "*:3000:localhost:6000" localhost
此时输入B_user密码。
A 电脑执行
ssh -p 3000 C_username@B_ip
配置自启动
配置 ubuntu 18.04 自启动
cat /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
cat /etc/autossh.local
#!/bin/sh -e
sudo -u C_user autossh -M 5000 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 5" -NR 6000:localhost:22 B_user@B_ip &
exit 0
执行命令
sudo systemctl enable autossh # 加入自启动
sudo systemctl start autossh # 启动服务
systemctl status autossh # 查看服务状态