Skip to content

Instantly share code, notes, and snippets.

@djmitche
Created April 6, 2025 02:54
Show Gist options
  • Save djmitche/6e1500304adfb2ab33bd403b238edd10 to your computer and use it in GitHub Desktop.
Save djmitche/6e1500304adfb2ab33bd403b238edd10 to your computer and use it in GitHub Desktop.
keys.sh
#!/bin/bash
# Check if the script is run before sleep/hibernate
if [ "${1}" == "pre" ]; then
# Find running ssh-agent processes and their sockets for logged-in users
# Note: This logic might need adjustment depending on how ssh-agent is started
# (e.g., systemd user service, direct eval, gnome-keyring acting as agent).
logins=$(users | tr ' ' '\n' | sort -u)
for user in $logins; do
uid=$(id -u "$user")
# Attempt to find SSH_AUTH_SOCK in the user's environment
# Common location for user systemd/dbus started agents:
socket_path="/run/user/$uid/keyring/ssh"
if [ -S "$socket_path" ]; then
echo "Flushing SSH keys for user $user (UID $uid) via socket $socket_path before sleep..."
sudo -u "$user" DISPLAY=:0 SSH_AUTH_SOCK="$socket_path" ssh-add -D > /dev/null 2>&1 || true
# Fallback attempt via pgrep (less reliable for finding the *correct* agent)
# else
# pid=$(pgrep -u "$user" ssh-agent)
# if [ -n "$pid" ]; then
# export $(grep -z SSH_AUTH_SOCK /proc/$pid/environ | tr '\0' '\n')
# if [ -n "$SSH_AUTH_SOCK" ]; then
# echo "Flushing SSH keys for user $user (UID $uid) via pgrep/proc before sleep..."
# sudo -u "$user" DISPLAY=:0 SSH_AUTH_SOCK="$SSH_AUTH_SOCK" ssh-add -D > /dev/null 2>&1 || true
# fi
# fi
fi
done
fi
# Optional: You could add actions for "post" resume, but automatically
# re-adding keys is complex and potentially insecure if they have passphrases.
# It's usually better to manually add keys when needed after resume.
# if [ "${1}" == "post" ]; then
# # Actions after resume...
# fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment