IN-Decent

Re-decentralizing internet with free software

Make Use of ssh_config File to Store SSH Connection Configurations

Posted at — May 28, 2020

When making an ssh connection, instead typing full hostname, port number or username each time it can be stored in user’s local ssh config file (~/.ssh/config) to save time.

This config file begins with Host directive and all configurations specified below applies to hosts matching the pattern specified in Host directive. Empty lines and lines starting with # are ignored.

Say I’m using below command to ssh into my dev server,

ssh -i ~/.ssh/dev_id_rsa -p 1222 myuser@devel.mydomain.com

This ssh command can be simplified by storing all configurations for the server in ~/.ssh/config as below:

Host dev

 User myuser
 Port 1222
 IdentityFile ~/.ssh/dev_id_rsa
 HostName devel.mydomain.com

Then next time I just have to type just the below command to ssh into server.

ssh dev

This file is read by scp and sftp commands as well, so for copying a file to dev server using scp, I just have to do:

scp myconfig dev:configs/myconfig

Also, wild cards can be used for hostnames and it will be expanded using %h variable. It can be used in HostName parameter like below,

Host myprod0*

 User root
 Port 1222
 IdentityFile ~/.ssh/prod.key
 HostName %h.mydomain.com

Also, local port forwardings as explained in Forward Local Connections to Remote Hosts With SSH Tunneling can be simplified as below,

Host tunnel_grafana

 User myuser
 Port 22
 LocalForward localhost:3000 192.168.0.20:3000
 HostName remotehost

Then I can just quickly create a tunnel using below command,

ssh -fNT tunnel_grafana

References:

  1. Simplify Your Life With an SSH Config File
  2. OpenSSH Config File Examples
  3. ssh_config manual page