Set Custom SSH Connection Timeout in Ubuntu

When connecting to a remote server via SSH on Ubuntu Linux, a slow or unresponsive network can cause your terminal to hang for a long time before timing out. This article explains how to set a custom connection timeout value in your SSH client configuration—both temporarily for a single session and permanently for all future connections.

Temporary Connection Timeout

If you only want to apply a custom timeout for a single SSH session, you can use the -o ConnectTimeout option directly in your terminal command. The value is specified in seconds.

For example, to set a 10-second timeout, run:

ssh -o ConnectTimeout=10 username@remote_host

If the connection is not established within 10 seconds, the SSH client will automatically abort the attempt.

Permanent Per-User Configuration

To avoid typing the option every time, you can configure a persistent timeout value for your local Ubuntu user account.

  1. Open or create your user-specific SSH configuration file using a text editor like Nano:

    nano ~/.ssh/config
  2. Add the ConnectTimeout directive. You can apply this to all hosts by using Host *, or restrict it to a specific domain or IP address.

    For all hosts:

    Host *
        ConnectTimeout 15

    For a specific host:

    Host example.com
        ConnectTimeout 5
  3. Save and close the file (in Nano, press Ctrl+O, Enter, then Ctrl+X).

  4. Set the correct file permissions to ensure security:

    chmod 600 ~/.ssh/config

Permanent System-Wide Configuration

To enforce a custom SSH connection timeout for all users on your Ubuntu system, you must edit the global SSH client configuration file.

  1. Open the global configuration file with root privileges:

    sudo nano /etc/ssh/ssh_config
  2. Locate the Host * section and add or modify the ConnectTimeout line:

    Host *
        ConnectTimeout 20
  3. Save the file and exit.

This setting will now apply to any user executing the ssh command on your Ubuntu machine.