Как открывать порты в системе Linux
Порт — это конечная точка соединения. В операционной системе порт открывается или закрывается для передачи пакетов данных определенных процессов или сетевых служб.
Обычно порты определяют конкретную присвоенную им сетевую службу. Это можно изменить вручную, настроив службу на использование другого порта, но в целом можно оставить значения по умолчанию.
Первые 1024 порта (номера портов от 0 до 1023) называются общеизвестными или системными и зарезервированы для часто используемых служб. К ним относятся SSH (порт 22), HTTP (порт 80), HTTPS (порт 443) и тому подобное.
Номера портов выше 1024 называются эфемерными портами.
- Порты с номерами от 1024 до 49151 называются зарегистрированными/пользовательскими.
- Номера портов с 49152 по 65535 называются динамическими/частными портами.
В этом мануале мы откроем эфемерный порт в Linux, поскольку общие службы используют известные порты.
Требования
Для выполнения туториала нужно уметь пользоваться терминалом.
Проверка открытых портов
Прежде чем открыть порт в Linux, нужно проверить список всех открытых портов и выбрать эфемерный порт, которого нет в этом списке.
С помощью команды netstat можно получить список всех открытых портов, включая TCP и UDP — это распространенные протоколы для передачи пакетов на сетевом уровне.
Учитывая используемые флаги, команда выводит следующее:
- все прослушиваемые сокеты (-l)
- номер порта (-n)
- TCP-порты (-t)
- UDP-порты (-u)
Active Internet connections (only servers)
Примечание. Если в вашем дистрибутиве нет netstat, то с помощью команды ss можно вывести список открытых портов путем проверки сокетов прослушивания.
Убедитесь, что команда ss выводит согласованные выходные данные:
Получим следующий вывод:
Эта команда выводит практически те же открытые порты, что и netstat.
Открытие порта для TCP-соединений
Теперь откроем закрытый порт и настроим его на прослушивание TCP-соединений.
В этом туториале мы откроем порт 4000. Но при желании вы можете выбрать другой закрытый порт. Только убедитесь, что его номер больше 1023.
С помощью команды netstat убедитесь, что порт 4000 не используется:
netstat -na | grep :4000
То же самое можно сделать с помощью команды ss:
ss -na | grep :4000
Вывод должен быть пустым, таким образом подтверждается, что порт сейчас не используется, чтобы была возможность вручную добавить правила порта в системный брандмауэр iptables.
Ubuntu и системы на базе ufw
ufw — клиент командной строки для брандмауэра UncomplicatedFirewall.
Команда будет выглядеть следующим образом:
sudo ufw allow 4000
CentOS и системы на базе firewalld
firewall-cmd — клиент командной строки для брандмауэра firewalld.
Команды будут выглядеть так:
Для других дистрибутивов Linux
Изменить системные правила фильтрации пакетов IPv4 можно с помощью iptables.
iptables -A INPUT -p tcp —dport 4000 -j ACCEPT
Тестирование порта
После успешного открытия TCP-порта нужно его протестировать.
При отправке вывода ls любому подключенному клиенту, сначала запустите netcat (nc) и прослушивайте (-l) порт (-p) 4000:
ls | nc -l -p 4000
Теперь клиент получит вывод ls после того, как он откроет TCP-соединение на порту 4000. Пока оставьте этот сеанс.
Откройте другой терминал на той же машине.
Поскольку мы открыли TCP-порт, мы можем протестировать TCP-подключения с помощью telnet. Если у вас этой команды нет, установите ее с помощью менеджера пакетов.
Введите IP вашего сервера и номер порта (в данном случае 4000) и выполните следующую команду:
telnet localhost 4000
Эта команда пытается открыть TCP-соединение на локальном хосте через порт 4000.
Получим следующий вывод, в котором указано, что соединение с программой установлено (nc):
Вывод ls (в данном примере while.sh) отправлен клиенту, что указывает на успешное TCP-соединение.
С помощью nmap проверьте, открыт ли порт (-p):
nmap localhost -p 4000
Эта команда проверит открытый порт:
Как видите, вы успешно открыли новый порт в Linux.
Примечание: nmap выводит список только открытых портов, на которых в данный момент есть прослушивающее приложение. Если вы не используете приложение для прослушивания (например netcat), то порт 4000 будет отображаться как закрытый, поскольку в настоящее время на этом порту нет ни одного прослушивающего приложения. Аналогично не будет работать и telnet, поскольку этой команде также нужно прослушивающее приложение. Именно по этой причине nc такой полезный инструмент. Он имитирует такие среды с помощью простой команды.
Но порт открыт временно, так как изменения будут сбрасываться при каждой перезагрузке системы.
Сохранение правил брандмауэра
Способ, который мы рассмотрели в этом мануале только временно обновляет правила брандмауэра, пока система не выключится или не перезагрузится. Поэтому для повторного открытия того же порта после перезагрузки необходимо повторить эти шаги. Однако правила брандмауэра можно сохранить навсегда.
Для брандмауэра ufw
Правила ufw не сбрасываются при перезагрузке. Это происходит потому, что он интегрирован в процесс загрузки, и ядро применяет соответствующие конфигурационные файлы и сохраняет правила брандмауэра ufw.
Для firewalld
Необходимо применить флаг –permanent, чтобы правила были действительны после перезагрузки системы.
Для iptables
Чтобы сохранить правила конфигурации, рекомендуется использовать iptables-persistent.
Подводим итоги
В этом туториале мы разобрали, как открыть новый порт в Linux и настроить его для входящих соединений, а также поработали с netstat, ss, telnet, nc и nmap.
Security — Firewall
The Linux kernel includes the Netfilter subsystem, which is used to manipulate or decide the fate of network traffic headed into or through your server. All modern Linux firewall solutions use this system for packet filtering.
The kernel’s packet filtering system would be of little use to administrators without a userspace interface to manage it. This is the purpose of iptables: When a packet reaches your server, it will be handed off to the Netfilter subsystem for acceptance, manipulation, or rejection based on the rules supplied to it from userspace via iptables. Thus, iptables is all you need to manage your firewall, if you’re familiar with it, but many frontends are available to simplify the task.
ufw — Uncomplicated Firewall
The default firewall configuration tool for Ubuntu is ufw. Developed to ease iptables firewall configuration, ufw provides a user-friendly way to create an IPv4 or IPv6 host-based firewall.
ufw by default is initially disabled. From the ufw man page:
“ufw is not intended to provide complete firewall functionality via its command interface, but instead provides an easy way to add or remove simple rules. It is currently mainly used for host-based firewalls.”
The following are some examples of how to use ufw:
First, ufw needs to be enabled. From a terminal prompt enter:
To open a port (SSH in this example):
Rules can also be added using a numbered format:
Similarly, to close an opened port:
To remove a rule, use delete followed by the rule:
It is also possible to allow access from specific hosts or networks to a port. The following example allows SSH access from host 192.168.0.2 to any IP address on this host:
Replace 192.168.0.2 with 192.168.0.0/24 to allow SSH access from the entire subnet.
Adding the –dry-run option to a ufw command will output the resulting rules, but not apply them. For example, the following is what would be applied if opening the HTTP port:
ufw can be disabled by:
To see the firewall status, enter:
And for more verbose status information use:
To view the numbered format:
Note
If the port you want to open or close is defined in /etc/services , you can use the port name instead of the number. In the above examples, replace 22 with ssh.
This is a quick introduction to using ufw. Please refer to the ufw man page for more information.
ufw Application Integration
Applications that open ports can include an ufw profile, which details the ports needed for the application to function properly. The profiles are kept in /etc/ufw/applications.d , and can be edited if the default ports have been changed.
To view which applications have installed a profile, enter the following in a terminal:
Similar to allowing traffic to a port, using an application profile is accomplished by entering:
An extended syntax is available as well:
Replace Samba and 192.168.0.0/24 with the application profile you are using and the IP range for your network.
Note
There is no need to specify the protocol for the application, because that information is detailed in the profile. Also, note that the app name replaces the port number.
To view details about which ports, protocols, etc., are defined for an application, enter:
Not all applications that require opening a network port come with ufw profiles, but if you have profiled an application and want the file to be included with the package, please file a bug against the package in Launchpad.
IP Masquerading
The purpose of IP Masquerading is to allow machines with private, non-routable IP addresses on your network to access the Internet through the machine doing the masquerading. Traffic from your private network destined for the Internet must be manipulated for replies to be routable back to the machine that made the request. To do this, the kernel must modify the source IP address of each packet so that replies will be routed back to it, rather than to the private IP address that made the request, which is impossible over the Internet. Linux uses Connection Tracking (conntrack) to keep track of which connections belong to which machines and reroute each return packet accordingly. Traffic leaving your private network is thus “masqueraded” as having originated from your Ubuntu gateway machine. This process is referred to in Microsoft documentation as Internet Connection Sharing.
ufw Masquerading
IP Masquerading can be achieved using custom ufw rules. This is possible because the current back-end for ufw is iptables-restore with the rules files located in /etc/ufw/*.rules . These files are a great place to add legacy iptables rules used without ufw, and rules that are more network gateway or bridge related.
The rules are split into two different files, rules that should be executed before ufw command line rules, and rules that are executed after ufw command line rules.
First, packet forwarding needs to be enabled in ufw. Two configuration files will need to be adjusted, in /etc/default/ufw change the DEFAULT_FORWARD_POLICY to “ACCEPT”:
Then edit /etc/ufw/sysctl.conf and uncomment:
Similarly, for IPv6 forwarding uncomment:
Now add rules to the /etc/ufw/before.rules file. The default rules only configure the filter table, and to enable masquerading the nat table will need to be configured. Add the following to the top of the file just after the header comments:
The comments are not strictly necessary, but it is considered good practice to document your configuration. Also, when modifying any of the rules files in /etc/ufw , make sure these lines are the last line for each table modified:
For each Table a corresponding COMMIT statement is required. In these examples only the nat and filter tables are shown, but you can also add rules for the raw and mangle tables.
Note
In the above example replace eth0, eth1, and 192.168.0.0/24 with the appropriate interfaces and IP range for your network.
Finally, disable and re-enable ufw to apply the changes:
IP Masquerading should now be enabled. You can also add any additional FORWARD rules to the /etc/ufw/before.rules . It is recommended that these additional rules be added to the ufw-before-forward chain.
iptables Masquerading
iptables can also be used to enable Masquerading.
Similar to ufw, the first step is to enable IPv4 packet forwarding by editing /etc/sysctl.conf and uncomment the following line:
If you wish to enable IPv6 forwarding also uncomment:
Next, execute the sysctl command to enable the new settings in the configuration file:
IP Masquerading can now be accomplished with a single iptables rule, which may differ slightly based on your network configuration:
The above command assumes that your private address space is 192.168.0.0/16 and that your Internet-facing device is ppp0. The syntax is broken down as follows:
-t nat – the rule is to go into the nat table
-A POSTROUTING – the rule is to be appended (-A) to the POSTROUTING chain
-s 192.168.0.0/16 – the rule applies to traffic originating from the specified address space
-o ppp0 – the rule applies to traffic scheduled to be routed through the specified network device
-j MASQUERADE – traffic matching this rule is to “jump” (-j) to the MASQUERADE target to be manipulated as described above
Also, each chain in the filter table (the default table, and where most or all packet filtering occurs) has a default policy of ACCEPT, but if you are creating a firewall in addition to a gateway device, you may have set the policies to DROP or REJECT, in which case your masqueraded traffic needs to be allowed through the FORWARD chain for the above rule to work:
The above commands will allow all connections from your local network to the Internet and all traffic related to those connections to return to the machine that initiated them.
If you want masquerading to be enabled on reboot, which you probably do, edit /etc/rc.local and add any commands used above. For example add the first command with no filtering:
Firewall logs are essential for recognizing attacks, troubleshooting your firewall rules, and noticing unusual activity on your network. You must include logging rules in your firewall for them to be generated, though, and logging rules must come before any applicable terminating rule (a rule with a target that decides the fate of the packet, such as ACCEPT, DROP, or REJECT).
If you are using ufw, you can turn on logging by entering the following in a terminal:
To turn logging off in ufw, simply replace on with off in the above command.
If using iptables instead of ufw, enter:
A request on port 80 from the local machine, then, would generate a log in dmesg that looks like this (single line split into 3 to fit this document):
The above log will also appear in /var/log/messages , /var/log/syslog , and /var/log/kern.log . This behavior can be modified by editing /etc/syslog.conf appropriately or by installing and configuring ulogd and using the ULOG target instead of LOG. The ulogd daemon is a userspace server that listens for logging instructions from the kernel specifically for firewalls, and can log to any file you like, or even to a PostgreSQL or MySQL database. Making sense of your firewall logs can be simplified by using a log analyzing tool such as logwatch, fwanalog, fwlogwatch, or lire.
Other Tools
There are many tools available to help you construct a complete firewall without intimate knowledge of iptables. A command-line tool with plain-text configuration files:
- Shorewall is a very powerful solution to help you configure an advanced firewall for any network.
References
The Ubuntu Firewall wiki page contains information on the development of ufw.
Also, the ufw manual page contains some very useful information: man ufw .
Открытие портов в Linux
Безопасное соединение узлов сети и обмен информацией между ними напрямую связан с открытыми портами. Подключение и передача трафика производится именно через определенный порт, а если в системе он закрыт, выполнить такой процесс не представится возможным. Из-за этого некоторые пользователи заинтересованы в пробросе одного или нескольких номеров для наладки взаимодействия устройств. Сегодня мы покажем, как выполняется поставленная задача в операционных системах, основанных на ядре Linux.
Открываем порты в Linux
Хоть во многих дистрибутивах по умолчанию присутствует встроенный инструмент по управлению сетями, все же такие решения часто не позволяют в полной мере осуществить настройку открытия портов. Инструкции данной статьи будут основаны на дополнительном приложении под названием Iptables — решение для редактирования параметров межсетевого экрана с использованием прав суперпользователя. Во всех сборках ОС на Линуксе она работает одинаково, разве что отличается команда для установки, но об этом мы поговорим ниже.
Если вы хотите узнать, какие из портов уже открыты на компьютере, вы можете воспользоваться встроенной или дополнительной утилитой консоли. Детальные инструкции по поиску необходимой информации вы найдете в другой нашей статье, перейдя по следующей ссылке, а мы же приступаем к пошаговому разбору открытия портов.
Шаг 1: Установка Iptables и просмотр правил
Утилита Iptables изначально не входит в состав операционной системы, из-за чего ее нужно самостоятельно инсталлировать из официального репозитория, а уже потом работать с правилами и всячески изменять их. Установка не занимает много времени и выполняется через стандартную консоль.

-
Откройте меню и запустите «Терминал». Сделать это также можно, используя стандартную горячую клавишу Ctrl + Alt + T.
Как видите, в дистрибутиве теперь появилась команда iptables , отвечающая за управление одноименной утилитой. Еще раз напомним, что работает этот инструмент от прав суперпользователя, поэтому в строке обязательно должна содержаться приставка sudo , а уже потом остальные значения и аргументы.
Шаг 2: Разрешение обмена данными
Никакие порты не будут нормально функционировать, если утилита запрещает обмен информацией на уровне собственных правил межсетевого экрана. Кроме всего, отсутствие необходимых правил в дальнейшем может вызывать появление различных ошибок при пробросе, поэтому мы настоятельно советуем выполнить следующие действия:
- Убедитесь, что в конфигурационном файле отсутствуют какие-либо правила. Лучше сразу же прописать команду для их удаления, а выглядит она так: sudo iptables -F .

- Теперь добавляем правило для вводимых данных на локальном компьютере, вставив строку sudo iptables -A INPUT -i lo -j ACCEPT .

- Примерно такая же команда — sudo iptables -A OUTPUT -o lo -j ACCEPT — отвечает за новое правило для отправки информации.

Благодаря указанным выше параметрам вы обеспечили корректную отправку и прием данных, что позволит без проблем взаимодействовать с сервером или другим компьютером. Осталось только открыть порты, через которые и будет осуществляться то самое взаимодействие.
Шаг 3: Открытие необходимых портов
Вы уже ознакомлены с тем, по какому принципу добавляются новые правила в конфигурацию Iptables. Существуют и несколько аргументов, позволяющих открыть определенные порты. Давайте разберем эту процедуру на примере популярных портов под номерами 22 и 80.
-
Запустите консоль и введите туда две следующие команды поочередно:
sudo iptables -A INPUT -p tcp —dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp —dport 80 -j ACCEPT .
В случае когда уже администратор компьютера внес свои правила в инструмент, организовал сброс пакетов при подходе к точке, например, через sudo iptables -A INPUT -j DROP , вам нужно использовать другую команду sudo iptables: -I INPUT -p tcp —dport 1924 -j ACCEPT , где 1924 — номер порта. Она добавляет необходимый порт в начало цепи, и тогда пакеты не сбрасываются.

Далее вы можете прописать все ту же строку sudo iptables -L и убедиться в том, что все настроено корректно.

Теперь вы знаете, как пробрасываются порты в операционных системах Linux на примере дополнительной утилиты Iptables. Советуем обязательно следить за появляющимися строками в консоли при вводе команд, это поможет вовремя обнаружить какие-либо ошибки и оперативно устранить их.
How To Open a Port on Linux

A port is a communication endpoint. Within an operating system, a port is opened or closed to data packets for specific processes or network services.
Typically, ports identify a specific network service assigned to them. This can be changed by manually configuring the service to use a different port, but in general, the defaults can be used.
The first 1024 ports (port numbers 0 to 1023 ) are referred to as well-known port numbers and are reserved for the most commonly used services. These include SSH (port 22 ), HTTP (port 80 ), HTTPS (port 443 ).
Port numbers above 1024 are referred to as ephemeral ports.
- Port numbers 1024 to 49151 are called the registered/user ports.
- Port numbers 49152 to 65535 are called the dynamic/private ports.
In this tutorial, you will open an ephemeral port on Linux, since the most common services use the well-known ports.
Prerequisites
To complete this tutorial, you will need:
- Familiarity with using the terminal.
List All Open Ports
Before opening a port on Linux, you must check the list of all open ports, and choose an ephemeral port to open that is not on that list.
Use the netstat command to list all open ports, including TCP and UDP, which are the most common protocols for packet transmission in the network layer.
This will print:
- all listening sockets ( -l )
- the port number ( -n )
- TCP ports ( -t )
- UDP ports ( -u )
Note: If your distribution doesn’t have netstat , you can use the ss command to display open ports by checking for listening sockets.
Verify that you are receiving consistent outputs using the ss command to list listening sockets with an open port:
This will print:
This gives more or less the same open ports as netstat .
Opening a Port on Linux to Allow TCP Connections
Now, open a closed port and make it listen for TCP connections.
For the purposes of this tutorial, you will be opening port 4000 . However, if that port is not open in your system, feel free to choose another closed port. Just make sure that it’s greater than 1023 .
Ensure that port 4000 is not used using the netstat command:
Or the ss command:
The output must remain blank, thus verifying that it is not currently used, so that you can add the port rules manually to the system iptables firewall.
For Ubuntu Users and ufw -based Systems
Use ufw — the command line client for the UncomplicatedFirewall.
Your commands will resemble:
Refer to How to Setup a ufw Firewall Setup for your distribution.
Note:
- Ubuntu 14.0.4: “Allow Specific Port Ranges”
- Ubuntu 16.0.4/18.0.4/20.0.4/22.0.4: “Allowing Other Connections / Specific Port Ranges”
- Debian 9/10/11: “Allowing Other Connections / Specific Port Ranges”
For CentOS and firewalld -based Systems
Use firewall-cmd — the command line client for the firewalld daemon.
Your commands will resemble:
Refer to How to Set Up firewalld for your distribution.
Note:
- CentOS 7/8: “Setting Rules for your Applications / Opening a Port for your Zones”
- Rocky Linux 8/9: “Setting Rules for your Applications / Opening a Port for your Zones”
For Other Linux Distributions
Use iptables to change the system IPv4 packet filter rules.
Note:
- Ubuntu 12.04: “A Basic Firewall”
- Ubuntu 14.04: “Accept Other Necessary Connections”
Test the Newly Opened Port for TCP Connections
Now that you have successfully opened a new TCP port, it is time to test it.
First, start netcat ( nc ) and listen ( -l ) on port ( -p ) 4000 , while sending the output of ls to any connected client:
Now, after a client has opened a TCP connection on port 4000 , they will receive the output of ls . Leave this session alone for now.
Open another terminal session on the same machine.
Since you opened a TCP port, use telnet to check for TCP Connectivity. If the command doesn’t exist, install it using your package manager.
Input your server IP and the port number ( 4000 in this example) and run this command:
This command tries to open a TCP connection on localhost on port 4000 .
You’ll get an output similar to this, indicating that a connection has been established with the listening program ( nc ):
The output of ls ( while.sh , in this example) has also been sent to the client, indicating a successful TCP Connection.
Use nmap to check if the port ( -p ) is open:
This command will check the open port:
The port has been opened. You have successfully opened a new port on your Linux system.
Note: nmap only lists opened ports that have a currently listening application. If you don’t use any listening application, such as netcat, this will display the port 4000 as closed since there isn’t any application listening on that port currently. Similarly, telnet won’t work either since it also needs a listening application to bind to. This is the reason why nc is such a useful tool. This simulates such environments in a simple command.
But this is only temporary, as the changes will be reset every time you reboot the system.
Persisting Rules
The approach presented in this article will only temporarily update the firewall rules until the system shuts down or reboots. So similar steps must be repeated to open the same port again after a restart.
For ufw Firewall
ufw rules do not reset on reboot. This is because it is integrated into the boot process, and the kernel saves the firewall rules using ufw by applying appropriate config files.
For firewalld
You will need to apply the —permanent flag.
Refer to How to Set Up firewalld for your distribution.
Note:
- CentOS 7/8: “Setting Rules for your Applications”
- Rocky Linux 8/9: “Setting Rules for your Applications”
For iptables
You will need to save the configuration rules. These tutorials recommend iptables-persistent .
Note:
- Ubuntu 12.04: “Saving Iptables Rules”
- Ubuntu 14.04: “Saving your Iptables Configuration”
Conclusion
In this tutorial, you learned how to open a new port on Linux and set it up for incoming connections. You also used netstat , ss , telnet , nc , and nmap .
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.