I have a bunch of keys added to the ssh-agent, keys to servers, repositories, etc.

Is there a way to remove all the ssh keys added to ssh-agent when the user locks the system?

My system right now is Ubuntu Desktop 16.04 with GNOME 3


You can watch for the events in DBUS and on lock call ssh-add -D to remove all keys from the agent:

dbus-monitor --session "type='signal',interface='org.gnome.ScreenSaver'" |
  while read x; do
    case "$x" in 
      *"boolean true"*) echo SCREEN_LOCKED; ssh-add -D;;
      *"boolean false"*) echo SCREEN_UNLOCKED;;  

But you need to export the SSH_AUTH_SOCK environment variable to this script, so it would be able to access your agent.

You can store the above into the script clean_lock.sh, set execute bits (chmod u+x clean_lock.sh) and run the script in background ./clean_lock.sh &.

  • I have checked that answer. But how to run a script on background that keeps listening to the state changed. – Starx Nov 1 '16 at 13:07
  • Oh hang on, that worked. – Starx Nov 1 '16 at 13:09
  • I tried this answer as it said it was what worked of 16.04 – Starx Nov 1 '16 at 13:09

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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