How to change the ssh port on Linux or Unix server

[ March 5, 2018 ]

You can easily change the SSH Port for Your Linux or Unix server. The ssh port defined in sshd_config file. This file located in /etc/ssh/sshd_config location.

Procedure to change the SSH Port for Linux or Unix Server

Open the terminal application and connect to your server via SSH.
Locate sshd_config file by typing the command.
Edit the file and set Port option.
Save and close the file.
Restart the sshd service.

Locate sshd_config file by typing the following command

$ find / -name “sshd_config”

Sample outputs:

/etc/ssh/sshd_config

Edit the file and set Port option

Type the following command:

$ sudo vi /etc/ssh/sshd_config

Locate line that read as follows:
Port 22

OR
#Port 22

To set the port to 2222, enter:
Port 2222

Save and close the file.

A note about SELinux users

You must type the following command to change port to 2222:
# semanage port -a -t ssh_port_t -p tcp 2222
# systemctl restart sshd

Updating your firewall to accept the ssh port 2222

If you are using UFW on a Ubuntu/Debian Linux, type:
$ sudo ufw allow 2222/tcp

The syntax for iptables is as follows
$ sudo /sbin/iptables -A INPUT -m state –state NEW -m tcp -p tcp –dport 2222 -j ACCEPT

The syntax for pf firewall is as follows (FreeBSD/OpenBSD/NetBSD Unix) in your pf.conf:
pass log on $ext_if proto tcp to any port 2222 keep state

Warning: You must update your firewall settings to accept new port. Otherwise the following command will lock down your ssh access.
Restart the sshd service

Type the following command on a CentOS/RHEL/Fedora Linux:
$ sudo service sshd restart

OR if you are using CentOS/RHEL/Fedora Linux with systemd:
$ sudo systemctl restart sshd

OR if you are using Ubuntu/Debian/Mint Linux:
$ sudo service ssh restart

OR if you are using Ubuntu/Debian/Mint Linux with systemd:
$ sudo ystemctl restart ssh

Or if you are using FreeBSD Unix, enter:
$ sudo service sshd restart

Related Articles