内网穿透 - AutoSSH

  • 1207 字
  • 次阅读
  1. 1. 前言
  2. 2. 一键脚本
  3. 3. 手动安装
    1. 3.1. 远程机(公网机)设置SSH
    2. 3.2. 本地机(内网机)安装 & 设置
      1. 3.2.1. 1. 安装autossh
      2. 3.2.2. 2. 创建autossh服务
      3. 3.2.3. 3. 填入以下代码
      4. 3.2.4. 4. 设置开机自启并启动服务

前言

AutoSSH是基于原生ssh而实现端口转发, 本教程只演示内网穿透这一用途 为了穿透掉线重连实现无密码连接SSH, 远程机(公网机)请务必使用SSH-KEY的验证方式

一键脚本

以下为本人自己编写的一键脚本, 若不放心, 请移步后面的手动安装教程

1
bash <(curl -fsSL https://raw.githubusercontent.com/Slotheve/Shells/main/autossh.sh) 

手动安装

远程机(公网机)设置SSH

1
2
3
4
5
echo 'GatewayPorts yes' >> /etc/ssh/sshd_config && \ 
echo 'TCPKeepAlive yes' >> /etc/ssh/sshd_config && \
echo 'ClientAliveInterval 60' >> /etc/ssh/sshd_config && \
echo 'ClientAliveCountMax 3' >> /etc/ssh/sshd_config && \
systemctl restart sshd

本地机(内网机)安装 & 设置

1. 安装autossh

1
2
# apt apt install -y autossh lsof 
#yum yum install -y autossh lsof

2. 创建autossh服务

1
2
touch /etc/systemd/system/autossh.service 
# 创建空服务文件

3. 填入以下代码

1
2
3
4
5
6
7
8
9
10
11
[Unit] 
Description=AutoSSH
After=network-online.target

[Service]
User=root
ExecStart=/usr/bin/autossh -M 内网机未被占用随机端口 -NR 公网机未被占用随机端口(之后连接内网机所用):127.0.0.1:内网机内网ssh端口 root@公网IP -p 公网机公网ssh端口 -o "StrictHostKeyChecking no"
Restart=always

[Install]
WantedBy=multi-user.target

4. 设置开机自启并启动服务

1
2
3
systemctl daemon-reload 
systemctl enable autossh.service
systemctl start autossh.service

提示: 一般启动失败大概率是端口被占用了, 或者是ssh-key文件权限问题

分享
分享提示信息