Change Default SSH Port In Ubuntu

 ·  · 

Steps to change default SSH port in Ubuntu.


1 Change port

The default SSH port is 22, you can change it in file: /etc/ssh/sshd_config.

$ sudo vim /etc/ssh/sshd_config


Go to the line Port 22, change 22 to be your custom port number. A five digits port number is recommended.

# SSH Port
Port 24000  # change this to your port 

There is a list of well-known socket ports or system ports already used. You can refer to it to avoid a conflict.


2 Update iptables

You may need to add the new SSH port to iptables as well.

$ iptables -A INPUT -p tcp -m state --state NEW --dport 24000 -j ACCEPT

Or add an IPv6 rule:

$ ip6tables -A INPUT -p tcp -m state --state NEW --dport 24000 -j ACCEPT

Note: commands above in some Linux distributions (e.g. Ubuntu) won't permanently save updated iptables rules, the new changes of rules will be lost after a reboot.

You can permanently save the updated rules manually or with help of tools, for example, ufw or iptables-persistent.

Manually save current rules:

$ iptables-save > /etc/iptables/rules.v4
$ ip6tables-save > /etc/iptables/rules.v6

Manually load saved rules:

$ iptables-restore < /etc/iptables/rules.v4
$ ip6tables-restore < /etc/iptables/rules.v6

You can achieve the same effect using iptables-persistent in Ubuntu or Debian.

$ sudo dpkg-reconfigure iptables-persistent

Then answer yes to the questions about whether to save the rules.

Lastly, using ufw in Ubuntu:

$ sudo ufw allow 24000


3 Restart SSH

Restart SSH service.

$ sudo service ssh restart


4 Connect

The only difference is a -p option to specify SSH port.

$ ssh [email protected]_server -p 24000

If you use Mosh shell, the command will be as follows.

$ mosh [email protected]_server --ssh="ssh -p 24000"