autossh

autossh 是一个用于自动重启 SSH 会话的工具,特别适用于需要长期保持 SSH 隧道或端口转发的情况。它通过监控 SSH 连接状态,在连接断开时自动重新建立连接,从而提高连接的稳定性。

yum install autossh

 基本用法

autossh -M <monitor_port> -p <ssh_port> -i <identity_file> -R <remote_port>:localhost:<local_port> user@remote_host

参数说明:

  • -M <monitor_port>:指定一个端口用于监控 SSH 连接状态(可选,设为 0 可禁用)。
  • -p <ssh_port>:远程主机的 SSH 端口(默认是 22)。
  • -i <identity_file>:指定私钥文件。
  • -R-L:用于设置反向或正向端口转发。
  • user@remote_host:远程主机的用户名和地址。
  • 示例:建立一个反向隧道

    假设你想把本地的 8080 端口映射到远程主机的 8081 端口:
    bash
    复制
    autossh -M 20000 -R 8081:localhost:8080 user@remote.example.com
     

    ✅ 建议与注意事项

    • 使用密钥认证:避免使用密码登录,确保 SSH 密钥已配置并加入 ssh-agent
    • 设置重试间隔:可以通过环境变量 AUTOSSH_POLLAUTOSSH_GATETIME 控制重试行为。
    • 后台运行:可以结合 nohupsystemd 实现开机自启和后台守护。

    📘 示例:使用 systemd 创建服务(可选)

    创建一个服务文件 /etc/systemd/system/autossh-tunnel.service
    ini
    复制
    [Unit]
    Description=AutoSSH tunnel
    After=network.target
    
    [Service]
    Environment="AUTOSSH_GATETIME=0"
    ExecStart=/usr/bin/autossh  -M 0 -N -L 172.32.0.0:10023:10.10.15.3:22 -p 8225 admin@172.25.25.13 -o ServerAliveInterval=30 -o ServerAliveCountMax=3
    Restart=always
    User=root
    
    [Install]
    WantedBy=multi-user.target
     
    然后启用并启动服务:
     
    sudo systemctl daemon-reexec
    sudo systemctl daemon-reload
    sudo systemctl enable autossh-tunnel
    sudo systemctl start autossh-tunnel

     防火墙要放行 10022 端口

     

    sudo firewall-cmd --permanent --add-port=10022/tcp
    sudo firewall-cmd --reload

     这个admin账户一定是172.25.25.13的账户

    ssh -p 10023  admin@172.32.1.2

     

posted @ 2025-10-24 15:22  XXLLA  阅读(14)  评论(0)    收藏  举报