If you have multiple servers to manage, you find yourself connecting to each of them a tedious task. Different private keys, different ports to connect, different hostnames and so many things to remember. That's why ~/.ssh/config
was introduced. This configuration file defines the behavior of SSH client.
Scenario 1: You are a developer. You don't want to type your password everytime you push into a Git Repo
Nowadays, almost all Git hosting solutions like Github and Bitbucket provide SSH Key based authentication. So, instead of typing site-based login password everytime you want to initiate a remote git command, you can use public-key authentication for that, and voila no passwords.
To do this, let's create a key pair for Git:
cd ~/.ssh
ssh-keygen -f git_key
Don't specify any passphrase. If you do, you will have to type it everytime or use a SSH agent to remember that passphrase for you.
So, if you ls
in the current directory, you would see:
$ ls
git_key git_key.pub
Now, we need to copy the contents of git_key.pub
to provider's settings. An easy way to do that is:
xclip -sel clip < ~/.ssh/git_key.pub
The contents will be in the clipboard that can be pasted anywhere.
So, how do we use the key with git? One way is to specify SSH command that git uses as:
GIT_SSH_COMMAND='ssh -i git_key' git push origin master
But this is too tedious. That's when config
comes to rescue. A sample config file may be:
Host bitbucket.org
User yourusername
HostName bitbucket.org
IdentityFile ~/.ssh/git_key
With this config in ~/.ssh/config
, git will now not ask for anything. You may have to change your remote URL to use SSH connection though. See Changing a remote's URL and Use the SSH protocol with Bitbucket for how to do it.
Scenario 2: Different Ports, Different Keys, Different Hostnames
Suppose you have following servers to manage:
- [email protected] | SSH Port: 2338 | Uses Key-based Authentication
- [email protected] | SSH Port: 3455 | Uses password based authentication
How would you remember all these details? Let's use ~/.ssh/config
:
Host ex-one
User dev
HostName one.example.com
Port 2338
PreferredAuthentications publickey
IdentityFile ~/.ssh/example_key
Host local-server
User root
HostName 10.1.33.2
Port 3455
With this config in place, you can login to first server using:
ssh ex-one
No need to remember anything except passwords or private keys' passphrase.
Conclusion
This is only a short introduction to ssh_config
. Many more things can be customized. To get detailed documentation, do man ssh_config
.
Happy SSHing