SSH – Add All Private Keys in .ssh Directory with ssh-add

findgrepsshssh-agentxargs

In my day-to-day, I need to ssh to various machines, all of which I have a different private key for.

When I start a new shell session – only my default id_rsa is added to the ssh key chain – I have been running

ssh-add ~/.ssh/*

However this also trys to, and fails, when adding things like ~/.ssh/config

Using find / grep, how can I go about only adding valid private key files?

Best Answer

Slightly convoluted, but:

for possiblekey in ${HOME}/.ssh/id_*; do
    if grep -q PRIVATE "$possiblekey"; then
        ssh-add "$possiblekey"
    fi
done

You can also add all of your keys to your ~/.ssh/config each in their own IdentityFile directive outside of a Host directive:

# 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

The latter, honestly-better, method has the added perk of not suddenly picking up a new key that you've added without you explicitly adding it to the "keyring" as it were.