Перейти к содержимому

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

  • автор:

How to Change SSH Port in Ubuntu 18.04

This tutorial explains how to configure Ubuntu OpenSSH server to run on some specific port number rather than the default port number 22, in order to increase the overall security of your Ubuntu server.

The SSH server on Ubuntu listen on TCP port 22 by default. You can run the netstat command to check ssh port currently running on:

run the netstat command to check ssh port currently running on

As you can see, the SSH daemon is currently running on TCP port 22.

In Ubuntu 18.04, the Port directive of the sshd_config config file specifies the port number that ssh server listens on. You can check the current configuration with following command:

The Port directive is commented out by default, which means SSH daemon listens on the default port 22.

The Port directive of the sshd_config config file specifies the port number that ssh server listens on

If you want to change the default SSH port in Ubuntu, perform the following steps with root privileges:

  1. Open the /etc/ssh/sshd_config file and locate the line:
  2. Then, uncomment (Remove the leading # character) it and change the value with an appropriate port number (for example, 22000):
  3. Restart the SSH server:

After that, run the netstat command and make sure that the ssh daemon now listen on the new ssh port:

When connecting to the server using the ssh command, you need to specify the port to connect using the -p flag:

Note that if the Firewall is enabled, you need to add a rule to allow new SSH port.

How to Change the SSH Port in Linux | A Quick Step-by-Step Guide to Your SSH Port

how to change ssh port

If you plan to boost your server’s security, you will need to change the SSH port from its default value. The default port number is a widely known fact and that makes it a security risk that you can’t afford. To make the procedure easy, we provide step-by-step instructions in plain English that tell you how to change the SSH port in Linux. The overview contains some basic information on the SSH protocol and why it’s important to your server security. Of course, you may skip it and just start with the tutorial.

What is SSH?

The Secure SHell protocol (SSH) is a security measure that gives you and other users the ability to connect to a secure server over an unsecured network (like the Internet). This becomes indispensable when you’re planning on running a server (whether a VPS or a dedicated server). You have to connect to your server from your laptop and that connection has to go through the Internet to get there. The Internet, obviously, is an unsecured environment, meaning you can’t afford to let your guard down. That is why the Secure SHell protocol is also equipped with several valuable tools that help establish and maintain server security, including tools for password and key authentication.

Why is SSH Security Important?

When you get a dedicated server or a VPS, you will be given full root access to the system, which means you can use the SSH protocol to remotely connect to the server and make any configurations you need. While SSH does not support graphics and only provides a Command-Line Interface, it is still the main method of server administration. Like all network-based services, SSH uses a default port number. But because the SSH port is harder to change than that in other protocols, like VNC, some users don’t bother to change it. That means hackers and malicious software will have more of a chance to gain access to your server because they know which port to target. So, you should take the time to change the default SSH port once and for all, and with this tutorial, you can do it quickly and without extra effort.

Linux Hosting SimplifiedLinux Hosting Simplified

Want a better way to host your websites and web apps? Developing something new? Simply don’t like Windows? That’s why we have Linux VPS.

How to Change SSH Port in Linux

Throughout the tutorial, we’re going to be using the Linux Terminal to enter the necessary commands. The screenshots are taken from Fedora Server 34 but most of the commands work for all major Linux distributions. Where distro-specific commands are needed, we provide them separately. To go through these steps you need to be signed in to your server using VNC or SSH. With the explanation out of the way, let’s get started with the actual process.

Step 1: Launching the Terminal

First, we need to open the Terminal. If you’re using SSH, you will be using the terminal by default. If you’re using a remote desktop protocol like VNC, you can open the Terminal by pressing Ctrl+Alt+T or by searching the applications menu in all Linux distributions.

Step 2: Edit the SSH Config File

Now, we’re going to use the nano text editor . Nano lets you edit texts right from the CLI, making it the perfect choice for SSH connections. Nano should be installed by default; if it’s not, see the appendix for the commands to install it. We’re going to use the editor to edit the SSH configuration file: /etc/ssh/sshd_config (you can use your favorite text editor if you have a remote desktop connection). For that, you should enter the following command:

Now, scroll down until you find the Port attribute:

[nano editor on Linux Terminal displaying the SSH config file]

Step 3: (Optional) Change the SSH Port for Security

As you can see, the default port is mentioned as 22, and the # before it means this line is a commend. To make any changes, you must remember to delete the # to uncomment it. Some people like to use SSH port 443, which is usually reserved for SSL encryption, thereby confusing would-be hackers. Let’s say you want to change the SSH port to 3333; to do that, make the following change:

Again, make sure there is no # before the word Port . Press Ctrl+O to save the changes you’ve made and Ctrl+X to exit the editor.

Step 4: Restart the SSHD Service to Finalize Changes

You have finished configuring the SSH settings but for the changes to take effect, you have to restart the SSHD service in charge of SSH connections. For that, enter the following command:

Step 5: Configure your Firewall

Before starting to enjoy your enhanced server security, however, you should configure your firewall to stop blocking your new SSH port. This is where the distro-specific commands come in, because of the default firewalls used by different distros.

How to Change SSH Port in CentOS/RHEL/Fedora

Most RHEL-based distros, like CentOS, use a security suite called SELinux (Security-Enhanced Linux), which acts as a firewall, among other things. Before going any further, however, you should first see if SELinux is actually enabled. To do that, enter the following command

If you see something like this, with the first line reading SELinux status: enabled then you’ll have to go through the following steps. Otherwise, you can just skip this and continue to the last step here .

[Command to check SELinux on/off status]

Now that we have determined SELinux is enabled, we’ll use the semanage package. If it was disabled, you can use these instructions to quickly turn SELinux on. Use the following command to add the port you have chosen to SELinux’s list of SSH ports (3333 in this example):

Now, we need to tell the firewall to add port 3333 to your public zone, which is the registered range of open port numbers:

All that’s left now is to restart the firewall service to make the changes take effect:

That’s that for CentOS change SSH port. You can test the new port below.

How to Change SSH Port in Ubuntu/Debian/Kali

Ubuntu and some other Debian-based distros have the UFW firewall installed and active by default. That can be done using the following command, which you need to enter into the Terminal like the ones before:

That’s it for Ubuntu change SSH port. Now let’s just move on to testing the connection with the new port.

Testing the New SSH Port

Now, to see if everything worked out the way it should, we will do a quick test to see if our SSH port forwarding has been successful. If you’ve been using SSH to this point, you should first exit the session by closing the shell. Open a Terminal on your client and enter the following command to establish an SSH connection:

Of course, you should replace 00.00.00 with the correct IP address for your server, which you can get from your control panel on your provider’s website.

Linux Hosting SimplifiedLinux Hosting Simplified

Want a better way to host your websites and web apps? Developing something new? Simply don’t like Windows? That’s why we have Linux VPS.

Other Security Measures

This is it, as far as boosting your server SSH security will go, but there is always more. The security tasks of an administrator are never done. There are still things to do, like disabling root account access, creating stronger passwords, etc. Of course, the hosting provider plays the most important role in ensuring server security, so picking the right one is vital. That is why Cloudzy runs its Linux VPS servers on extra-secure servers with hardware and AI-based firewalls, smart DDoS protection, and other proprietary safeguards. Put your mind at ease and get a secure Linux VPS solution from Cloudzy today.

Смена порта 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 чтобы его не трогали боты. А какие методы защиты от ботов используете вы? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Changing SSH port in Ubuntu or Debian

Karikevinod

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

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

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