如何以编程方式查找默认 ssh 密钥?

Dre*_*rew 6 ssh bash ssh-keys

根据我的大部分经验,默认情况下,ssh将在 ~/.ssh/id_rsa(.pub) 中查找默认密钥对。

\n\n

有时,我尝试编写脚本来利用这个默认的关键位置,但最终我对其进行了硬编码(例如DEFAULT_KEY_LOCATION="${HOME}/.ssh/id_rsa"或类似的东西),我觉得这是一个 BadThing\xe2\x84\xa2。

\n\n

是否有任何环境变量或 ssh 工具的输出可以告诉我用户默认密钥的位置?

\n\n

例如,是否有类似的命令ssh-defaults --key-location或环境变量 $SSH_DEFAULT_KEY?

\n

met*_*com 4

从 ssh 的手册页:

\n\n
     -i identity_file\n         Selects a file from which the identity (private key) for public\n         key authentication is read.  The default is ~/.ssh/identity for\n         protocol version 1, and ~/.ssh/id_dsa, ~/.ssh/id_ecdsa and\n         ~/.ssh/id_rsa for protocol version 2.  Identity files may also be\n         specified on a per-host basis in the configuration file.  It is\n         possible to have multiple -i options (and multiple identities\n         specified in configuration files).  ssh will also try to load\n         certificate information from the filename obtained by appending\n         -cert.pub to identity filenames.\n
Run Code Online (Sandbox Code Playgroud)\n\n

随后,如果它位于 ssh 可以自动找到的位置,则根本不需要指定路径。IE

\n\n
ssh -i ~/.ssh/id_rsa foo@bar.com\n
Run Code Online (Sandbox Code Playgroud)\n\n

\n\n
ssh foo@bar.com\n
Run Code Online (Sandbox Code Playgroud)\n\n

两者都会以相同的方式工作。如果您需要以编程方式查找密钥位置,而不是使用 ssh(即填充授权密钥),您可以检查配置文件检查的所有位置,并解析 ssh_config 文件以查找单个主机条目。来自 man ssh_config:

\n\n
         The file name may use the tilde syntax to refer to a user\xe2\x80\x99s home\n         directory or one of the following escape characters: \xe2\x80\x98%d\xe2\x80\x99 (local\n         user\xe2\x80\x99s home directory), \xe2\x80\x98%u\xe2\x80\x99 (local user name), \xe2\x80\x98%l\xe2\x80\x99 (local host\n         name), \xe2\x80\x98%h\xe2\x80\x99 (remote host name) or \xe2\x80\x98%r\xe2\x80\x99 (remote user name).\n
Run Code Online (Sandbox Code Playgroud)\n\n

因此,您还必须解析此格式以查找单个文件(如果已定义)。

\n