SSH Key Priority – Prioritize Explicit SSH Key Over SSH-Agent Keys

sshssh-agentssh-keys

I have a bunch of ssh keys loaded semi-permanently into ssh-agent. ssh-add -L lists 6 keys.

I also have other keys which are stored separately; let's say, on a USB stick. I exactly don't want to keep them handy all the time. Let me call one of them square.key.

The problem is this: on those occasions when I need square.key, I'm okay with plugging the USB stick and specifying -i /path/to/square.key — but it doesn't work. -v reveals why:

debug1: Will attempt key: /home/ulidtko/.ssh/key1 RSA SHA256:<redacted> agent
debug1: Will attempt key: /home/ulidtko/.ssh/key2 RSA SHA256:<redacted> agent
debug1: Will attempt key: key3@localhost ED25519 SHA256:<redacted> agent
debug1: Will attempt key: key4@localhost RSA SHA256:<redacted> agent
debug1: Will attempt key: key5@localhost ed25519 ED25519 SHA256:<redacted> agent
debug1: Will attempt key: key6@localhost ECDSA SHA256:<redacted> agent
debug1: Will attempt key: /path/to/square.key ED25519 SHA256:<redacted> explicit
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering public key: /home/ulidtko/.ssh/key1 RSA SHA256:<redacted> agent
debug1: Authentications that can continue: publickey,password
debug1: Offering public key: /home/ulidtko/.ssh/key2 RSA SHA256:<redacted> agent
debug1: Authentications that can continue: publickey,password
debug1: Offering public key: key3@localhost ED25519 SHA256:<redacted> agent
debug1: Authentications that can continue: publickey,password
debug1: Offering public key: key4@localhost RSA SHA256:<redacted> agent
debug1: Authentications that can continue: publickey,password
debug1: Offering public key: key5@localhost ed25519 ED25519 SHA256:<redacted> agent
debug1: Authentications that can continue: publickey,password
debug1: Offering public key: key6@localhost ECDSA SHA256:<redacted> agent
Received disconnect from 46.101.206.106 port 22:2: Too many authentication failures
Disconnected from 46.101.206.106 port 22

Somehow, ssh thinks it's a great idea to try every key from ssh-agent BEFORE the square.key which I pass manually on the command line. And so this triggers Too many authentication failures on the server; square.key is never offered.

Is there a way to override or configure this order? I'd like to continue using ssh-agent, but ssh to respect my manually-set commandline flags, and try the -i "explicit" keys first.

Best Answer

One workaround is to pass IdentityAgent=none, either on the same commandline:

ssh -i /path/to/square.key -o IdentityAgent=none remote.server.net

or equivalently, via the ~/.ssh/config:

Host remote.server.net
    IdentityFile /path/to/square.key
    IdentityAgent none