SSH is a useful program for remotely logging in to a computer over the internet or a network. It creates a secure connection so powerful commands and tools can be safely used. In order to do this it needs a ‘port’: a number on the server that identifies which program can connect. However, two programs trying to use the same port can cause network conflicts. And although the default port is usually fine, sometimes the way other programs are set up stop it from working properly.
The following guide explains how to change the port SSH connects to on a CentOS 6 server.
In order to change the port, the first step is editing the config file for ‘sshd’, which is the SSH daemon. Use this command to edit it:
The default port for SSH is 22. Change this number to whatever you need, but be sure to avoid ports already in use by the server which are commonly used by other programs. This means most ports below 1024, but be sure to check what is in use to avoid conflicts later.
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options change a
# default value.
#Port 22 <----------------------------------------------- You need to remove the comment (#) and change the value by the port you want #AddressFamily any #ListenAddress 0.0.0.0 #ListenAddress :: [...]
After the config file has been edited and saved, the SSH daemon needs to be restarted for the changes to take effect. Use this:
service sshd restart
If SELinux is enabled on the server, its security features will block the connection unless the port is also added there. Use this command, and insert the port number that was set in the sshd config file:
semanage port -a -t ssh_port_t -p tcp xxxx
Finally, the firewall will also need to be modified to allow the port through. If you used SSH for this guide, logging out before this last step will mean you can't log back in! Use this command, again substituting the port number used in the sshd config:
-A INPUT -m state --state NEW -m tcp -p tcp --dport xxxx -j ACCEPT
You can now securely connect to the server with SSH on the chosen port. If this guide was useful to you, share it with your friends!