How to Use The SSH Config File (2024)

Introduction

The SSH protocol creates a secure connection between two remote machines. An SSH config file helps easily configure the default values for these connections and enables efficient streamlining of SSH connections.

This article explains how to use SSH config files to manage SSH connections.

How to Use The SSH Config File (1)

Prerequisites

  • Access to the terminal (CTRL+Alt+T).
  • Access to a text editor, such as nano or Vim.
  • A remote server to test connections.

What are SSH Config Files?

SSH configuration files are a powerful tool for automating SSH connections. The default location of a user-specific config file is in ~/.ssh/config, whereas the system-wide configuration file for all users is in /etc/ssh/ssh_config. Both file locations should stay unchanged.

How to Use The SSH Config File (2)

A config file is a plain text file with various SSH connection options. Use any text editor to open, read, or edit a config file.

How are SSH Config Files Used?

When an SSH config file is in the appropriate location, run an ssh command with the correct parameters to read the options specified in the config file.

For example, if an SSH config file contains an example Host section like the following:

Host my-website.com HostName my-website.com User my-user IdentityFile ~/.ssh/id_rsa

This ssh command connects to the remote host:

ssh my-website.com

The command applies the options for the givenHostNameof the server, such as theUserandIdentityFile. The configuration file contains default connection information for a host and avoids having to enter connection details manually.

A chain of multiple host options and wildcards enables the creation of default values for all servers or lets you add specific parameters for some servers.

How to Create SSH Config Files?

To create an SSH config file, do the following:

1. Open the terminal (CTRL+Alt+T).

2. Navigate to the .ssh directory:

cd ~/.ssh

Note: If the directory does not exist, create it with the mkdir command:

mkdir ~/.ssh

3. Use a text editor to create and open the config file. For example, if you use nano, run:

nano config

The editor creates and opens the file for editing.

4. After filling out the file with information, close nano and save the changes.

5. Give read and write permissions to the current user only:

chmod 600 ~/.ssh/config

The file requires strict permissions due to abuse potential.

The sections below explain how to format the SSH config file and all the available parameters.

Format of the SSH Config File

SSH config files follow a specific format to work correctly. An example config file looks like the following:

Host hostname_1 PARAMETER argument PARAMETER argumentHost hostname_2 PARAMETER argumentHost * PARAMETER argument
How to Use The SSH Config File (3)

The SSH config file is divided into Host sections with specific configuration options for every host. The argument is the exact hostname, IP address, or a match pattern.

