Yandex

How to Change the SSH Port?

Print
  • ssh, port
  • 1

Why do I need to change the SSH port from the default 22 to a different one? This is done for two reasons:

  • for security purposes, so that attackers do not try to access your server by brute-forcing your SSH password
  • for comfortable use of SSH, so that SSH does not refuse your connection due to excessive spurious traffic

You can select any free port from 1023 to 65535. For example, 9999. To check whether the port you have selected is free on the server, use the following command ss -lptun | grep 9999. The output should be empty.

Specify the new port in the configuration file /etc/ssh/sshd_config. To edit a file from the console, I suggest using the nano redoctor. The command will look like this: nano /etc/ssh/sshd_config. Moving through the file using the arrows you need to find the line Port 22 (can also take the form #Port 22) and replace it with Port 9999.
To save the changes, use the key combination Ctrl + O, click Enter. And to exit the editor Ctrl + X.

You can check if the changes are correct using the command grep ^Port /etc/ssh/sshd_config. The output of the command should only contain the string Port 9999 and nothing else.

If everything is correct, restart SSH with the command systemctl restart ssh. In RedHat operating systems, you must use the name of the service sshd, i.e. the command will be of the form: systemctl restart sshd.

Check if the service works on the port:  ss -lptun | grep 9999.

For SSH access, we now need to specify a port. From Linux, the command will look like this:
ssh -p{port} {user}@{ip}

For example:
ssh -p9999 [email protected]

Was this answer helpful?

Back
spinner