Skip to Content

ssh-agent - How to configure ssh-agent forwarding ?

SSH Agent

SSH agent allows you to store ssh keys, and certificates on memory in unencrypted format. ssh-agent acts as an ssh key manager which allows you to use ssh keys without entering a passphrase every time you log in.

  1. Enable ssh-agent
# start the ssh-agent 
[email protected]:#$ eval "$(ssh-agent -s)"
Agent pid 69599
 
   2. Add the SSH key to the ssh-agent
[email protected]:#$ ssh-add ~/.ssh/id_rsa
 You can replace id_rsa with your key name. It will ask for a passphrase if you are using encrypted keys while adding.
 
  You can view the added  by  the following command

ssh-add -L

 
  Now you can ssh to the target machine without entering the passphrase

ssh [email protected]_machine

 
You can use the following command to remove the from ssh-agent

ssh-add -D

You can stop SSH Agent by the following command

[email protected]:~$ eval "$(ssh-agent -k)"
Agent pid 182 killed

SSH agent forwarding

SSH agent forwarding will allow you login to a distant remote machine by forwarding the SSH keys stored on your local SSH agent onto a host to which you are connecting. For example, you need to connect to your production servers via your gateway server. Then you can add your SSH key to your local desktop ssh-agent and it will forward to your production servers via your gateway server. So you need not add your SSH key to your gateway servers. 

 

  1. Create or open up the file at ~/.ssh/config

Enter the following text, and replace gateway with your server domain name or IP.
Host gateway
ForwardAgent yes 
 
 If we don't want to create a config file, you can use the " -A "  flag with the ssh command.  " -A "option enables forwarding of the authentication agent connection
 2.  Enable ssh-agent
# start the ssh-agent 
[email protected]:#$ eval "$(ssh-agent -s)"
Agent pid 69599
  3. Add the SSH key to the ssh-agent
[email protected]:#$ ssh-add ~/.ssh/id_rsa
 You can replace id_rsa with your key name. It will ask for a passphrase if you are using encrypted keys while adding.
 
4. SSH to your gateway machine. You can use -A option or you need to enable forwarding as mentioned in step 1.

[email protected]:~# ssh -A [email protected]

[email protected]:~# 

#Now you can ssh to your production server

[email protected]:~# ssh [email protected]_server

[email protected]_server:~#

You are successfully authenticated with the SSH key on your Desktop Machine.