Как открыть порт 22 для ssh
Перейти к содержимому

Как открыть порт 22 для ssh

  • автор:

How to Change the SSH Port on VPS, Common Ports and How to Choose the Right One

How to Change the SSH Port on VPS, Common Ports and How to Choose the Right One

Secure Shell (SSH) is a network protocol that allows users to access the server remotely. It also encrypts the communication between a client and private server, making it more secure.

However, using the standard Transmission Control Protocol (TCP) port 22 for SSH might be risky since it is vulnerable to many cyber threats, especially brute-force attacks – a hacking method used to gain access to encrypted sensitive data.

Therefore, changing your default port is one of the best ways to protect your SSH server. In this article, we will explain how to choose a new SSH port and walk you through changing it on your virtual private server (VPS).

How to Choose a New SSH Port

When choosing a new SSH port, note that port numbers 0-1023 are reserved for various services and can only be bound by root access.

Here is a list of the most common privileged services and their associated ports and functions:

SSH configuration file with Port 22

Change the SSH port number to 1026:

Changing SSH port to 1026

Then save the changes.

Pro Tip

If the contents of your sshd_config file look differently, simply add a new Port line, just like in the example above.

3. Configure Your Firewall

Start by making sure the newly selected port is not blocked. If this is a new VPS setup, all ports should be open by default.

Update your firewall settings to allow incoming connections to the new port. For this example, we will be using the UFW firewall. Run the following command:

Next, restart the SSH service using the following command:

Debian and Ubuntu:

Debian and Ubuntu with systemd:

CentOS and Fedora

CentOS and Fedora with systemd:

4. Test the New Default Port

To verify that the new SSH port is open, run either the ss or netstat command:

Screenshot of output for command "s -tulpn | grep 1026"

Screenshot of output for command "ssh -p [port] user@server"

Now you can try to log in to SSH using the following command:

Pro Tip

Test the SSH connection using a new Terminal window. Do not log out from the previous root session until you’ve confirmed that the new setup is working well.

As for Hostinger users, if you cannot connect to your VPS using the new port, you can always reset the SSH and firewall settings to default from your VPS dashboard on hPanel.

Conclusion

Using the default SSH port 22 can make you an easy target for hackers – they often look for open ports through which to intercept and extract sensitive data. Therefore, we recommend changing the SSH port to avoid potential cyber attacks and add extra protection to your Linux server.

Before choosing a new port for your SSH access, note that the ports numbered 0-1023 are reserved for privileged services. Hence, it is best to use a port ranging from 1024 to 65535.

Configuring a new specified port is relatively easy – you only need to update the number in the SSH daemon configuration file and firewall settings. Then, restart the SSH service and test the new port’s connection again.

We hope this article has helped you change your SSH port on VPS. If you have any questions or ideas, please leave them in the comments section below.

Смена порта SSH-сервера как мера защиты от брутфорса

По умолчанию SSH-сервер открывает для входящих соединений 22 TCP-порт, и тем самым вызывает потенциальную угрозу bruteforce-атак, поскольку злоумышленник обнаружив на сервере такой открытый порт, пытается подобрать пароль к удалённому серверу при помощи специальных средств автоматизации.

В этой статье мы опишем, как сконфигурировать SSH-сервер на альтернативном порту.

Особо отметим, что не стоит воспринимать описанный здесь метод, как панацею. Китайская мудрость гласит — «Security by Obscurity is no Security at all». Не забывайте и про другие методы защиты SSH, такие как правильная настройка межсетевого экрана, разрешение доступа только ограниченному набору IP-адресов, отказ от парольной аутентификации и использование ключей RSA/DSA, и т.п.

Конфиг SSH-сервера обычно располагается в /etc/ssh/sshd_config. Для редактирования этого файла вам потребуются привилегии суперпользователя root, или возможность выполнить sudo для получения таких привилегий текстовым редактором.

Выполните команду, например:

В открывшемся файле найдите следующую строку:

Закомментируйте её и добавьте новую строку со случайным номером порта, например 58291. Номер порта не должен превышать 65535. Также удостоверьтесь, что выбранное вами значение не конфликтует с другими сервисами в системе, например mysqld использует порт 3306, httpd — 80, ftpd — 21. Рекомендуем выбрать пятизначное значение.

На всякий случай, для просмотра уже открытых в системе портов, выполните следующую команду:

После модификации, участок файла конфигурации SSH должен выглядеть примерно так:

Что-бы SSH-сервер начал слушать новый порт вместо прежнего, его нужно перезапустить:

Соединение с SSH-сервером на альтернативном порту

Итак, теперь когда у нас есть SSH-сервер, слушающий альтернативный порт, как с ним соединяться? Если вы попытаетесь соединиться при помощи командной строки Linux, то по умолчанию SSH-клиент попытается использовать стандартный порт, и это приведёт к ошибке подключения:

Вместо этого вы должны передать SSH-клиенту номер порта значением параметра -p , примерно так:

Теперь соединение пройдёт успешно.

Если вы используете свободный SSH-клиент PuTTY, то укажите порт в настройках сессии, как показано на картинке:

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 7a251930eb7f77bc • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare

How to open the SSH port 22? [closed]

Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers.

Closed 8 years ago .

I have installed the ssh utility on an embedded system but I can’t connect to it. I am able to ssh from the device to another computer on the network but not the other way around.

The only port opened in the device is the 21st:

When I try to connect to it I get a connection refused error. I have tried with another port but nothing has changed. The configuration file /etc/ssh/sshd_config is the following

I don’t have iptables and I can’t install it. How can I connect to the device using ssh?

Solution

There was a problem with the generated keys. Move them to the /tmp folder

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *