Skip to content

Instantly share code, notes, and snippets.



Last active Mar 22, 2020
What would you like to do?
Load SSH key into ssh-agent from a veracrypt-encrypted drive when it's plugged in
ACTION=="add", KERNEL=="sd?", ATTRS{serial}=="SERIAL_NUMBER_OF_USB", RUN+="/usr/local/bin/load-ssh-keys"
# Author Ando Roots <> 2016
# Licence: MIT
# Requirements: VeraCrypt and `ssh-agent` installed, Ubuntu environment
# Known problems: notify-send might not always work. All open nautilus windows will be killed.
# The following program is meant to be run by udev when a Veracrypt-encrypted USB drive
# is inserted. The script mounts the drive, prompts for passwords and loads SSH keys into ss-agent.
# Customize as needed. More at
# The braces and '&' "group" the enclosed program into one logical unit and send it to the background.
# This is done because the scripts run by udev should be very quick to exit, for it has a timeout value
# (and this script calls for user input).
# The DISPLAY variable tells VeraCrypt where to display the password prompt window
export DISPLAY=:0
# Change this to your UNIX username
# Xauthority is needed to be "authorized" to display something on the screen (password prompt)
export XAUTHORITY=/home/$LOGNAME/.Xauthority
# This tells us the address to a ssh-agent socket (how one can connect to ssh-agent)
export SSH_AUTH_SOCK=`find /tmp -type s -name agent.\* 2>/dev/null`
# DBUS address is needed to display notify-send messages
GNOME_PID=$(pgrep gnome-session)
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$GNOME_PID/environ|cut -d= -f2-)
# Script execution, in order:
# - mount the encrypted drive (prompt for password)
# - close the Nautilus window that pops up for a new mounted device
# - add the SSH key to ssh-agent (prompt for password)
# - unmount the encrypted drive
# - display a notification that the key is loaded
# if any of the above steps failed, display a failure notification
veracrypt -m ro $DEVNAME /media/keyring && \
killall nautilus && \
ssh-add -c -t 8h /media/keyring/work/id_rsa && \
veracrypt -d $DEVNAME && \
sudo -u $LOGNAME notify-send -i media-removable 'SSH keys loaded' "`ssh-add -l`" && \
sudo -u $LOGNAME notify-send -i emblem-unreadable 'Failed to load SSH keys' 'Investigate manually'
} &
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.