Linux: Using ssh-agent

Hi,

if you do not always want to enter your private key password/passphrase when using certificate based ssh or scp connections then ssh-agent is your friend 🙂 .

When ssh-agent starts it creates a UNIX socket to which ssh or scp connects to.

michael@debdev:~# ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-xpu8YEvBmBKf/agent.537; export SSH_AUTH_SOCK;
SSH_AGENT_PID=538; export SSH_AGENT_PID;

ssh-agent writes two lines with environment variables which must be set so that ssh or scp can use it. ssh-agent cannot set the environment variables directly because it cannot set variables in its parent process (bash).

michael@debdev:~# SSH_AUTH_SOCK=/tmp/ssh-xpu8YEvBmBKf/agent.537
michael@debdev:~# export SSH_AUTH_SOCK
michael@debdev:~# SSH_AGENT_PID=538
michael@debdev:~# export SSH_AGENT_PID

But there is also a shorter way. eval executes its 1st argument in the shells context. The command executed inside of the backticks `ssh-agent` tells the shell to take the output of the command an use it as a command line(s).

michael@debdev:~# eval `ssh-agent`
Agent pid 538
michael@debdev:~# set | grep SSH
SSH_AGENT_PID=538
SSH_AUTH_SOCK=/tmp/ssh-xpu8YEvBmBKf/agent.537

Ok ssh-agent is running now. Now you have to add a ssh private key.

michael@debdev:~# ssh-add .ssh/id_rsa
Enter passphrase for .ssh/id_rsa:
Identity added: .ssh/id_rsa (rsa-key-Michael-20180820)

If your key uses the default name id_rsa you can omit the parameter

michael@debdev:~# ssh-add
Enter passphrase for /home/michael/.ssh/id_rsa:
Identity added: /home/michael/.ssh/id_rsa (rsa-key-Michael-20180820)

Check it

michael@debdev:~# ssh debdev2 
Linux debdev 4.9.0-7-686 #1 SMP Debian 4.9.110-3+deb9u2 (2018-08-13) i686
...

Your ssh-agent can also forwarded through a ssh connection to the connected machine and you can use it there too. Start the ssh session with -A

michael@debdev:~# ssh -A debdev2 
Linux debdev 4.9.0-7-686 #1 SMP Debian 4.9.110-3+deb9u2 (2018-08-13) i686
...
michael@debdev2:~# ssh debdev3
....

Michael

Leave a Reply