Saturday, December 3, 2016

Shorten ssh command using config file

If you are accessing remote servers frequently using ssh. You can save your ssh configuration (server Ip, port, user, key) to a file and reuse this configuration without entering these details repeatedly. This provides cleaner approach for ssh commands than creating command aliases (ex: alias qa-services='ssh -i ~/.ssh/key/services.pem ubuntu@124.17.27.185 -p 22'  )

SSH client obtains configuration data from the following sources in the bellow order:

           1.   command-line options
           2.   user's configuration file (~/.ssh/config)
           3.   system-wide configuration file (/etc/ssh/ssh_config)


We are going set the configuration in user's configuration file

Create a ssh client user configuration file in '~/.ssh/' directory with file name 'config'

Add following content to the file (~/.ssh/config)


 Host qa-services  
    HostName 124.17.27.185  
    User ubuntu  
    Port 22  
    IdentityFile ~/.ssh/key/services.pem  
 Host prod-db  
    HostName 124.21.151.26  
    User ubuntu  
    Port 22  
    IdentityFile ~/.ssh/key/db.pem  


Configuration keywords :
              HostName - hostname or public ip address.
     User - Specifies the user to log in as.
     Port - Specifies the port number to connect on the remote host.
     IdentityFile - Specifies a file from which the user's DSA, ECDSA, Ed25519 or RSA authentication identity is read.

Save the config file. Now you can access to your servers with simple commands like below.

 ssh qa-services 
 ssh prod-db

No comments: