Changing the SSH port on Linux is pretty easy and straightforward. As it is with most of the packages that are available for any Linux distribution including Ubuntu, they come with a configuration file. Let’s modify that configuration file and update our port to something that’s not so commonly available.
Change SSH Port in Linux and Ubuntu
The process is the same for any Linux distribution. The directory structure could be a little different but the file names will remain the default ones. So in case, you have difficulty finding a file, just search for it using the search tools.
On Linux systems, we have the /etc/services file which lists out all the active services along with the ports and type of connections. Let’s see what port our SSH server is running on.
root@HowLinux:~# grep 'ssh' /etc/services
As you can see, the default port shows 22 here and the type of connection is TCP. Let’s change the port to 2020.
Editing the sshd_config File
To change the default port our ssh service is active on, we’ll edit the ssh server configuration file. The /etc/ssh/sshd_config file holds the default configuration data for the ssh server. Open it up with your favorite text editor.
root@HowLinux:~# nano /etc/ssh/sshd_config
Scroll down until you see a line that says Port 22 that is commented out. Just remove the # at the beginning of the line, and edit the port to 2020 (or whichever port you need to run the server on).
Restart the SSH Server
Now we need to restart our SSH server on Linux or Ubuntu to make sure that our settings take effect.
root@HowLinux:~# service sshd restart
There will be no output for this command. If you receive any errors, do check if you’ve spelled everything correctly.
Verifying the SSH Port Change
We’ll use the netstat command in Linux to verify what port our ssh server is listening for connections on. Run the following command on your system.
root@HowLinux:~# netstat -tlp | grep ssh
The -t and -l option stand for TCP and Listening. So we’re looking for all the connections that are of the TCP type and are actively listening for incoming connections. The -p option shows the program names.
We are also piping the output to grep so we only see the port that ssh server is running on and not every other service running on our system.
That’s great! As you can see, our server has now started listening on the port 2020.
Allowing Incoming Connections Through Firewall in Ubuntu
If you’re using Ubuntu, the default setup will have the UFW firewall installed. It allows the default SSH ports but won’t allow a port that we set up by ourselves. Let’s add a rule to allow incoming connections on the 2020 port with the TCP connection type.
root@HowLinux:~# ufw allow 2020/tcp
Now you know how to set up the SSH server port using the configuration file. You can read through the configuration file to see if there are any other configurations that you wish to change. We’ll learn more about the ufw firewall and the netstat command in future tutorials.