Use whitespace as a separator between parameters and arguments or an equals sign (=). If the value contains whitespaces, encase the string between quotation marks ("). Use a comma-separated list for multiple arguments.

The following characters help define different patterns:

  • An asterisk (*) matches zero or more characters. For example, Host *.com matches any host ending in the .com domain set, whereas Host * matches any host.
  • A question mark (?) matches exactly one character. For example, 192.168.1.? matches all hosts in 192.168.1.[0-9] range.
  • An exclamation mark (!) negates a pattern. For example, !192.168.1.1, 192.168.1.*

Empty lines and lines starting with the hash sign (#) are comments. SSH ignores these lines and uses the first obtained values when searching through the config file. Place host-specific information near the beginning of the file and general default information near the end.

Parameters for SSH Config Files

The SSH config file offers many parameters to configure SSH connections. Below is a brief description of all the available parameter keywords and their functionality.

Note: The parameters and arguments are case-sensitive.

AddressFamily

The AddressFamily parameter sets the address family to use when connecting via SSH. Possible arguments are inet (IPv4 only), inet6 (IPv6 only), or any.

BatchMode

The BatchMode parameter controls whether to prompt for a password or not. The value is set tonoby default and asks to enter a password.

Set the argument toyesif using SSH in scripts.

BindAddress

The BindAddress parameter helps specify the bind address in a multi-address system. If the UserPrivilegedPort value is yes, the option does not work.

ChallengeResponseAuthentication

The ChallengeResponseAuthentication parameter controls whether to challenge-response authentication when using SSH to connect to a server. The default value is yes.

CheckHostIP

TheCheckHostIPparameter tells SSH whether to perform additional checks on the host IP address in theknown_hostsfile. The parameter allows SSH to detect host key changes. By default, the value isyes.

Cipher

Cipheris a protocol version 1 parameter for stating the cipher type for encrypting sessions. Supported types areblowfish,des, and3des(default).

Ciphers

The Ciphers parameter states the cipher type for encrypting sessions in protocol version 2. The available ciphers and default values are:

aes128-ctr, aes192-ctr, aes256-ctr, arcfour256, arcfour128, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, aes192-cbc, aes256-cbc, arcfour

Provide multiple ciphers in a comma-separated list.

ClearAllForwardings

The parameter controls whether to clear all dynamic, local, and remote port forwarding from the command line or configuration file. The default value for ClearAllForwardings is no.

When running SSH from the command line, clear any preset configuration using the parameter.

Compression

The Compression parameter controls whether to use compression or not. The default value is no.

CompressionLevel

The CompressionLevel parameter sets the compression amount if the Compression parameter is yes. The level is an integer between 1 (fastest, worst) and 9 (slowest, best), with level 6 as default. The parameter applies to protocol version 1 only.

ConnectionAttempts

The ConnectionAttempts parameter controls how many connection attempts to try before exiting. One try happens per second, and the default number of attempts is 1. Add the parameter to a script if attempts sometimes fail.

ConnectTimeout

The ConnectTimeout parameter defines the connection timeout in seconds when connecting to an SSH server. The default timeout value is the system TCP timeout.

ControlMaster

The ControlMaster parameter allows sharing a connection through the same network. The parameter enables the following arguments:

  • yes - Enables listening on a control socket provided in ControlPath.
  • no - Disables listening but still allows connecting through the ControlPath through the master's network connection (default).
  • ask - Listens for connections and requires confirmation. If the ControlPath does not open, SSH continues without connecting to the master connection.
  • auto - Allows opportunistic multiplexing and creates a new connection if it does not exist.
  • autoask - Combines the ask and auto options.

ControlPath

The ControlPath parameter contains the information for the control socket in shared connections. The none argument disables connection sharing. If providing a path, the following substitutions are available:

  • %l - The local hostname.
  • %h - The target hostname.
  • %p - The connection port.
  • %r - The remote login username.

The minimum recommendation is %h, %p, and %r to ensure connections have unique identifiers.

DynamicForward

The DynamicForward parameter enables dynamic TCP port forwarding over the secure channel. The format is bind_address:port or bind_address/port.

Use localhost as the bind address to bind the port for local use or * to make the port available from all interfaces.

EnableSSHKeysign

The EnableSSHKeysign parameter in the global SSH configuration file (/etc/ssh/ssh_config) starts a program to generate digital signatures for host-based authentication. The available arguments are yes or no.

EscapeChar

The EscapeChar parameter defines the escape character. The default escape character is a tilde (~). Use none to turn off escape characters.

ExitOnForwardFailure

The ExitOnForwardFailure parameter indicates whether to terminate the connection if port forwarding fails. The possible arguments are yes or no (default).

ForwardAgent

The ForwardAgent parameter controls whether an authentication agent forwards to the remote machine. The default value is no. Enable the option with caution since users who can bypass file permissions can gain access to the local agent.

ForwardX11

TheForwardX11parameter controls X11 (windowing system) forwards to the remote machine. The value isnoby default and disallows forwarding X11 controls.

Users who bypass file permissions and have enabledForwardX11Trustedcan perform keystroke monitoring and other potentially unwanted tasks when the parameter value isyes.

ForwardX11Trusted

TheForwardX11Trustedparameter enables complete control over X11 clients to the original display. The default value isno, and the xauth token expires after twenty minutes for X11 clients. Enable the option with caution because it lifts all restrictions.

GatewayPorts

TheGatewayPortsparameter defines whether remote hosts can connect to local forwarded ports. The default value isno, and the local forwarded ports bind to the loopback address when disabled.

GlobalKnownHostsFile

The GlobalKnownHostsFile parameter allows specifying a different location for the global host key file. The default location is /etc/ssh/ssh_known_hosts.

GSSAPIAuthentication

TheGSSAPIAuthenticationparameter is a protocol version 2 option that controls whether GSSAPI is enabled. The GSSAPI provides access to various security services, and by default, the parameter is disabled and set tono.

GSSAPIKeyExchange

TheGSSAPIKeyExchangeparameter is a protocol version 2 option that enables key exchange based on GSSAPI and is set to no by default. The server does not need a host key when the parameter value is yes.

GSSAPIClientIdentity

TheGSSAPIClientIdentityparameter specifies the client identity SSH uses for GSSAPI. The parameter has no client identity by default, so SSH uses the default identity.

GSSAPIDelegateCredentials

TheGSSAPIDelegateCredentialsparameter controls whether to forward credentials to the server. The default value isno, and no credentials are delegated to the server.The parameter only works for protocol version 2.

GSSAPIRenewalForcesRekey

The GSSAPIRenewalForcesRekey parameter triggers rekeying the SSH connection if GSSAPI credentials renew. The parameter is no by default.

GSSAPITrustDns

TheGSSAPITrustDnsparameter controls whether to securely trust the DNS to normalize the host's name. The default argument value isno, and the hostname provided through the command line passes to the GSSAPI as is. The parameter is available for protocol version 2.

HashKnownHosts

The HashKnownHosts parameter controls whether to hash known host entries in the ~/.ssh/known_hosts file. SSH uses the hashed values as usual while not disclosing the file's contents.

By default, the parameter is set to no. Change the value to yes to hash all future entries. Old entries remain unchanged.

HostbasedAuthentication

The HostbasedAuthentication parameter indicates whether to try rhost based authentication with public key authentication. The default value for the parameter is no and applies only to protocol version 2.

HostKeyAlgorithms

The HostKeyAlgorithms parameter sets the preference order for host key algorithms in protocol version 2. The default order is ssh-rsa,ssh-dss.

HostKeyAlias

The HostKeyAlias parameter allows setting an alias name for the host key to use when saving or looking up the host key. Use the parameter when running multiple servers on a single host or for SSH tunneling.

HostName

TheHostNameparameter contains the actual login hostname. The default value is the hostname given in the command line. Use the parameter to specify nicknames, abbreviations, or numerical IP addresses.

How to Use The SSH Config File (4)

IdentitiesOnly

The IdentitiesOnly parameter specifies to only use identity files stated in ssh_config. By default, the value is set to no. Use the parameter when ssh-agent offers multiple identities.

IdentityFile

The IdentityFile parameter contains the path to the identity file with a user's RSA or DSA identity. The default path for protocol version 1 is ~/.ssh/identity, whereas protocol version 2 uses either ~/.ssh/id_rsaor~/.ssh/id_dsa.

The identity file path allows using the tilde (~) for a user's home directory, and the following substitutions:

  • %d is the local user's home directory.
  • %u is the local user's username.
  • %l is the local hostname.
  • %h is the remote hostname.
  • %r is the remote username.

The parameter allows using multiple identity files which apply the provided order.

KbdInteractiveAuthentication

The KbdInteractiveAuthentication controls whether to use the interactive keyboard mode for authentication. The default value for the parameter is yes.

KbdInteractiveDevices

The KbdInteractiveDevices parameter contains a list of methods to use with keyboard-interactive authentication. The default values list depends on the server type. For example, an OpenSSH server uses zero or more of the following: bsdauth, pam, and skey.

LocalCommand

TheLocalCommandparameter allows a command to run on the local machine after successfully connecting via SSH. The command string executes in the user's shell.

To permit executing the command, enable thePermitLocalCommandparameter.

How to Use The SSH Config File (5)

LocalForward

TheLocalForwardparameter specifies a local port to forward through the secure channel to a target host and a port on the remote machine. The parameter requires two arguments:

  • bind_address:port for IPv4 or bind_address/port for IPv6 addresses. The bind address is optional.
  • host:hostport for IPv4 or host/hostport for IPv6 addresses.

For multiple ports, specify multiple arguments or provide additional forwarding information via the command line.

LogLevel

The LogLevel parameter controls the output verbosity of SSH messages. The available options are:

QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3

The INFO argument is the default value, whereas DEBUG and DEBUG1 indicate the same level.

MACs

The MACs parameter allows listing the message authentication algorithms (MACs) for protocol version 2. The algorithms determine the algorithm for data integrity protection. Possible values are:

hmac-md5, hmac-sha1, umac-64@openssh.com, hmac-ripemd160, hmac-sha1-96, hmac-md5-96

State multiple algorithms in a comma-separated list. The algorithms apply in the specified order.

NoHostAuthenticationForLocalhost

The NoHostAuthenticationForLocalhost parameter disables authentication for localhost. The default value is no, meaning the host key check happens for localhost.

Enable the option to allow sharing a home directory across machines. Warnings for changed host keys appear because "localhost" refers to a different device on every machine.

NumberOfPasswordPrompts

The NumberOfPasswordPrompts parameter allows stating how many password prompts happen upon failure. The argument for the parameter is an integer value, which is 3 by default.

How to Use The SSH Config File (6)

PasswordAuthentication

The PasswordAuthentication parameter controls whether there should be password authentication. The default value for the parameter is yes.

PermitLocalCommand

The PermitLocalCommand option controls whether the LocalCommand parameter executes a command on a local machine after connecting. By default, the parameter is turned off with the value no.

Port

The Port parameter contains the port number on the remote host. The default port for SSH is port number 22.

PreferredAuthentications

The PreferredAuthentications parameter is a list of authentication methods the client uses in order of preference. The list contains protocol version 2 authentication methods, and the possible values are:

gssapi-with-mic, hostbased, publickey, keyboard-interactive, password

Changing the order also changes the client's preference for authentication.

Protocol

The Protocol parameter contains the preferred protocol version for SSH. The possible values are 1 and 2. List the values in order of preference to create a fallback option if the first option does not work.

ProxyCommand

The ProxyCommand parameter defines the command for connecting to the server, and the argument is a command string that executes in the user's shell.

The command should connect to an OpenSSH daemon server running on a machine or execute sshd -i. For example, use Netcat to connect to an HTTP proxy with the following:

ProxyCommand nc -X connect -x <address>:<port> %h %p

The nc command contains proxy support and works with the ProxyCommand parameter to connect via proxy. The %h parameter substitutes the host, whereas %p is the port number.

PubkeyAuthentication

The PublicKeyAuthentication parameter controls whether to use public key authentication or not. The default value is no and works for protocol version 2 only.

RekeyLimit

The RekeyLimit parameter sets the maximum amount of data to transmit before the key renegotiates. The argument value is the number of bytes and allows suffixes for kilobytes (K), megabytes (M), and gigabytes (G).

Depending on the cipher, the default value is between1Gand4G.

RemoteForward

The RemoteForward parameter defines a TCP port on a remote machine to forward through the secure connection. Provide the following two arguments:

  • bind_address:port for IPv4 or bind_address/port for IPv6 addresses. The bind address is optional.
  • host:hostport for IPv4 or host/hostport for IPv6 addresses.

To use multiple ports, specify multiple arguments or provide additional forwarding information via the command line.

RhostsRSAAuthentication

The RhostRSAAuthentication parameter sets whether to use rhost based authentication and RSA-host authentication. The available options are yes or no (default).

RSAAuthentication

The RSAAuthentication parameter controls whether to attempt RSA authentication. The parameter only applies to protocol version 1, and the default value is yes. The RSA authentication attempt occurs only when an identity file exists, or the authentication agent is running.

SendEnv

The SendEnv parameter contains environment variables to send from the local environment to the server. Configure the server to accept environment variables through the AcceptEnv parameter in the /etc/ssh/sshd_config file.

No variables are sent by default. To send multiple environment variables, use SendEnv multiple times or provide a comma-separated list with variable names.

ServerAliveCountMax

The ServerAliveCountMax parameter sets the maximum number of server alive messages (default is 3). The session terminates when the connection reaches the threshold, defined as ServerAliveInterval*ServerAliveCountMax, in seconds.

The messages help a client or server know when a connection is inactive.

ServerAliveInterval

The ServerAliveInterval parameter is the timeout interval in seconds where no data comes from the server. After the interval elapses, SSH sends an encrypted request to respond to the server. The default value for the parameter is 0, meaning SSH sends no messages to the server.

SmartcardDevice

The SmartcardDevice parameter controls which smartcard device to use. Smartcard support is inactive by default. If active, the default argument is the smartcard SSH public keys.

StrictHostKeyChecking

The StrictHostKeyChecking parameter flags whether to automatically add host keys to the ~/.ssh/known_hosts file upon changes. The default options are yes, no, or ask (default). The check is a good security measure against trojan horse attacks.

TCPKeepAlive

The TCPKeepAlive parameter sends TCP messages to the server to check for connectivity. If the network is down or the server crashes, the client gets the information through the TCP messages.

By default, the messages are set as yes. Turn the parameter off to avoid disconnecting during temporary route downtimes.

Tunnel

The Tunnel parameter requests a tunnel interface device forwarding between the client and server. The available options are yes, point-to-point, ethernet, or no (default). The tunnel option for yes is point-to-point.

TunnelDevice

The TunnelDevice parameter helps determine which devices to open on the client (local tunneling) and server (remote tunneling). The argument is local:remote, whose values are the device IDs or any. The remote device ID is optional and defaults to any when omitted.

The default value for the tunnel device is any:any and uses the next available device in both cases.

UsePrivilegedPort

The UserPrivilegedPort parameter determines whether to use a privileged port for outside connections. The possible values are yes or no (default). If using RhostsRSAAuthentication with older servers, set the parameter value to yes.

User

When establishing a connection, theUserparameter sets the login username. Use the option when the username differs on machines or to avoid specifying it in the command line.

UserKnownHostsFile

The UserKnownHostsFile parameter sets the path for the known hosts file. The default location is ~/.ssh/known_hosts.

VerifyHostKeyDNS

The VerifyHostKeyDNS parameter determines whether to use DNS and SSHFP file records to verify the remote key. The default value is no, and changing it to yes automatically enables trusting keys that match the DNS fingerprint. Use the option ask to display fingerprint matches and to require confirmation.

VisualHostKey

The VisualHostKey parameter controls whether to print the ASCII art of the remote host key fingerprint for unknown host keys. By default, the value is no, and only the hex string fingerprint prints for unknown host keys.

XAuthLocation

The XAuthLocation parameter holds the full path to the X authority file utility. The default location is /usr/bin/xauth.

Conclusion

After reading this guide, you know how to use an SSH config file to set up connection options automatically.

Next, check out the most common SSH Linux commands.

How to Use The SSH Config File (2024)

FAQs

How is the config file used by SSH? ›

SSH client configuration files allow us to connect to servers with pre-configured commands. This saves typing each SSH command parameter when logging into a remote machine and executing commands on a remote device.

How to do SSH configuration? ›

Procedure
  1. Open the SSH configuration file /etc/ssh/sshd_config.
  2. Disable non-admin SSH tunneling. ...
  3. Disable agent forwarding (which is enabled by default). ...
  4. Update authentication methods. ...
  5. If SSH is not going to be used for other purposes on your system, consider restricting use to an explicit list of allowed HSTS users.

How do you specify a key in SSH config? ›

To specify which private key should be used for connections to a particular remote host, use a text editor to create a ~/.ssh/config that includes the Host and IdentityFile keywords. Once you save the file, SSH will use the specified private key for future connections to that host.

How do I open a SSH config file in Windows? ›

OpenSSH configuration files
  1. By launching ssh.exe with the -F parameter, specifying a path to a configuration file and an entry name from that file.
  2. A user's configuration file at %userprofile%\.ssh\config.
  3. The system-wide configuration file at %programdata%\ssh\ssh_config.
Jul 29, 2022

How are config files used? ›

Config files store data for applications that enable users to interact with those applications in a specific and purposeful way. For example, if you're trying to configure a SQL (Structured Query Language) server, you may use a configuration file to determine which IP addresses can access the database.

Where is the SSH custom config file? ›

The client-side configuration file is located at ~/. ssh/config – the ~ is a universal shortcut to your home directory. Often, this file is not created by default, so you may need to create it yourself. The touch command will create it if it does not exist (and update the last modified timestamp if it does).

How to use SSH command? ›

You can start an SSH session in your command prompt by executing ssh user@machine and you will be prompted to enter your password. You can create a Windows Terminal profile that does this on startup by adding the commandline setting to a profile in your settings. json file inside the list of profile objects.

How do I edit SSH config file? ›

To edit the SSH client config file in Vim, open the terminal and enter vim ~/. ssh/config. This opens the file in Vim, where you can edit it according to your requirements.

How do I connect to a server using SSH? ›

Connecting to your Dedicated Server via Terminal
  1. Open the terminal on your computer.
  2. Type ssh, followed by a space. ...
  3. If you see a message stating “Are you sure you want to continue connecting” type yes, then click the Enter key.
  4. You will then be prompted to enter your password.
Feb 21, 2024

How to write an SSH key? ›

Generate an SSH Key Pair
  1. Run the ssh-keygen command. You can use the -t option to specify the type of key to create. ...
  2. The command prompts you to enter the path to the file in which you want to save the key. ...
  3. The command prompts you to enter a passphrase. ...
  4. When prompted, enter the passphrase again to confirm it.

How to list all keys in SSH? ›

The command ssh-add -L lists all the public keys for all current SSH "identities". The first entry on each line is the key type, (ssh-rsa, ssh-dss, etc.), the second entry on each line is the public key itself, and the third entry on each line is typically the user and hostname on which the key was generated.

How to edit SSH config file in Linux? ›

Follow the below steps to edit the SSH config file. Step 1: Initially, open the 'Terminal or Putty or Console'. Step 2: Then login to the Server using SSH. Step 3: To edit the config file, enter the command.

How do I access SSH files? ›

How to open a file in ssh
  1. Log in using ssh: ssh user@server-name.
  2. To show just file run: cat /path/to/file.
  3. To edit or open a file named demo.py in the current directory, execute: nano demo.py. vi demo.py.
  4. Other options are: more filename. less filename.
Jan 21, 2019

Where is SSH server config? ›

The SSH server has its own set of configuration files, including the SSH server system-wide configuration file named sshd_config. By default, these files reside in the /etc/ssh directory on the remote host.

How do I open a SSH file in my browser? ›

Open the windows settings. Go to "Apps & feature -> Default Apps", scroll down and click on "Choose default apps by protocol". Now type in an SSH Url into the URL bar of any browser, for example ssh://user@example.com:2222 .

What should be in SSH config file? ›

Understanding ~/. ssh/config entries
  • Host : Defines for which host or hosts the configuration section applies. ...
  • HostName : Specifies the real host name to log into. ...
  • User : Defines the username for the SSH connection.
  • IdentityFile : Specifies a file from which the user's DSA, ECDSA or DSA authentication identity is read.
Mar 19, 2024

How to use SSH config file in Ansible? ›

Generating SSH Config Files with Ansible
  1. Creates a new EC2 instance.
  2. Adds the new EC2 host to an in-memory inventory group launched.
  3. Waits until SSH port 22 opens on the EC2 host.
  4. Adds the host's SSH key into ~/. ssh/known_hosts.
  5. Creates a new SSH config file for the host and puts it into the SSH include directory.
Apr 14, 2020

What does the config method do? ›

What is the config method? The config method allows your application to get or set values in all files that are in the config directory.

How config files work in Linux? ›

What Is Config File in Linux? A configuration (config) file is a local Linux file that controls how a program, utility, or process works. The config files are typically text files that contain the settings and instructions for various utilities, programs, and processes. The config files are non-executable.

Top Articles
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated:

Views: 6001

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.