需要机器一启动就自动连上远端(内网穿透、反向隧道、采集机回传),直接写 ~/.ssh/config 不够,因为开机时没有交互会话。可靠做法是交给 systemd 管理,或用 autossh 保活。

前提:免密与 host key

  • ssh-keygen -t ed25519 生成密钥,ssh-copy-id user@远端IP 推送公钥。
  • 首次连接会问 yes/no,systemd 里没人应答就会失败。先手工连一次,或写 StrictHostKeyChecking=accept-new。
  • 用 root 运行时密钥在 /root/.ssh 下,不是当前用户的。

方案一:systemd 服务

[Unit]
Description=auto ssh tunnel
After=network-online.target
Wants=network-online.target

[Service]
User=ubuntu
ExecStart=/usr/bin/ssh -N -o ServerAliveInterval=30 -o ExitOnForwardFailure=yes -R 2222:localhost:22 user@远端IP
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

存为 /etc/systemd/system/autossh.service,执行 systemctl daemon-reload && systemctl enable --now autossh。Restart=always 让它掉线自动重连。

方案二:autossh

apt install autossh,命令加 -M 0 关闭监控端口,靠 SSH 自身的 ServerAliveInterval 探活:autossh -M 0 -f -N -R 2222:localhost:22 user@远端IP。适合不支持 systemd 的老系统。

排查时看 journalctl -u autossh -f,常见失败是网络未就绪(加 After=network-online.target 并 systemctl enable systemd-networkd-wait-online)和密钥权限过宽(chmod 600)。