- How to change the ssh port on Linux or Unix server
- Procedure to change the SSH Port for Linux or Unix Server
- Locate sshd_config file by typing the following command
- Edit the file and set Port option
- A note about SELinux users
- Updating your firewall to accept the ssh port 2222 in Linux
- Restart the sshd service
- How to verify that TCP port 2222 opened
- How to use the new SSH port with command line
- Conclusion
- Как изменить порт SSH в Linux
- Изменение порта SSH
- 1. Выбор нового номера порта
- 2. Настройка брандмауэра
- 3. Настройка SSH
- Использование нового порта SSH
- Выводы
- How to Change SSH Port in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- How To Change OpenSSH SSH Server Port Number In Linux?
- Get Ssh Server Port Number From Ssh Configuration
- Change Ssh Server Port Number
- Restart Ssh Server To Apply Configuration
- Check New Port
- Connect Ssh With Different Port Number
- How To Change OpenSSH SSH Server Port Number In Linux? Infografic
- How to Change the Default SSH Port in Linux [Properly and Safely]
- Why change the default SSH port?
- Allow traffic on the new port by changing the firewall settings
- Changing the default SSH port
How to change the ssh port on Linux or Unix server
I am a new Linux/Unix server admin. How do I change the SSH Port for my Linux or Unix server using command line option?
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.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | OpenSSH on Linux or Unix OS |
Est. reading time | 3 minutes |
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 find command.
- Edit the sshd server file and set Port option.
- Save and close the file
- Restart the sshd service to change the ssh port in Linux.
Locate sshd_config file by typing the following command
$ find / -name «sshd_config» 2>/dev/null
Sample outputs:
The find command try to locate sshd server config file named sshd_config. I added the 2>/dev/null at the end to hide find command permission denied messages warning/spam.
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. Please note that port numbers 0-1023 are reserved for various system services. Hence, I recommend choosing port numbers between 1024 and 65535. Here is a common list of privileged services and designated as well-known ports:
Port | Protocol | Service |
---|---|---|
20 | tcp | ftp-data |
21 | tcp | ftp server |
22 | tcp | ssh server |
23 | tcp | telnet server |
25 | tcp | email server |
53 | tcp/udp | Domain name server |
69 | udp | tftp server |
80 | tcp | HTTP server |
110 | tcp/udp | POP3 server |
123 | tcp/udp | NTP server |
443 | tcp | HTTPS server |
Use the cat command/grep command/egrep command to see internet network services list:
cat /etc/services
less /etc/services
more /etc/services
grep -w ’22/tcp’ /etc/services
grep SSH /etc/services
grep -w ’80/tcp’ /etc/services
egrep -w ‘(80|443|110|53)/tcp’ /etc/services
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Viewing or choosing a new SSH port number in Linux
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
Updating your firewall to accept the ssh port 2222 in Linux
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
To open the new port run the following commands on Fedora/CentOS/RHEL/Oracle Linux using FirewallD
$ sudo firewall-cmd —permanent —zone=public —add-port=2222/tcp
$ sudo firewall-cmd —reload
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 systemctl restart ssh
Or if you are using FreeBSD Unix, enter:
$ sudo service sshd restart
How to verify that TCP port 2222 opened
Use the netstat command or ss command:
ss -tulpn | grep 2222
netstat -tulpn | grep 2222
How to use the new SSH port with command line
The syntax is:
ssh -p
sftp -P
scp -P
scp -P
For example:
ssh -p 2222 vivek@server1.cyberciti.biz
Conclusion
This page explained how to change the SSH port on both Linux and Unix-like systems including ssh command line option for connecting the server. For further information please see the following resources:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Как изменить порт SSH в Linux
По умолчанию SSH прослушивает порт 22. Изменение порта SSH по умолчанию добавляет дополнительный уровень безопасности к вашему серверу, снижая риск автоматических атак.
В этом руководстве объясняется, как изменить порт SSH по умолчанию в Linux. Мы также покажем вам, как настроить брандмауэр, чтобы разрешить доступ к новому порту SSH.
Изменение порта SSH
Изменить SSH-порт изображения — простая задача. Все, что вам нужно сделать, это отредактировать файл конфигурации SSH и перезапустить службу.
В следующих разделах объясняется, как изменить порт SSH в системе Linux.
1. Выбор нового номера порта
В Linux номера портов ниже 1024 зарезервированы для хорошо известных служб и могут быть связаны только с пользователем root. Хотя вы можете использовать порт в диапазоне 1-1024 для службы SSH, чтобы избежать проблем с распределением портов в будущем, рекомендуется выбрать порт выше 1024.
В этом примере изменится порт SSH на 5522, вы можете выбрать любой порт, который хотите.
2. Настройка брандмауэра
Перед изменением порта SSH вам необходимо настроить брандмауэр, чтобы разрешить трафик на новый порт SSH.
Если вы используете UFW, инструмент настройки брандмауэра по умолчанию для Ubuntu, выполните следующую команду, чтобы открыть новый порт SSH:
В CentOS инструментом управления брандмауэром по умолчанию является FirewallD. Чтобы открыть новый порт, выполните:
Пользователям CentOS также необходимо настроить правила SELinux:
Если вы используете iptables в качестве брандмауэра, чтобы открыть новый порт, запустите:
3. Настройка SSH
Откройте файл конфигурации SSH /etc/ssh/sshd_config текстовом редакторе:
Найдите строку, начинающуюся с Port 22 . В большинстве случаев эта строка начинается с символа решетки ( # ). Удалите хэш # и введите новый номер порта SSH:
Будьте особенно осторожны при изменении файла конфигурации SSH. Неправильная конфигурация может привести к сбою запуска службы SSH.
После этого сохраните файл и перезапустите службу SSH, чтобы изменения вступили в силу:
В CentOS служба ssh называется sshd :
Чтобы убедиться, что демон SSH прослушивает новый порт 5522, введите:
Результат должен выглядеть примерно так:
Использование нового порта SSH
Чтобы указать порт, вызовите команду ssh за которой следует параметр -p
Если вы регулярно подключаетесь к нескольким системам, вы можете упростить рабочий процесс, указав все свои подключения в файле конфигурации SSH .
Выводы
В этом руководстве вы узнали, как изменить порт SSH на сервере Linux. Вам также следует настроить аутентификацию на основе ключей SSH и подключаться к серверам Linux без ввода пароля.
Не стесняйтесь оставлять комментарии, если у вас есть вопросы.
Источник
How to Change SSH Port in Linux
SSH or Secure Shell daemon is a network protocol that is used to perform remotely secured log ins to Linux systems via a secured channel through unsecured networks using strong cryptography.
One of the most basic utility of SSH protocol is the ability to access Unix shells on remote Linux machines and execute commands. However, SSH protocol can offer other implementations, such as the ability to create secured TCP tunnels over the protocol, to remotely and securely transfer files between machines or to act as a FTP like service.
The standard port used by SSH service is 22/TCP. However, you might want to change SSH default port in your Linux server, in order to achieve some kind of security through obscurity because the standard 22/TCP port is continuously targeted for vulnerabilities by hackers and bots in internet.
To change SSH service default port in Linux, first you need to open the main SSH daemon configuration file for editing with your favorite text editor by issuing the below command and make the following changes.
In sshd_config file, search and comment the line that begins with Port 22, by adding a hashtag (#) in front of the line. Below this line, add a new port line and specify your desired port to bind SSH.
In this example, we’ll configure SSH service to bind and listen on port 34627/TCP. Make sure you choose a random port, preferably higher than 1024 (the superior limit of standard well-known ports). The maximum port that can be setup for for SSH is 65535/TCP.
Change SSH Port in Linux
After you’ve made the above changes, restart the SSH daemon to reflect changes and issue netstat or ss command to confirm that SSH service listens on the new TCP port.
In CentOS or RHEL Linux based distributions, install policycoreutils package and add the below rules to relax SELinux policy in order for the SSH daemon to bind on the new port.
Verify SSH New Port
Also, don’t forget to update the firewall rules specific for your own installed Linux distribution in order to allow incoming connections to be established on the new added SSH port.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
How To Change OpenSSH SSH Server Port Number In Linux?
Remote access is the main method while managing Linux systems. Remote access must be secured accordingly. OpenSSH suite which implements Ssh provides this security with server and client side. OpenSSH also provides auxiliary tools to make copying or identity management easily and securely. OpenSSH servers run by default TCP port 22. We call it generally ssh port. Ssh port number is know for the whole world so attackers can attack to beat our OpenSSH server like brute forcing.
Get Ssh Server Port Number From Ssh Configuration
Ssh server configuration file can be found at /etc/ssh/sshd_config . We will find related configuration line like below.
Get Ssh Server Port Number From Ssh Configuration
We can see that default configuration is used for ports because they are commented.
Change Ssh Server Port Number
We will open configuration file and add line below
Keep in mind be sure there is no other application using this port.
Restart Ssh Server To Apply Configuration
We have changed the configuration but in order to make the new configuration effective we need to restart the SSH service. During restart the SSH service will read its configuration where the new port is 2134 is listening.
Check New Port
There are different ways to check new SSH port. In this example we will use netstat command with the options -tln which means list TCP ports listening.
Connect Ssh With Different Port Number
By default while using ssh command we do not provide the port number 22 explicitly. ssh command assumes the port number 22. But what if we need to connect ssh server which port is different than 22. We will specify port number with -p option. In this example we will connect port number 2134
How To Change OpenSSH SSH Server Port Number In Linux? Infografic
Источник
How to Change the Default SSH Port in Linux [Properly and Safely]
If you are aware of the SSH basics, you already know that SSH uses port 22 by default.
When you connect to a server via SSH, most of the time you don’t provide any port information. And in such cases, your connection goes to the port 22 of the SSH server.
You can change the default port from 22 a port number of your choice using the following steps:
- Open the /etc/ssh/sshd_config file for editing.
- Locate the line that has Port 22 (if it is commented out with #, remove the # as well).
- Change the line to Port 2522 (or any number of your choice between 1024 and 65535).
- Make sure that the new port is allowed by the firewalls (if you have any).
- Restart ssh daemon with sudo systemctl restart sshd .
- From now onwards, you’ll have to specify the port to make the ssh connection ssh [email protected]_address_of_server -p 2522 .
Let me show you the steps in details and also tell you why you may consider changing the
Why change the default SSH port?
One of the most elementary tricks for securing SSH server is to change the default SSH port number 22.
Why? Because a number of bot scripts try the brute force attacks on the default port 22. Most of these scripts don’t always scan for open ports, and they target the default ports for various known services like SSH.
Changing the default SSH port reduces number of such attacks. There are other ways to improve the security of your SSH server. If interested, please follow these actionable tips for improving SSH server security.
Now that you know why you would change the default SSH port, let’s see how to do it.
Allow traffic on the new port by changing the firewall settings
If you have a firewall set or custom ipconfig or ifconfig or if you are using selinux, you must allow the new ssh port before making the changes. Otherwise you may lock yourself out without an SSH access.
Now this part depends upon what kind of firewall or routing you are using.
If you are using UFW, you can use the following command to allow port 2522:
If you are using iptables, you should use this command:
On Fedora, CentOS, Red Hat, the firewall is managed by firewalld and you can use this command:
On CentOS and Red Hat, you may also have to change the SELinux rules:
Now that you have put the correct firewall settings, let’s move on to changing the SSH port.
Changing the default SSH port
Usually, the ssh configuration file is located at /etc/ssh/sshd_config . You’ll have to use a terminal-based editor like Vim or Nano or Emacs to edit the file.
Distributions like Ubuntu have Nano installed by default so you can use it for opening the file in edit mode like this:
As you can see, you’ll have to be a sudo user or root to edit the ssh configuration.
Scroll down a bit and you’ll see a line with Port 22 . If it starts with # , it means the line is commented out. The commented out lines gives you the default settings.
So if you see # Port 22 , it means that default port is 22.
Change this line with a port number of your choice. In Linux, port number 0-1023 are usually reserved for various services. It will be good to avoid using anything between 0 and 1023 to avoid conflicts.
You can use any other port number between 1024 and 65535. I am using 2522 in the example. Make sure to remove the # before the Port line.
Save your changes and exit the editor. If you are using Nano, use Ctrl+X to save and exit.
The next step is to restart the ssh service. Most modern system use systemd services so you can use the following command:
Now if you want to access the SSH server, you’ll have to specify the port number:
Was it helpful?
I hope you find this tutorial helpful in changing the SSH port. Now that you have changed the port, you’ll have to use it all the time you want to connect to the server via SSH and that could be annoying.
This is why I recommend using SSH config file to save the settings for easy and quick access.
Источник