03. Using SSH Agent to Automate Login ssh-agent, ssh-add

The ssh-agent program is a daemon (a process that runs in the background) which stores your passphrases in memory, allowing you to easily access remote servers without typing a passphrase each time.

For our case, we have already created SSH keypairs with ssh-keygen and used ssh-copy-id to upload our private keys onto the authorized_keys file on our server. The only problem now is that we must input our passphrase upon every connection. Let's see how ssh-agent can help automate this task.

Running the SSH Agent and adding keys

To start the ssh-agent, input the command followed by bash.

$ ssh-agent bash

This will spawn a new bash process, in which ssh-agent runs in the background and stores the keys in memory. Now we can add our actual keys with ssh-add.

$ ssh-add
Enter passphrase for /home/user/.ssh/id_rsa: Identity added: /home/user/.ssh/id_rsa (/home/user/.ssh/id_rsa)

If your key is not in the canonical ~/.ssh directory, or has a different filename, type its path directly after the ssh-add command (e.g. ssh-add /path/to/file)

Congratulations! Now your passphrase has been added to the ssh-agent, and you will no longer need to input the passphrase. Now try logging into your server.

$ ssh user@
Last login: Mon Dec 21 05:19:49 2015 from [user@ ~]$

Remember that once you exit out of the bash terminal spawned with ssh-agent, your passphrases will be lost and you'll have to run ssh-agent and ssh-add again.

Checking if SSH agent is running

Sometimes you'll need to check whether the ssh-agent is running or not. We can do so by checking our processes.

$ ps aux | grep ssh-agent
user      2411  0.0  0.0  10616   524 ?        Ss   05:35   0:00 ssh-agent bash

Listing all keys added

To view the keys that have been successfully added to the ssh-agent, use the -l option.

$ ssh-add -l
2048 ec:39:69:3d:c4:8b:63:fd:57:a3:78:51:6d:cd:cd:46 /home/user/.ssh/id_rsa (RSA)

Take your Linux skills to the next level!

How Linux Works

Take your Linux skills to the next level! Try Linux & UNIX

In this completely revised second edition of the perennial best seller How Linux Works, author Brian Ward makes the concepts behind Linux internals accessible to anyone curious about the inner workings of the operating system. Inside, you'll find the kind of knowledge that normally comes from years of experience doing things the hard way.

$ Check price
39.9539.95Amazon 5 logo(114+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources