I want to configure my laptop to clear all my SSH keys from the authentication agent when I close the lid of my laptop.

Clearing the keys can be done by running ssh-add -D. Running a script when closing the lid can be achieved by adding the script to /etc/pm/sleep.d/.

However, when I add the command su work -c "ssh-add -D" to a script in the directory, I get the error message:

Could not open a connection to your authentication agent.

How can the command be properly run from a script that is being run as root?


You need SSH_AUTH_SOCK in the environment of your script. This can be done by executing

declare -p SSH_AUTH_SOCK >~/.ssh-env

as part of your login process. The script then has to source this file before it executes ssh-add:

. ~/.ssh-env
  • Is the value sensitive at all? Should you chmod 600 ~/.ssh-env it?
    – Sampo
    Feb 3 '16 at 11:23
  • 1
    @Sampo No, it isn't. It can probably be determined by other users anyway (depending on the access rights in /proc). Just the access to the socket itself should be safe. Feb 3 '16 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.