Как поменять порт ssh ubuntu
Перейти к содержимому

Как поменять порт ssh ubuntu

  • автор:

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

Удалённое администрирование Linux, как правило, осуществляется при помощи SSH (Secure Shell) — сетевого протокола прикладного уровня, позволяющего производить туннелирование TCP-соединений. Вышедший в 1995-м году SSH широко используется и в наши дни. С помощью этого протокола, помимо администрирования операционной системы с помощью командной оболочки, можно выполнять файловые операции и монтировать удалённые файловые системы.

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

Как изменить порт SSH?

В большинстве разновидностей Linux конфигурационный файл SSH-сервера располагается по пути /etc/ssh/sshd_config. Тем не менее, можно воспользоваться и поиском для того, чтобы узнать наверняка. Воспользуйтесь командой:

sudo find /etc/ -name «sshd_config»

В данном случае файл там, где и должен быть. Откройте в текстовом редакторе файл sshd_config:

sudo nano /etc/ssh/sshd_config

Найдите строку Port 22 и измените значение (в нашем примере на Port 222). Возможно в вашем конфигурационном файле эта строка будет закомментирована, то есть выглядит вот так — #Port 22.

В этом случае нужно убрать символ # и выполнить действия, описанные выше:

Сохраните файл. Далее следует перезапустить демон SSH. Выполните команду:

sudo systemctl restart sshd

Для того, чтобы проверить прошла ли удачно смена порта SSH сервера, выполните следующую команду:

sudo netstat -tupln | grep ssh

Будут показаны открытые порты SSH на вашем компьютере:

Строка tcp 0.0.0.0:222 LISTEN говорит о том, что 222-й порт, который назначенный для SSH-демона, успешно используется. В SSH-клиентах, подключаемых к вашему компьютеру, нужно будет изменить порт по умолчанию на назначенный SSH-серверу.

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

Если у вас в качестве файрвола установлен UFV, выполните команду:

sudo ufw allow 222/tcp

Для тех, кто использует iptables, необходимо разрешить новый порт с помощью команды:

sudo /sbin/iptables -A INPUT -m state —state NEW -m tcp -p tcp —dport 222 -j ACCEPT

В операционных системах, использующих firewalld, выполните такую команду:

sudo firewall-cmd —permanent —add-port=222/tcp sudo firewall-cmd reload

Здесь порт 222 — это порт SSH, назначенный мною для примера. Теперь вы знаете как поменять порт SSH чтобы его не трогали боты. А какие методы защиты от ботов используете вы? Напишите в комментариях!

Changing SSH port in Ubuntu or Debian

SSH or Secure Command is a network protocol, that helps to connect and perform operation in the remote machine. You can connect to SSH with key or username and password.

By default SSH uses port 22. You may need to change the ssh port for security security reasons such as to avoid targets from bots. You can change the default port by below steps.

  • Login to the server/remote machine
  • Open /etc/ssh/sshd_config
  • Locate the text: Port 22
  • Change the port which you want to set. Choose a port between 1024 and65535.
  • Save the file and exit
  • Restart the ssh service: sudo systemctl restart sshd
  • Disconnect from the server
  • Now, connect to machine with specifying new port as SSH is not utilising default port. Use code as below to ssh into the machine.

Note: -p is used for ssh and -P is used for scp to specify the port

How to run the SSH server on a port other than 22

I have two computers behind the same router. Let’s call them A and B.

A can SSH to B in the following manner: ssh usr@<internal ip of computer>

B can SSH to A by doing the same, but the external IP must be used. I have forwarded port 22 of my router to the IP of computer A, so that all makes sense to me.

However, I want to also forward port 26 to computer B, and SSH from outside the network by using the external IP for both, but specifying either port 22 or 26, to effectively select which computer to use.

I have tried allowing port 26 through OUTPUT of iptables on A and INPUT of B, but that didn’t seem to work. I have also forwarded port 26 to the internal IP of B (through the router), as I did with 22 for A.

Here’s what I get when I try to SSH from A to B using the external IP and port 26:

  • A = OpenSSH_5.9p1 Debian-5ubuntu1, OpenSSL 1.0.1 14 Mar 2012
  • B = OpenSSH_6.0p1 Debian-4, OpenSSL 1.0.1c 10 May 2012

A has 12.04 Ubuntu, B is a Raspberry Pi with Raspbian.

EDIT: Something that I forgot to put in: I did try switching the SSH config file (I found it is /etc/ssh/ssh_config ) I uncommented (deleted the # ) the line with Port and changed 22 to 26 . It gave me the connection refused message still. (I rebooted to no avail.)

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

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