Mastering the SSH Config File: A Complete Guide
An in-depth guide to understanding and configuring the SSH config file for seamless remote connections across servers and systems.
If you regularly connect to multiple remote systems using SSH
(Secure Shell), you know how frustrating it can be to remember all the hostnames, IP addresses, ports, and authentication methods. Some servers use different usernames, while others require different SSH keys or custom ports.
Sure, you could save all these details in a separate text file and copy-paste them whenever needed. Or maybe create aliases to simplify commands. But there’s a better solution!
OpenSSH
allows you to define a per-user configuration file where you can store all your SSH connection details in one place. This means you can simply type ssh myserver
instead of remembering and typing a long command like:
ssh -i ~/.ssh/mykey.pem -p 2222 user@192.168.1.100
In this guide, we’ll explore the SSH client configuration file, understand its structure, and learn about the most useful configuration options.
Before we continue, we assume you are using a Linux
or macOS
system with OpenSSH
installed, as this guide specifically focuses on configuring SSH
in these environments. While other operating systems may have their own SSH
clients, the instructions and examples provided here are tailored for OpenSSH
, the most commonly used SSH implementation on both Linux
and macOS
systems.
What is an SSH Configuration File?
The SSH configuration file is a simple text file that allows you to define settings for SSH connections. Instead of specifying connection details every time you run ssh
, you can save them in a file called ~/.ssh/config
.
With this file, you can:
- Assign short aliases to servers
- Set default usernames, ports, and keys for different hosts
- Customize authentication settings
- Improve security by enforcing specific SSH options
The SSH config file makes remote access much simpler and more efficient!
SSH Configuration File Location
The SSH configuration file is located at:
~/.ssh/config
-
The
~
symbol represents your home directory. -
If the file doesn’t exist, you can create it using:
touch ~/.ssh/config
-
Ensure the correct file permissions are set to avoid security issues:
chmod 600 ~/.ssh/config
This ensures that only you can read and write to the file.
Basic Structure of the SSH Config File
Before diving into the details of the config
file, let's first look at a practical example to help you understand it better. Normally, we use the ssh
command with flags (options) to connect to a remote server.
To connect as the user test
to a server called myserver.com
(or its IP address 192.168.1.100
) on port 2222
, you would run:
ssh -p 2222 test@myserver.com # OR ssh -p 2222 test@192.168.1.100
This works just fine. But there's another way to pass options using the -o
flag. For the same example, here’s how it would look:
ssh -o "Port=2222" -o "User=test" -o "HostName=myserver.com" # OR ssh -o "Port=2222" -o "User=test" -o "HostName=192.168.1.100"
As we can see, we’re using options like Port
, User
, and HostName
. Note that these options must start with an uppercase letter.
You can find a full list of available options in the SSH manual page.
Now that we understand how to use SSH with command-line options, we can take a look at the SSH configuration file, which works similarly but in a more convenient way.
The SSH config file allows you to save these options so you don't have to type them every time. Instead, you define them once, and then just refer to the server by its alias.
Structure of the SSH Config File
In the example below, we can see a typical SSH config file that includes several Host
blocks, each defining a set of configurations for different servers or sets of servers:
Host firsthost Hostname myserver.com User test IdentityFile ~/.ssh/mykey.pem Host secondhost ANOTHER_OPTION custom_value Host *host ANOTHER_OPTION custom_value Host * CHANGE_DEFAULT custom_value
When we run the command ssh firsthost
, SSH starts by reading the first section, which is the Host firsthost
block. Here, it finds specific configurations like the Hostname
, User
, and IdentityFile
options, which are applied directly for this connection.
After applying the settings from the firsthost
block, SSH doesn't stop there. It continues checking the subsequent blocks to see if any of them match or apply additional settings.
Next, SSH moves to the second block, Host secondhost
. Since firsthost
doesn’t match secondhost
, this block is skipped. This is where the idea of specificity comes in—SSH applies the most specific configurations first.
Then, SSH moves to the third block, Host *host
. Here, it finds a wildcard that matches firsthost
because firsthost
ends with host
. As a result, SSH will check for any settings in this block that might apply. For example, if ANOTHER_OPTION
is defined here, it will be added to the existing configuration from the firsthost
block, unless it was already set in the previous blocks.
Finally, SSH reaches the last block, Host *
. This block is a catch-all for any configuration that should apply globally to all hosts, regardless of their name or alias. The setting CHANGE_DEFAULT custom_value
will be applied to the connection if it wasn't already added in a more specific block.
After SSH gathers all the relevant settings from the config file—whether from specific blocks or global ones—it will attempt the connection to firsthost
with all the configurations it has assembled.
Using the SSH Config File
Once the config file is set up, instead of typing the full command every time, you can simply run:
ssh firsthost # OR for the second host ssh secondhost
This is much quicker and easier, especially if you need to connect to multiple servers with different configurations.
Common SSH Configuration Options
Here are some useful options you can include in your ~/.ssh/config
file:
Connection Options
Now we have an idea, on what is a SSH configuration file, how it works, and how to write it, let's discuss some common option
The first thing we will talk is the minium configuration necessary to connect to a remote host.
Host myserver HostName myserver.com User test Port 2222 IdentityFile ~/.ssh/mykey.pem
So far, we have discussed some of the options necessary to establish a connection. We have covered these options:
- Host myserver → This is an alias for the server. Instead of typing the full command, you can simply use
ssh myserver
. - HostName myserver.com → The actual hostname or IP address of the remote server.
- User test → The default username for logging in to the server.
- Port 2222 → The SSH port (default is
22
, but some servers use custom ports). - IdentityFile ~/.ssh/mykey.pem → The private key file used for authentication.
There are many other useful SSH options worth exploring. Below are some of the most commonly used ones, categorized by their functionality.
-
ServerAliveInterval: Defines the time interval (in seconds) for sending keepalive packets to the server. If the server doesn’t respond, SSH can detect an unresponsive connection. The default is
0
(disabled), but setting it to a nonzero value helps prevent disconnections. -
LogLevel: Controls the level of detail in SSH logs. Available values are
QUIET
,FATAL
,ERROR
,INFO
,VERBOSE
,DEBUG
,DEBUG1
,DEBUG2
, andDEBUG3
. The default isINFO
, whileDEBUG
levels provide more detailed logs for troubleshooting. -
StrictHostKeyChecking: Determines whether SSH automatically accepts or rejects unknown host keys.
yes
blocks new or changed keys (best for security),ask
prompts the user,accept-new
allows only new hosts, andno
accepts all keys without verification. -
UserKnownHostsFile: Specifies the file where SSH stores known host keys. By default, this is
~/.ssh/known_hosts
. Changing it can be useful for custom security setups or separate environments. -
VisualHostKey: Displays an ASCII representation of the server’s key fingerprint during connection. This helps users visually confirm the remote server’s authenticity before logging in.
-
Compression: Enables SSH data compression to improve performance on slow networks. Setting this to
yes
can reduce bandwidth usage but may increase CPU load. It’s rarely needed on modern, high-speed connections. -
IdentityFile: Specifies the private key file used for authentication. This is useful when managing multiple SSH keys, allowing users to specify different keys for different servers.
-
IdentitiesOnly: Restricts SSH to use only the keys explicitly defined in
IdentityFile
. This prevents SSH from trying additional keys loaded in the SSH agent, reducing authentication conflicts.
With these SSH configuration options in mind, we can fine-tune our ~/.ssh/config
file to simplify access, improve security, and handle multiple environments efficiently.
For example, when managing different types of servers (production, testing, and development), applying shared configurations can reduce redundancy and improve maintainability. Below is a professional SSH config file with multiple hosts and shared settings.
Real-World SSH Config Example
# Global settings applied to all SSH connections Host * ServerAliveInterval 60 # Keep the connection alive every 60 seconds LogLevel ERROR # Suppress unnecessary logging StrictHostKeyChecking accept-new # Automatically accept new host keys # Shared settings for all servers ending in '-server' Host *-server User admin # Default user for all servers matching '*-server' IdentityFile ~/.ssh/server_key.pem # Shared identity file for test and dev servers TCPKeepAlive yes # Ensure the connection does not drop IdentitiesOnly yes # Only use the specified identity file # Production server configuration (Overrides shared settings) Host prod-server HostName prod.example.com # Production server hostname Port 2222 # Custom SSH port IdentityFile ~/.ssh/prod_key.pem # Specific key for production server IdentitiesOnly yes # Only use the specified identity file # Testing server configuration (Uses shared settings) Host test-server HostName test.example.com # Testing server hostname # Development server configuration (Uses shared settings but adds ForwardAgent) Host dev-server HostName dev.example.com # Development server hostname ServerAliveInterval 120 # Extend keepalive interval for development
Usage
Now, instead of typing long SSH commands, we can connect with:
ssh prod-server ssh test-server ssh dev-server
Forwarding Option
SSH not only allows remote connections but also supports forwarding different types of data between systems.
Here are some key options related to SSH forwarding:
-
ForwardAgent: Allows forwarding your local SSH authentication agent to the remote system. This means you can use your local keys to authenticate further SSH connections from the remote machine. Default is
no
. -
LocalForward: Creates a secure tunnel from a port on your local machine to a specific address and port on the remote server. This is useful for accessing remote services as if they were running locally.
-
ForwardX11: Enables X11 forwarding, allowing graphical applications from the remote server to appear on your local desktop. Default is
no
. -
ExitOnForwardFailure: If set to
yes
, SSH will terminate the connection if it fails to set up any requested port forwardings. By default, SSH continues running even if some forwarding rules fail. -
RemoteForward: Similar to
LocalForward
, but it forwards a local port on your machine to a remote host and port, allowing services on your local machine to be accessed from the remote server. -
DynamicForward: Sets up a SOCKS proxy on your local machine, which can be used to route web traffic through an SSH tunnel. This enables secure browsing via the remote server.
-
StreamLocalBindUnlink: Ensures that any existing Unix domain socket file is removed before creating a new forwarding. Useful when working with Unix sockets to avoid conflicts.
-
ProxyCommand: Specifies a command to connect to the remote server, rather than the default SSH connection. Often used for routing through a proxy or another gateway.
-
AllowStreamLocalForwarding: Controls whether Unix domain socket forwarding is allowed. Set to
yes
to allow forwarding of Unix socket connections.
These options provide flexibility in managing remote connections, whether for authentication, secure tunneling, graphical application access, or port forwarding. Depending on your use case, you can select the appropriate forwarding options to meet your needs.
Note: While we've covered some of the most common SSH config options here, there's a wide range of additional settings you can explore. If you're interested in trying more options, check out the official manual at: https://linux.die.net/man/5/ssh_config.
Final Thoughts
The SSH configuration file is a powerful tool that streamlines your workflow, reducing the need for repetitive commands and minimizing connection errors. Whether you're managing just a few servers or overseeing a complex infrastructure, having a well-organized SSH config file ensures smoother and more efficient connections. By customizing your settings, you can save time, avoid mistakes, and stay in control of your environment.