ssh-add 添加 .ssh 目录中的所有私钥

Mat*_*ark 7 grep ssh find xargs ssh-agent

在我的日常工作中,我需要通过ssh 连接到各种机器,所有这些机器我都有不同的私钥。

当我开始一个新的 shell 会话时——只有我的默认 id_rsa 被添加到 ssh 密钥链中——我一直在运行

ssh 添加 ~/.ssh/*

然而,当添加类似~/.ssh/config 之类的内容时,这也会尝试并失败

使用find/ grep,我怎样才能添加有效的私钥文件?

Dop*_*oti 14

有点绕,但是:

for possiblekey in ${HOME}/.ssh/id_*; do
    if grep -q PRIVATE "$possiblekey"; then
        ssh-add "$possiblekey"
    fi
done
Run Code Online (Sandbox Code Playgroud)

您还可以在指令之外的自己的指令中将所有键添加到您的~/.ssh/configeach 中:IdentityFileHost

# Global SSH configurations here will be applied to all hosts
IdentityFile ~/.ssh/id_dsa
IdentityFile ~/.ssh/id_project1
IdentityFile ~/.ssh/id_someotherkey

Host somespecifichost.example.com
    IdentityFile ~/.ssh/id_specifichostonlykey
Run Code Online (Sandbox Code Playgroud)

后者,老实说,更好,方法具有额外的好处,即不会突然拿起您添加的新密钥,而无需您将其显式添加到“钥匙圈”中。

  • 不幸的是,如果您有很多密钥,这可能会阻止您连接到服务器,并声称“身份验证失败次数过多”,因为它会为所有服务器逐一尝试每个密钥,并且在尝试一定数量的错误密钥后会断开连接。 (2认同)

小智 5

您实际上并不需要find,您可以使用递归 grep 使用该l标志仅发送匹配的文件名:

grep -slR "PRIVATE" ~/.ssh/ | xargs ssh-add