On the test, I change the SSH port in Ubuntu Server 14.0.4 LTS and Ubuntu Server 16.0.4 LTS.
Open the SSH configuration for example in the nano text editor (in nano, press Ctrl+X to exit, y/n to save or cancel changes):
sudo nano /etc/ssh/sshd_config
Find the line “Port 22” and change it for example to “Port 58222“.
To apply the changes, restart ssh (on different systems it can reboot in different ways, so here is a list of possible commands):
sudo service ssh restart sudo /etc/init.d/ssh restart sudo /etc/init.d/sshd restart
After restarting SSH, it will be available on the new port, and the current session on the old one will remain active, so without disconnecting for testing, we will try to connect to the new port, if not, then the firewall is working in the system and you need to allow it in the system, for example in iptables this is done this way (where 58222 is our new port):
sudo iptables -A INPUT -p tcp --dport 58222 -j ACCEPT
You can allow iptables to connect to SSH only from the specified range of IP addresses:
sudo iptables -A INPUT -d 192.168.0.0/24 -p tcp --dport 58222 -j ACCEPT
If everything is ok, we connect through a new port and can delete the old iptables rule, for example:
sudo iptables -D INPUT -p tcp --dport 22 -j ACCEPT
An example of a command to connect from Linux to SSH on a non-standard port:
ssh -p 58222 firstname.lastname@example.org
View the system on which port and on what network interfaces SSH works like this:
netstat -tulpan | grep ssh