SSH is an encrypted protocol used to connect between two systems. It’s widely used to gain access to remote server and run shell commands. It is also a common thing we use with VCS like github, gitlab etc.
SSH Key Generation
Creating ssh key is pretty simple, the CLI generates a public and private key pair. The public key is shared with the server and the private key is kept secret.
ssh-keygen -t rsa -b 4096
By default, we get a private key id_rsa
and public key id_rsa.pub
in ~/.ssh
directory.
Using SSH
Before connecting, we need to add the public key to the server. We can do this by copying the public key to the server
- add the public key to
~/.ssh/authorized_keys
file on the server.
cat ~/.ssh/id_rsa.pub | ssh username@server_ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
or
- using
ssh-copy-id
ssh-copy-id username@server_ip
To establish a connection to a remote server, we use the ssh
command followed by the username and the server IP address.
ssh username@server_ip
This will connect to the server
If the key is not successfully added to the server, the server will prompt for the password.
Using Multiple SSH Keys
We can also configure to use multiple ssh keys for different servers. This can be done by adding the following configuration to ~/.ssh/config
file.
For example, if we have different keys for gitlab
and github
, we can add the following configuration to ~/.ssh/config
file.
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa_gitlab
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
Debugging SSH
If we are facing issues with the ssh connection, we can use the -v
flag to get more information about the connection.
ssh -v username@server_ip
This will print the debug information about the connection.
It will show which key is being used, which key is being offered, and the reason for the connection failure.
Debugging Network
We can discover the hosts by using host
command.
host github.com
Anyway, network debugging tools like ping
, traceroute
, mtr
are another story.