How to Change Default SSH Port in Ubuntu
In this tutorial, we will learn how to change the OpenSSH port on an Ubuntu server.
Changing the SSH port from the default of 22 will help improve server security and dissuade attackers from attempting to compromise your machine.
Check Current SSH Port
Before changing anything, let's check if the current SSH TCP port is 22 using netstat
.
sudo netstat -tulnp | grep ssh
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 761/sshd: /usr/sbin
tcp6 0 0 :::22 :::* LISTEN 761/sshd: /usr/sbin
Change SSH Port Config File
To change the SSH port open the ssh_config
file and locate to the line containing #Port 22
sudo nano /etc/ssh/sshd_config
Comment #Port 22
(remove the hash), then set the port number to what you'd like it to be.
Include /etc/ssh/sshd_config.d/*.conf
Port 6464
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::
Save and close the file.
Apply The Changes
To apply the changes restart the sshd
service with systemctl
using the following command:
sudo systemctl restart sshd
Now check the changes have applied with netstat
:
sudo netstat -tulnp | grep ssh
tcp 0 0 0.0.0.0:5454 0.0.0.0:* LISTEN 13449/sshd: /usr/sb
tcp6 0 0 :::5454 :::* LISTEN 13449/sshd: /usr/sb
Open UFW SSH Port
Important: You will need to allow connections to your new SSH port if you have UFW enabled. Use to the following command:
sudo ufw allow <port number>/tcp
Verify the changes:
sudo ufw status
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
8000 ALLOW Anywhere
5454/tcp ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
5454/tcp (v6) ALLOW Anywhere (v6)
Login With Different SSH Port
When you login to your server VIA SSH in future, you'll need to supply the port like this:
ssh -p 5454 ubuntu@your_server_ip