无跳转机连接

本机:A,远程主机:B

要实现免密连接,A 需要有公钥和私钥对,将 A 的公钥放到远程主机 B 的 ~/.ssh/authorized_keys 中。当 A 请求连接 B 时,B 使用 authorized_keys 中的公钥加密一段话发送给 A,A 用 A 的私钥解密这段话,再发送给 B,由 B 验证如果验证成功,则实现 A——>B。

  1. 使用 ssh-keygen -t rsa 在 A 和 B 中产生公私钥(若 A 和 B 中已经存在则跳过)
  2. 将 A 的公钥 ~/.ssh/id_rsa.pub 放到 B 的 ~/.ssh/authorized_keys
  3. 配置 vscode remote ssh 插件,在 A 的 ~/.ssh/config 中写入:
Host B
HostName xxxxxx #B的ip
Port xx #端口
User xxx #用户名
IdentityFile ~/.ssh/id_rsa #A的私钥

使用跳转机连接

本机:A,跳转机:J1,跳转机:J2,远程主机:B

将 A 的公钥 ~/.ssh/id_rsa.pub 放到 J1、J2 和 B 的 ~/.ssh/authorized_keys 中,这样可行的原因是:

This configuration will open a background SSH connection to the jump box, and then connect via a private IP address to the target.

其余步骤和第一节一样,A 中 ~/.ssh/config 写入:

Host J1  
HostName xxxx
User xxx
IdentityFile ~/.ssh/id_rsa

Host J2
HostName xxxx
User xxx
IdentityFile ~/.ssh/id_rsa
ProxyCommand ssh -q -W %h:%p J1

Host B
HostName xxxx
User xxx
IdentityFile ~/.ssh/id_rsa
ProxyCommand ssh -q -W %h:%p J2