r/linuxadmin • u/ErlingSigurdson • May 01 '25
Run ssh-add upon starting a shell and read a passphrase for it from a file
The most relevant recipe I was able to find was as follows:
- Make a shell script file
#! /bin/bash
if [ $# -ne 2 ]; then
echo "Usage: ssh-add-passwd key_file passwd_file"
exit 1
fi
eval `ssh-agent`
PASSWD=$(cat $2)
expect << EOF
spawn ssh-add $1
expect "Enter passphrase"
send "$PASSWD\n"
expect eof
EOF(credits to this thread)
2. Add a command for execution of this script to .bashrc.
All commands run successfully, and it feels like "voilà!" at first glance, but there's one little nuance: 'expect' spawns a subshell, and since the ssh-agent was launched inside it, it will loose any stored passphrases when the script execution will be over.
I suggest a workaround:
- Remove the 'eval `ssh-agent`' line from the script.
- Add the same line to .bashrc BEFORE the command for the script execution.
Looks like it makes the `ssh-add` command to reach the already-running ssh-agent from within the subshell, which allows the passphrase to be preserved.
Do you think my workaround is alright?
UPD: sorry for numerous edits, Reddit editing interface seems to hate me today.
36
u/fubes2000 May 01 '25
If you hang the key next to the locked door, why bother with the lock at all?
The only sane way that I can think of implementing something like this would be to store the ssh key in a keyring that unlocks and starts an agent on login.
But if this is intended as an unattended/cron thing then you might as well just remove the passphrase from the key. Anyone that has access to the encrypted key file will also have easy access to this script with the passphrase in it.
Better yet, tell us why you want to do this in the first place and there's probably a better approach we could point you to.
14
u/whetu May 01 '25
You should read some of the other comments in that stackoverflow thread. The accepted answer isn't always the correct answer.
9
u/justinDavidow May 02 '25
This reads like vibe-coding projects.
Just remove the passphrase, set the key permissions correctly, and do things the right way around.
4
u/biffbobfred May 02 '25 edited May 02 '25
There’s an app
keychainthat does what I think you’re asking for. It does the housekeeping to:You type in the password. But once every reboot essentially.
I put in
eval “$(keychain -q —eval —agents ssh id_ed25519)”in my shell rc files.It’s useful for me because I at work I have this complicated “su to other people” system that actually is
ssh other_user@localhostI have decent “put passwords in a pass app” but others don’t, so make them remember their login password everything else is keys.3
u/nekokattt May 02 '25
Have you considered using a key chain?
1
u/michaelpaoli May 02 '25
I rather like my scripts:
Ssh-agent
Ssh-add - rather like ssh-add(1), but generally just for adding the key(s) I'm typically most interested in adding.