配置公网ssh服务

1、By default, SSH daemon is only listening on 127.0.0.1, so we won’t be able to access to our forwarded ports from outside. To get it listen on the interface connected to Internet we must enable GatewayPorts option in SSH server's configuration.
默认情况下,SSH守护程序只侦听127.0.0.1,所以我们将无法从外部访问我们转发的端口。 要让它在连接到Internet的接口上侦听,我们必须在SSH服务器的配置中启用GatewayPorts选项。

vim /etc/ssh/sshd_config
然后GatewayPorts yes在文件的底部添加。
或者sed -i s/"#GatewayPorts no"/"GatewayPorts yes"/g /etc/ssh/sshd_config

2、为防止SSH登录自动超时,修改下面参数每60秒会发一个KeepAlive请求
vim /etc/ssh/sshd_config
修改server端的配置文件/etc/ssh/sshd_config

# server每隔60秒给客户端发送一次保活信息包给客户端
ClientAliveInterval 60

# server端发出的请求客户端没有回应的次数达到86400次的时候就断开连接,正常情况下客户端都会相应
ClientAliveCountMax 86400

创建脚本

添加免密配置

使用ssh-copy-id 公网IP, 复制本地的公钥到公网的授权文件。配置完后测试一下ssh user@公网IP

复制脚本,替换里面的user@公网IP

#!/bin/bash

# 假设forward_rules.conf文件包含了所有的远程转发规则
forward_rules_file="forward_rules.conf"

if [ ! -f "$forward_rules_file" ]; then
  echo "Error: File $forward_rules_file does not exist."
  exit 1
fi

while IFS=: read -r remote_ip remote_port local_ip local_port
do
  PID=$(ps -ef | grep -v grep | grep  "$remote_ip:$remote_port:$local_ip:$local_port" | awk '{ print $2 }')

  if [ -z "$PID" ]; then
    echo "Application is already stopped"
  else
    echo "Killing PID $PID"
    kill -9 "$PID"
  fi

  echo "Starting service with remote forwarding $remote_ip:$remote_port:$local_ip:$local_port..."
  #nohup ssh -CqTnN -R "$remote_ip:$remote_port:$local_ip:$local_port" user@公网 > /dev/null 2>&1 &
done < "$forward_rules_file"

添加需要端口映射配置文件

创建forward_rules.conf文件添加内容, 前面是公网IP端口,后门是本地地址和端口

4x.9x.2x5.xx:90x0:127.0.0.1:90x0

执行上面脚本,看一下公网上面有没有暴露出来端口

netstat -

参考文章:

https://blog.csdn.net/vic_qxz/article/details/98482385