Force SSH Client to use specific private key
Overview
While SSH is an essential tool for system administrators and developers, repeatedly specifying key files and connection parameters can become cumbersome, especially when managing multiple servers. Fortunately, SSH config files provide a solution to streamline these connections, making the process more efficient and user-friendly.
For example, a standard CLI (command line interface) SSH command may look as follows:
ssh -i ~/.ssh/my_specific_private_key [email protected]
Understanding SSH Config Files
SSH config files allows you to define various configuration parameters for SSH connections. By creating a centralized configuration file, you can avoid the need to specify key files, usernames, and other connection details each time they connect to a server. Instead, the configuration file automates these processes, simplifying the overall SSH experience.
Creating an SSH Config File
To get started, create an SSH config file in your home directory or within the .ssh directory (on MacOS this will be found at /Users/your_name/.ssh). The default filename is config. You can use a text editor of your choice to create or modify this file. Here's a basic template:
# ~/.ssh/config
# Server 1 example
# This is the CLI equivalent of typing: ssh -i ~/.ssh/my_private_key [email protected]
# Now you only need to type: ssh server1
Host server1
HostName 10.2.25.5
User root
IdentityFile ~/.ssh/my_private_key
# Server 2 example
# This is the CLI equivalent of typing: ssh -i ~/.ssh/my_private_key2 [email protected]
# Now you only need to type: ssh server2
Host server2
HostName example.com
User username
IdentityFile ~/.ssh/my_private_key2
Explanation of the config key components:
- Host: This is a label for the specific configuration block. It represents the name or alias you want to use when connecting to the server. For example, you can now type from the command line: ssh server1
- HostName: Specifies the actual domain name or IP address of the server.
- User: Defines the username used for connecting to the server. If omitted, your local username will be used.
- IdentityFile: Specifies the location of the private key file. This eliminates the need to use the -i option with every SSH command.
Connecting Without Specifying Options
Once your SSH config file is set up, connecting to a server is as simple as:
ssh server1
This command will automatically use the specified username, hostname, and private key from the configuration file.