Changing the Default SSH Port (Linux / CentOS)

SSH is one of the most commonly attacked services as it provides easy access to full control of a dedicated server. Changing the default SSH port will help prevent an attacker from launching brute force attacks on the default port.

**Change someportnumber to a new port number that is not in use for other services.

Step 1

Log in to your server as root

Step 2

Within the command line, execute the command nano /etc/sysconfig/iptables to edit the IPTables configuration file.

Add the following line to the configuration file: -A INPUT -m state –state NEW -m tcp -p tcp –dport someportnumber -j ACCEPT directly below the line -A INPUT -m state –state NEW -m tcp -p tcp –dport 22 -j ACCEPT in the configuration file.

Save and exit by holding down Ctrl and X

Step 3

Within the command line, run the command service iptables restart to restart the IPTables service

Step 4

Run the command service iptables status to see if the new rule has been applied (optional)

Step 5

Edit the SSH configuration file with the command nano /etc/ssh/sshd_config

Modify the line #port 22 By removing # and replacing 22 With your new desired port number, we opened the IPTables configuration.

Save and exit by holding down Ctrl and X

Step 6

Within the command line, execute service sshd restart to restart the SSH service.

Step 7

If you can still access the command line, type ss -tnlp | grep ssh to verify SSH is listening on the new port. (optional)

Step 8

Connect to the server via SSH using the new port you selected.

Step 9

Run the command nano /etc/sysconfig/iptables to edit the IPTables configuration file again.

Comment out the line -A INPUT -m state –state NEW -m tcp -p tcp –dport 22 -j ACCEPT by adding # at the beginning of the line to block all connectivity to port 22.

Save and exit by holding down Ctrl and X

Step 10

Execute the command service iptables restart to restart the IPTables service