15

I can add pem files to my SSH agent very easily using ssh-add, like so:

$ ssh-add /home/jsmith/keys/mytest.pem

But I can't seem to remove them:

$ ssh-add -d /home/jsmith/keys/mytest.pem
Bad key file /home/jsmith/keys/mytest.pem: No such file or directory

The pem file still exists though... I haven't moved or changed it in any way. Why am I having so much trouble removing this pem file from my SSH agent that I just added a moment ago? What's the correct way to do this?

I want to avoid using ssh-add -D (with a capital "D") because that would delete all of the identities from my SSH agent, and I only want to delete the one I've specified.

jww
  • 97,681
  • 90
  • 411
  • 885
Dasmowenator
  • 5,505
  • 5
  • 36
  • 50

3 Answers3

25

You have to use the public key for this. So first extract the public key and then remove it from the agent.

ssh-keygen -y -f /home/jsmith/keys/mytest.pem > /home/jsmith/keys/mytest.pub
ssh-add -d /home/jsmith/keys/mytest.pub

The man page mentions the "public" key as well: "if no public key is found at a given path, ssh-add will append .pub and retry".

Tony Stark
  • 2,318
  • 1
  • 22
  • 41
  • 2
    Thank you, this works! Though it seems very convoluted - is there really no way to just delete the pem file from your ssh keychain without jumping through hoops like this? – Dasmowenator Aug 05 '19 at 20:55
  • 2
    The technical answer is that the [command sent to an ssh agent to remove a key](https://tools.ietf.org/id/draft-miller-ssh-agent-01.html#rfc.section.4.3) identifies a key by its public portion. It's possible to derive the public portion of a key from the contents of a private key file, but apparently the ssh-add program doesn't contain logic to do that when deleting a key. – Kenster Aug 05 '19 at 21:08
  • Is this correct? The man page says `-d` is : ` -d Debug mode. When this option is specified ssh-agent will not fork and will writ e debug information to standard error`? – Chris Stryczynski Jul 10 '20 at 14:06
  • 1
    Man page for what? ssh-add? See https://linux.die.net/man/1/ssh-add. – Tony Stark Jul 10 '20 at 14:10
  • That's weird. Another man page say: *"-d Deletes the given identities from the agent. The **private** key files for the identities to be deleted should be listed on the command line."* Either way, the easiest way to drop the key in memory is to kill and restart the key-server. – not2qubit Jan 29 '22 at 11:45
4

The best alternative I've found is to re-add the same file but with a life-time of 1 second:

ssh-add -t 1 myfile.pem

It is easier to remember than extracting the public key.

MagMax
  • 1,645
  • 2
  • 17
  • 26
2

If you know the comment associated with the key you can simply get the public key from the agent and pipe it back in to delete it.

ssh-add -L | grep -F 'test@example.com' | ssh-add -d -
LennyLenny
  • 21
  • 1