Problem
Change the port used for SSH connections on a CentOS/Fedora/Red Hat system.
tl;dr
Open sshd_config:
nano /etc/ssh/sshd_config
Look for this line:
#Port 22
And change it to this line, assuming your new port is 1234:
Port 1234
Open up the new port in IPTables and restart SSH:
iptables -I INPUT -p tcp –-dport 1234 -j ACCEPT service iptables save service sshd restart
Solution
Default port used to connect to SSH is 22. It is an extremely well-known connection, and as such is guaranteed to be scanned by any number of hackers or automated bots looking to exploit your system. In fact, if you set up connection logging on a web-facing server, you will often see several attempts per hour to connect to your server via SSH.
For this reason, it can often be a good idea to change your SSH port to a random high number that is most definitely NOT a well-known port, and as such usually is not scanned. This is called "security through obscurity." In a way, it's similar to burying your money in a chest, as opposed to keeping it under your mattress. After all, chances are the first place a thief will look is right under your mattress. Sure, the money is still accessible in your garden, but the thief will probably give up before digging a few hundred holes.
Port used to connect to SSH is a single setting in /etc/ssh/sshd_config file. Open the file:
nano /etc/ssh/sshd_config
Look for the line that reads
#Port 22. It will be near the beginning of the file:
#Port 22
Uncomment it (remove the # symbol) and change it to whichever new port you would like:
Port 1234
Then hit Ctrl-O and Ctrl-X to save and exit the file.
When you are done with the above, restart SSH:
service sshd restart
Open the port in IPTables
If you are using IPTables (and you should be), you need to open the new port before you can connect through it:
iptables -I INPUT -p tcp –-dport 1234 -j ACCEPT service iptables save
It's also a good idea to drop connections via port 22, so the bot or malicious hacker cannot tell whether SSH is running at all. Please note that as soon as you do so, your SSH connection will drop if you are still connected on port 22. You will have to reconnect on the new port to save the rule.
iptables -I INPUT -p tcp –-dport 22 -j DROP service iptables save
Connect to the server
If you are using a non-standard port, you need to specify it when you connect to the server via SSH. If you are using Putty, simply change port number from 22 to the new number, such as 1234 in Port field. Port field is right next to the "Host Name (or IP address)" field you use to type in your server's IP address or DNS name.
If you are connecting via SSH from another Linux box, add -p 1234 argument to your connection:
ssh -p 1234 root@1.2.3.4