0

In a shell script, I need to automatically fill the passphrase when running ssh-add.

I came across expect and tried this script, but with no luck:

expect -c "spawn ssh-add; expect -re \".*passphrase.*\"; send \"mypass\r\n\";"

The script doesn't throw any errors, but when it ssh it asks for password (meaning it didn't work).

EDIT: If run ssh-add and add the passphrase manually it works as expected.

fra-c
  • 29
  • 7
  • "when I ssh it asks me for password (meaning it didn't work)" You may be jumping to conclusions here. There are plenty of reasons why ssh might prompt for a password even after you've added a key to your agent. In fact, it's practically a FAQ on this site. – Kenster Oct 10 '15 at 16:33
  • 4
    Related: [How to make ssh-add read passphrase from a file?](http://stackoverflow.com/q/13033799/55075) – kenorb Oct 11 '15 at 12:59
  • @Kenster I edited the question, maybe it wasn't clear. Now let's jump together. – fra-c Oct 11 '15 at 14:35

2 Answers2

1

Here is a better way to automate it.

Create a script (e.g. ps.sh with executable flags) which prints your passphrase, e.g.:

#!/bin/sh
echo 'my_passphrase'

Then specify this script via SSH_ASKPASS variable, so it can be used for the authentication, e.g. :

$ cat id_rsa | SSH_ASKPASS=./ps.sh ssh-add -

Another way is to use named pipe:

$ mkfifo -m=600 ~/.fifo
$ cat id_rsa > ~/.fifo | SSH_ASKPASS=./ps.sh ssh-add ~/.fifo

You can read more about SSH_ASKPASS in man ssh-add:

If ssh-add does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS.

kenorb
  • 155,785
  • 88
  • 678
  • 743
  • This solution prints: `Enter passphrase for /dev/fd/63:`. The one you linked: `Enter passphrase for ~/.fifo:`. I don't understand :( – fra-c Oct 11 '15 at 14:38
  • @fra-c Corrected the example. Seems using pipe is necessary to load `SSH_ASKPASS` as per manual (in order to not have a terminal associated). – kenorb Oct 11 '15 at 17:52
  • 1
    Note you also need to set DISPLAY=dummy if you are in a script or tty without X – cmc Feb 12 '19 at 23:59
-2

If you use expect to pass the password, it means that you need to store the password somewhere along width the key - both readable by the same user. This does not enhance security at all since an attacker which is able to access the key would be able to access the password at the same time.

Simply use a key without a password.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • True, unless I pass the password as a parameter or delete the file afterwards. Also please don't reply if you don't know the answer. – fra-c Oct 11 '15 at 14:36