Why SSH always using first key accepted by server?
I have three SSH key pairs that can be found via ssh-add -L
; two keys are accepted by the remote server, but only one key can be used for GitHub, and I want to clone a GitHub repository via agent forwarding (hosting limits prevent deploy keys from working).
- The following can't log into GitHub and I found SSH perhaps uses the first key [
id_rsa
] listed viassh-add -L
, ignoring my-i
command, so agent forwarding only works after deleting keyid_rsa
:ssh -A -tt -i ~/.ssh/id_rsa_github user@ip 'ssh -T [email protected]'
- I tried adding
IdentityFile
andIdentitiesOnly
to~/.ssh/config
, but it was also unsuccessful
Is this normal behavior and how do I force SSH to use a specific key?
I think it's normal. The agent already knows some keys. Then -i
is an option of ssh
, it doesn't directly affect the agent. When asked, ssh
can add a key to the agent, but there is no straightforward way for it to remove keys or change their order. Moreover the agent is designed to serve to many clients. Some of them may need the keys you want to "hide" from this particular ssh
connection. You need a somewhat different approach.
Run the local ssh
as a subprocess of a dedicated agent and let ssh
add the desired key to the agent. This way the key will be the only one known to the relevant agent. Processes that use the general purpose agent (if any) will not be affected.
ssh-agent ssh -A -tt -o AddKeysToAgent=yes -i ~/.ssh/id_rsa_github user@ip 'ssh -T [email protected]'
From man 1 ssh-agent
:
command [arg ...]
If a command (and optional arguments) is given, this is executed as a subprocess of the agent. The agent exits automatically when the command given on the command line terminates.[…]
[…] The agent starts a command under which its environment variables are exported […]
[…]
[…]
ssh(1)
looks at these environment variables and uses them to establish a connection to the agent.The agent initially does not have any private keys. Keys are added using
ssh-add(1)
or byssh(1)
whenAddKeysToAgent
is set inssh_config(5)
. […]
From man 1 ssh
:
-o option
Can be used to give options in the format used in the configuration file.
From man 5 ssh_config
:
AddKeysToAgent
Specifies whether keys should be automatically added to a runningssh-agent(1)
. If this option is set toyes
and a key is loaded from a file, the key and its passphrase are added to the agent with the default lifetime, as if byssh-add(1)
.