ssh

Table of Contents

1. 内网穿透方法

目的:外部网络直接访问局域网络(比如ssh),把局域网某个设备的指定端口暴露给外部网络
约定:
公网机器为W,IP地址为 W_ip ,ssh监听端口为 W_port ,登陆用户名为 W_user
局域网机器为L,IP地址为 L_ip ,ssh监听端口为 L_port ,登陆用户名为 L_user
打算开放公网机器的 W_port2 端口用来连到局域网机器, W_port3 端口作为autossh自动断线重连的监听端口

步骤如下:

  • 开启公网机器的8086端口,防火墙设置
  • 在公网机器上修改/etc/ssh/sshd_config,加入
GatewayPorts yes 

然后重启ssh服务:

systemctl restart ssh.service 

不开启此选项,只能公网机器自己访问内网机器(监听的是localhost),个人计算机无法直接ssh内网机器

  • 然后在内网机器上:
ssh -gfnNTR 0.0.0.0:W_port2:L_ip:L_port W_user@W_ip -o ServerAliveInterval=300 -o ServerAliveCountMax=99999999

注释:

  -o ServerAliveInterval=300
    的意思是让ssh client每300秒就给server发个心跳,以免链路被RST.
  -f Requests ssh to go to background just before command execution.
    让该命令后台运行 .
  -n Redirects stdin from /dev/null (actually, prevents reading from stdin).

  -N Do not execute a remote command.
    不执行远程命令 .
  -T Disable pseudo-tty allocation.
    不占用 shell .
  -g Allows remote hosts to connect to local forwarded ports.
  • 只执行成功后会发现公网机器监听了端口52013,在外网可以直接通过以下命令远程访问内网机器:
ssh L_user@W_ip -p W_port2
  • 设置无密码登录,内网电脑上,使用内网机器的账号密码,建立信任关系:
ssh-copy-id root@W_ip -p W_port2

2. 保持连接不断开

在服务器端, 可以让服务器发送“心跳”信号测试提醒客户端进行保持连接
通过修改 sshd 的配置文件,能够让 SSH Server 发送“心跳”信号来维持持续连接,下面是设置的内容

打开服务器 /etc/ssh/sshd_config,我在最后增加一行

ClientAliveInterval 60
ClientAliveCountMax 1

这 样,SSH Server 每 60 秒就会自动发送一个信号给 Client,而等待 Client 回应,(注意:是服务器发心跳信号,不是客户端,这个有别于一些 FTP Client 发送的 KeepAlives 信号哦~~~),如果客户端没有回应,会记录下来直到记录数超过 ClientAliveCountMax 的值时,才会断开连接。

如果你没有服务器端管理权限, 在客户端进行设置也可以实现
只要在/etc/ssh/ssh_config文件里加两个参数就行了

1 TCPKeepAlive yes
2 ServerAliveInterval 120
3 ServerAliveCountMax 30

前一个参数是说要保持连接,后一个参数表示每过5分钟发一个数据包到服务器表示“我还活着”

如果你没有root权限,修改或者创建~/.ssh/ssh_config也是可以的

在这种方法中, 如果你只想针对某一个ssh连接进行持续, 你可以将上述配置文件复制一下进行修改然后在连接的时候使用 -F参数进行配置文件的指定。 当然因为只需要修改两个参数, 你也可以直接在连接命令中进行设定即:

ssh -o TCPKeepAlive=yes -o ServerAliveInterval=120 -o ServerAliveCountMax=30 pswzyu@nuihq.com -p 12345678

使用autossh自动断线重连

autossh -p 22 -M W_port3 -fcNR -o "PubkeyAuthentication=yes" -o "StrictHostKeyChecking=false" -o "PasswordAuthentication=no" -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R *:W_port2:localhost:L_port W_user@W_ip

Author: Face2wind

Created: 2026-09-18 Fri 18:16

Validate

粤ICP备2026139951号