SSH or secure shell is a network protocol for operating networking services securely over network. It uses encryption standards to securely connect and login to the remote system. It stores a public key in the remote system and private key in the client system.
Generate SSH key
You can generate such ssh key pair with this command:
gotanbl:~>ssh-keygen
It will propmpt for a key location(name of the key, folder usually is /home/user/.ssh/) and key passphrase(this is optional).
With this command, you generate two files:
- Private key, must be secure and only for you
- Public key, finish with .pub and which can be shared with others
Connect to the remote host via SSH
- Copy public key to remote system
ssh-copy-id -i PUBLIC_KEY USER@REMOTE_HOST
- Remote system ask for password
- Connect to remote system
ssh USER@REMOTE_HOST
Using SSH config file
If you are regularly connecting to multiple remote systems over SSH, you’ll find that remembering all of the remote IP addresses, different usernames, non-standard ports, and various command-line options is difficult, if not impossible.
OpenSSH give a nice solution with config file in which you can configure per-user configuration for each remote machine you connect to.
Config file is stored in .ssh folder under user’s home directory.
gotanbl:~>touch ~/.ssh/config
gotanbl:~>chmod 600 ~/.ssh/config
SSH config file take the following structure:
Host hostname1
SSH_OPTION value
SSH_OPTION value
Host hostname2
SSH_OPTION value
Host *
SSH_OPTION value
The contents of the SSH client config file is organized into stanzas (sections). Each stanza starts with the Host directive and contains specific SSH options that are used when establishing a connection with the remote SSH server.
Indentation is not required but is recommended since it makes the file easier to read.
The Host directive can contain one pattern or a whitespace-separated list of patterns. Each pattern can contain zero or more non-whitespace character or one of the following pattern specifiers:
- * -> Matches zero or more characters. For example, Host * matches all hosts, while 192.168.0.* matches hosts in the 192.168.0.0/24 subnet
- ? -> Matches exactly one character. The pattern, Host 10.10.0.? matches all hosts in 10.10.0.[0-9] range
- ! -> When used at the start of a pattern, it negates the match. For example, Host 10.10.0.* !10.10.0.5 matches any host in the 10.10.0.0/24 subnet except 10.10.0.5.
The SSH client reads the configuration file stanza by stanza, and if more than one patterns match, the options from the first matching stanza take precedence.
More details about all possible config directives at https://man.openbsd.org/OpenBSD-current/man5/ssh_config.5
[Example of config file]
If we connect to server:
gotanbl:~>ssh john@dev.example.com -p 2322
For this server config file would be:
Host dev
HostName dev.example.com
User john
Port 2322
IdentityFile ~/.ssh/dev
Now, you can connect to server with:
gotanbl:~>ssh dev