Set Custom SSH Port for Specific Host in Ubuntu

Connecting to remote servers via SSH often requires specifying a non-standard port for security reasons. Instead of typing the port number manually every time you connect, you can configure your Ubuntu Linux SSH client to automatically use a specific port for a designated host. This article demonstrates how to modify your local SSH configuration file to streamline your connection workflow, allowing you to connect using a simple nickname.

Step 1: Open or Create the SSH Config File

The SSH client configuration is managed through a file named config located in the hidden .ssh directory of your user home folder.

Open your terminal and open this file using a text editor like nano:

nano ~/.ssh/config

If the file or the .ssh directory does not exist, this command will create it.

Step 2: Add the Host Configuration

To define a specific port for a host, add a configuration block using the following format. Replace the placeholder values with your actual server details:

Host myserver
    HostName 192.168.1.50
    Port 2222
    User ubuntu

Here is what each parameter means: * Host: The shortcut name or alias you want to use in your terminal (e.g., myserver). * HostName: The actual IP address or domain name of the remote server. * Port: The custom, non-standard port number the remote SSH server is listening on. * User (Optional): The default username to use for the connection.

Save the file and exit the editor. In nano, press Ctrl + O, hit Enter to save, and then press Ctrl + X to exit.

Step 3: Set Correct File Permissions

For security reasons, SSH requires the configuration file to have restricted permissions. Run the following command to ensure only your user can read and write to the file:

chmod 600 ~/.ssh/config

Step 4: Connect to Your Host

Once configured, you no longer need to specify the IP address, username, or port in your terminal command. Simply run the ssh command followed by the alias you defined in the Host line:

ssh myserver

The SSH client will read the configuration file, apply the custom port, and initiate the connection.