Change port for sshd server
I changed the port for sshd on my servers to reduce the number of attacks against the sshd server. In the following example, I am changing the port from the default of 22 to 43231
First – backup your sshd_config file
cp -p /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F)
First – edit your /etc/ssh/sshd_config flle – If you have not changed the file, the following line should work:
sed -i 's/#Port 22/Port 43231/g' /etc/ssh/sshd_config
or
edit the the /etc/ssh/sshd_config file, find the “Port” line, remove the # from the beginning of the line (if it is there) and change the 22 to be 43231
SELINUX for SSH
By default SELINUX only allow port no. 22 for ssh. Now add new port context 43231.
Note: Replace 43231 in case you have selected different port number
Note: Replace 43231 in case you have selected different port number
semanage port -a -t ssh_port_t -p tcp 43231
Note: if you get the following after running semanage:
bash: semanage: command not found
you need to run (centos 7)
yum -y install policycoreutils-python
(Centos 8)
yum -y install policycoreutils-python-utils
then re-execute the complete semanage command above
Now check once the port context for ssh
semanage port -l | grep ssh
Below given is output from our server
[root@localhost ~]# semanage port -l | grep ssh ssh_port_t tcp 43231, 22 [root@localhost ~]#
Allow port 43231 with iptables (Centos 6)
Now allow port number 43231 for ssh. Run commands below. They will add the new iptables rule for port 43231 with TCP protocol and save the changes.
iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 43231 -j ACCEPT service iptables save
Allow port 43231 with firewalld (Centos 7)
Now allow port number 43231 for ssh. Run the commands below. They will permanently add the new firewalld rule in public zone for port 43231 with TCP protocol and perminantly save the changes.
firewall-cmd --permanent --zone=public --add-port=43231/tcp firewall-cmd --reload
Restart the SSH service
Now Restart the SSH service (Centos 6)
service sshd restart
Now Restart the SSH service (Centos 7)
systemctl restart sshd.service
Check listening ssh port with ss command
With ss command, you can find the listening port for ssh. Use below command for this
ss -tnlp | grep ssh
Below given output is reference from our server
[root@localhost ~]# ss -tnlp | grep ssh LISTEN 0 128 *:43231 *:* users:(("sshd",2786,3)) LISTEN 0 128 :::43231 :::* users:(("sshd",2786,4)) [root@localhost ~]#
Test It!
Try to do ssh access to server by using port no. 43231 from remote client.
ssh -p 43231 root@10.51.42.83
* Change 10.51.42.83 with your server ip address or fqdn.
* Change 43231 with your new ssh port number as you set while reading this post.
* Change root with user name which is allowed to get ssh access in your server.