端口转发

2023年01月03日 | 分享 | 点击首评

记录下端口转发的代码,用途挺广泛

ssh -R 1234:0.0.0.0:5678 root@ip

转发本地端口5678到服务器端口1234上,以实现外网可以访问本地端口,本地无需静态公网ip

 

另:

默认sshd gateway是关闭的,需要打开后才可以,不然只能对应服务器的本地端口才可以访问

vi /etc/ssh/sshd_config
GatewayPorts yes
systemctl restart sshd.service

ssh很容易因为网络断开,我用openAI写了个判断掉线重连的代码

#!/bin/bash
while true; do
  if curl --max-time 10  --output /dev/null --silent --head --fail "http://ip:5678"; then
    echo "URL is online"
  else
    echo "URL is offline"
    ssh -CqTnN -R 1234:0.0.0.0:5678 root@ip
  fi
  sleep 10   # 等待 10 秒后再次检查
done

或者使用autossh来实现

Mac安装autossh(其他环境自行搜索下载)

brew install autossh

转发命令

autossh -o "StrictHostKeyChecking=false" -M 2222 -NR 1234:0.0.0.0:5678 root@ip

StrictHostKeyChecking=false 连接新主机时不进行公钥确认

-M 在本机2222端口监视 SSH 连接状态

-N 意思是不执行远程命令

-R 意思是将远程主机(外网服务器)启动1234的端口数据转发到本地(内网服务器)的5678端口上

-f 后台运行,kill `pgrep autossh`退出后台

发布评论