How to Change SSH port in Ubuntu
Whether you're running multiple VMs locally or want to have a little peace of mind with bots attacking this famous port, changing SSH port has its legit usage.
The SSH uses port number 22 by default and there are plenty of reasons why you want to change it.
Whether you're running multiple VMs locally or want to have a little peace of mind with bots attacking this famous port, changing SSH port has its legit usage.
Change the SSH port in Ubuntu VM
If you haven't configured SSH yet, I'd highly recommend the other guide explaining how to configure SSH the easy way!
So the first step of configuring SSH in Ubuntu VM will be logging in remotely (obviously!):
ssh user@server_IP
To change the default SSH port, you'll have to make some changes in the file located at /etc/ssh/sshd_config
:
sudo nano /etc/ssh/sshd_config
Now, you have to look for #Port 22
, uncomment it (by removing #
) and change the port no. to the desired number. I'm going for port no. 2222 here:
Now, you have to reload the sshd_config so recently made changes can take effect:
sudo systemctl reload sshd
Changing rules for Firewall
This part will only be applicable to those who have configured a firewall to their system.
So let's start with allowing port through UFW:
sudo ufw allow 2222/tcp
Now, let's add the rule of accepting TCP port 2222 in IPTables:
sudo /sbin/iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 2222 -j ACCEPT
Connecting to Server after changing the SSH port
You tried connecting to your VM after changing the default SSH port and it throws an error saying "port 22: Connection refused"?
Don't worry, your precious VM is still safe!
You just have to mention the new port with -p
option while executing the SSH command:
ssh -p 2222 user@localhost
And you successfully changed your default SSH port to 2222!
Conclusion
This was my take on how to change the default port in your Ubuntu VM. And if you have any queries, feel free to SSH in the comments!
A software engineer who loves to tinker with hardware till it gets crashed. While reviving my crashed system, you can find me reading literature, manga, or watering my plants.