如果指纹已知,如何以编程方式接受 SSH 主机密钥?

cer*_*cem 5 ssh

我不想使用-o StrictHostKeyChecking=no选项,但我想将服务器的公钥保存在文件中,并在每次连接时使用该公钥,即使 IP 地址或端口发生更改。

-o UserKnownHostsFile=myfile使用选项时,如果我们通过不同的 IP 连接同一台机器,ssh 仍然会要求验证。

如何判断ssh将公钥保存在不同的位置并在当前连接中使用该公钥?用法示例:

# there is no 'foo-public.key' file at this moment
ssh -o TheMagicalOption=foo-public.key user@example.com -p 1234

The authenticity of host 'xxxxxxxx' can't be established.
ECDSA key fingerprint is SHA256:LR5wDKrEmHD0QhRcAmxTxBnzWIRmNUfJyeawhKw+W38.
Are you sure you want to continue connecting (yes/no)? [YES]

# 'foo-public.key' is created at this point 
on-target $ exit 

# another port forward is made, so the same server is on port 5678
ssh -o TheMagicalOption=foo-public.key user@example.com -p 5678
# not asking the same verification question
on-target $     
Run Code Online (Sandbox Code Playgroud)

小智 3

您可以使用

ssh -o StrictHostKeyChecking=ask \
    -o HashKnownHosts=no \
    -o CheckHostIP=no \
    -o UserKnownHostsFile=example_fp \
    -p 1234 user@example.com
Run Code Online (Sandbox Code Playgroud)

获取密钥。

  • HashKnownHosts=no确保主机名将以明文形式保存
  • CheckHostIP=no仅用于通过名称来识别主机

结果example_fp将是一行,开头如下

[example.com]:1234 ecdsa-sha2-nistp521 AAAA...
Run Code Online (Sandbox Code Playgroud)

当在第一个连接上使用标准端口 22 时,您会看到

example.com ecdsa-sha2-nistp521 AAAA...
Run Code Online (Sandbox Code Playgroud)

因此,要么在第一次连接时使用端口 22,要么随后编辑文件以删除端口号。下次连接时,该行将匹配任何端口号。