ssh-add password protected key automatically


Install the ‘expect’ package.

Create a script like so:

#!/usr/bin/expect -f

spawn ssh-add /home/user/.ssh/<key_file><br /> expect "Enter passphrase for /home/user/.ssh/<key_file>:"<br /> send "<passphrase>\n";<br /> interact<br />

You can write the first line as “#!/usr/bin/expect -df” if you want to debug errors until you get it right.

Replace <key_file> with the private key (file) you want, and the with the password of the key file.

Save the script with any name you want, and make sure it is not readable by anyone other than the script’s owner, as it contains the password in plaintext.

Add a simple line to your ~/.bashrc file (or any other file if you have a different shell) to call the script.

 

For example, if the script is saved under /home/myuser/.ssh/add_ssh_keys.

$ chmod 700 /home/myuser/.ssh/add_ssh_keys  < run this to make sure it has the correct permissions.

/home/myuser/.ssh/add_ssh_keys < append this line to your bashrc file.

Open a new shell and try it out.