Skip to Content

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

ssh jump server

Complete step by step tutorial on how to configure ssh-agent and 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 
root@server:#$ eval "$(ssh-agent -s)"
Agent pid 69599
 
   2. Add the SSH key to the ssh-agent
root@server:#$ 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  keys by  the following command

ssh-add -L

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

ssh username@target_machine

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

ssh-add -D

You can stop SSH Agent by the following command

root@server:~$ eval "$(ssh-agent -k)"
Agent pid 182 killed

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 server

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

ssh -A user@gateway

 2.  Enable ssh-agent
# start the ssh-agent 
user@desktop:#$ eval "$(ssh-agent -s)"
Agent pid 69599
  3. Add the SSH key to the ssh-agent
user@desktop:#$ 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.

user@desktop:~# ssh -A user@gateway

user@gateway:~# 

#Now you can ssh to your production server

user@gateway:~# ssh user@production_server

user@production_server:~#

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

 
Read more about on SSH-Agent forwarding