How to open port linux

How to open port linux

Открытие портов в Linux

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

Безопасное соединение узлов сети и обмен информацией между ними напрямую связан с открытыми портами. Подключение и передача трафика производится именно через определенный порт, а если в системе он закрыт, выполнить такой процесс не представится возможным. Из-за этого некоторые пользователи заинтересованы в пробросе одного или нескольких номеров для наладки взаимодействия устройств. Сегодня мы покажем, как выполняется поставленная задача в операционных системах, основанных на ядре Linux.

Открываем порты в Linux

Хоть во многих дистрибутивах по умолчанию присутствует встроенный инструмент по управлению сетями, все же такие решения часто не позволяют в полной мере осуществить настройку открытия портов. Инструкции данной статьи будут основаны на дополнительном приложении под названием Iptables — решение для редактирования параметров межсетевого экрана с использованием прав суперпользователя. Во всех сборках ОС на Линуксе она работает одинаково, разве что отличается команда для установки, но об этом мы поговорим ниже.

Если вы хотите узнать, какие из портов уже открыты на компьютере, вы можете воспользоваться встроенной или дополнительной утилитой консоли. Детальные инструкции по поиску необходимой информации вы найдете в другой нашей статье, перейдя по следующей ссылке, а мы же приступаем к пошаговому разбору открытия портов.

Шаг 1: Установка Iptables и просмотр правил

Утилита Iptables изначально не входит в состав операционной системы, из-за чего ее нужно самостоятельно инсталлировать из официального репозитория, а уже потом работать с правилами и всячески изменять их. Установка не занимает много времени и выполняется через стандартную консоль.

Шаг 2: Разрешение обмена данными

Никакие порты не будут нормально функционировать, если утилита запрещает обмен информацией на уровне собственных правил межсетевого экрана. Кроме всего, отсутствие необходимых правил в дальнейшем может вызывать появление различных ошибок при пробросе, поэтому мы настоятельно советуем выполнить следующие действия:

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

Благодаря указанным выше параметрам вы обеспечили корректную отправку и прием данных, что позволит без проблем взаимодействовать с сервером или другим компьютером. Осталось только открыть порты, через которые и будет осуществляться то самое взаимодействие.

Шаг 3: Открытие необходимых портов

Вы уже ознакомлены с тем, по какому принципу добавляются новые правила в конфигурацию Iptables. Существуют и несколько аргументов, позволяющих открыть определенные порты. Давайте разберем эту процедуру на примере популярных портов под номерами 22 и 80.

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

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

Easy steps to open a port in Linux RHEL/CentOS 7/8

Table of Contents

In this article I will share examples to check port status and open a port in Linux. This article was written while using CentOS 8, so it is safe to say that it also fully covers CentOS/RHEL 7/8, Fedora, Oracle Enterprise Linux and generally the whole Red Hat family of operating systems and possibly Novell’s SLES and OpenSUSE.

Before we jump into the examples to open a port in Linux, we must understand the requirement clearly. The very basic question which comes to my mind

We will cover all these scenarios in this article

Check port status

To check the list of existing ports which are open we will use nmap to check port status:

Currently we see only two ports are open on my CentOS 8 node.

Check list of listening ports

We will use netstat to list the TCP ports which are in listening state. The total number of ports are higher compared to the nmap output.

Open a port for some service

If this is your requirement then you are looking for the wrong question. Basically it is other way round i.e. a service will open a port. For example when you start SSHD service, by default it will start port 22 and not the other way round i.e. if you open port 22, it will not automatically start SSHD service.

Let us observe this in example, we know that port 22 is open on my CentOS 8 node. If I stop the sshd service

You can see that port 22 is not open anymore.

You must use respective service’s configuration file to change the default port. Once done you can restart the service and that should automatically open the respective port on your Linux node.

This covers the first scenario.

firewalld open port

It is also possible that your ports are disabled in firewall. If your port is not listed in nmap then it is most likely blocked by firewall.

We will use firewalld to open a port as this is the most used interface today in RHEL/CentOS 7 and 8. Determine which zone the system’s network interfaces are in. In the following example, the eth0 and eth1 interface is in the ‘public’ zone:

Once firewalld open port, next use netstat to check port status:

Use nc or ncat to open a port in Linux

Open another terminal of this server and check port status

As you see port 1234 is listening for both IPv4 and IPv6. To only use IPv4 use -4 with the above command

Next on another terminal you can check port status for port 1234

Use nc or ncat to open a port and transfer files

We can also use nc to transfer file from one host to another host. Here I will transfer my » inputfile » from centos-8 to rhel-8 On the client we will open a random port, here we will use 9899. I have enabled verbose so you can see more details on the screen

Next to start the transfer, use the below command

If you face any issues you can check the firewall between your server and client. It is possible that the respective port is blocked and you must use firewalld open port

Lastly I hope the steps from the article to open a port and check port status on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Related Posts

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Как открыть порт Ubuntu

Правильная настройка брандмауэра имеет очень важное значение для безопасности вашего сервера или даже домашнего компьютера, подключенного к сети интернет.

На промышленных серверах брандмауэр запрещает подключение к большинству из них, оставляя только необходимые. В этой статье мы рассмотрим как открыть порт iptables и закрыть все остальные. Хотя в большинстве дистрибутивов существуют специальные утилиты для настройки брандмауэра,мы будем использовать iptables, чтобы вы смогли понять процесс на самом низком уровне.

Просмотр правил Iptables

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

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

Как открыть порт iptables с нуля

Если в iptables уже есть какие-либо правила и вы хотите их удалить просто выполните:

Теперь нам нужно добавить правила, которые разрешат обмен данными между любыми портами на локальном интерфейсе lo, это нужно чтобы не вызвать системных ошибок:

Если кратко, то здесь добавляется два правила в цепочки INPUT и OUTPUT, разрешающие отправку и прием данных из интерфейса lo. Еще одно интересное и важное правило, которое многие упускают. Нужно запрещать только новые соединения, а пакеты для уже открытых нужно разрешать. Иначе получится, что мы отправляем серверу запрос (цепочка OUTPUT открыта), соединение открывается, но сервер не может нам ответить, потому что все пакеты отбрасываются в INPUT. Поэтому нужно разрешить все пакеты с состоянием ESTABLISHED и RELATED. Для этого есть модуль state:

Теперь самое интересное, рассмотрим как открыть порт 22 и 80 для протокола TCP:

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

Вывод очень упрощен и понять здесь что-то сложно, например, может показаться что у нас два одинаковых правила, хотя это не так. Чтобы отобразить более подробную информацию используйте:

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linuxЧтобы все это в действительности заработало, осталось поменять политику по умолчанию на DROP:

Все, можете проверять. Все пользователи смогут получить доступ к портам 22 и 80, а к остальным доступа не будет.

Как открыть порт, если уже есть правила

Довольно часто возникает ситуация, когда вам нужно открыть порт Linux, а iptables уже содержит набор правил, запрещающих доступ к портам. Иногда вы добавляете правило, все как нужно, с помощью описанной выше команды, но не замечаете никакого эффекта. Рассмотрим почему так происходит.

Допустим, программа или предыдущий администратор для надежности добавили в конец цепочки правило такого вида:

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linuxТеперь смотрим список правил и проверяем:

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

Выводы

В этой статье мы рассмотрели как открыть порт Ubuntu 16.04 или в любом другом Linux дистрибутиве, а также закрыть ненужные порты. Это повысит безопасность вашей системы. Только на первый взгляд кажется, что с iptables сложно работать. Если разобраться, то все будет достаточно просто. Надеюсь, эта информация была полезной для вас.

Opening a port on Linux

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linux

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Before we learn about opening a port on Linux, let’s understand what network ports are. A port is a communication endpoint. Within an operating system, a port allows the data packets 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 (Ports 0-1023) are referred to as well-known port numbers and are reserved for the most commonly used services include SSH (port 22), HTTP and HTTPS (port 80 and 443), etc. Port numbers above 1024 are referred to as ephemeral ports.

Among ephemeral ports, Port numbers 1024-49151 are called the Registered/User Ports. The rest of the ports, 49152-65535 are called as Dynamic/Private Ports.

In this tutorial, we will show how we can open an ephemeral port on Linux, since the most common services use the well-known ports.

List all open ports

Before opening a port on Linux, let us first check the list of all open ports, and choose an ephemeral port to open from that list.

We can use the netstat command to list all open ports, including those of TCP, UDP, which are the most common protocols for packet transmission in the network layer.

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linuxList Open Ports

Just to ensure that we are getting consistent outputs, let’s verify this using the ss command to list listening sockets with an open port.

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linuxList Listening Sockets

Opening a port on Linux to Allow TCP Connections

Let’s open a closed port and make it listen to TCP Connections, for the sake of this example.

Since port 4000 is not being used in my system, I choose to open port 4000. 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!

Again, just to make sure, let’s ensure that port 4000 is not used, using the netstat or the ss command.

The output must remain blank, thus verifying that it is not currently used, so that we can add the port rules manually to the system iptables firewall.

For Ubuntu Users and ufw firewall based Systems

You can skip the next few steps, and directly test your newly opened port!

For CentOS and firewalld based Systems

For these types of systems, if you have firewalld as your primary firewall, it is recommended that you use the firewall-cmd to update your firewall rules, instead of the old iptables firewall.

You can skip the next few steps, and directly test your newly opened port!

For Other Linux Distributions

So let’s add this new port to our system iptables rules, using the iptables command.

If this command is not yet installed, get it using your package manager.

To update the firewall rules, restart the iptables service.

OR using systemctl if you have it.

Test the newly opened port for TCP Connections

Now that we have successfully opened a new TCP port (Port 4000 in my case), let’s test it out.

This makes netcat listen on port 4000. Leave this session alone for now.

Open another terminal session on the same machine.

Since I’ve opened a TCP port, I’ll use telnet to check for TCP Connectivity. If the command doesn’t exists, again, install it using your package manager.

Format for telnet:

So input your server IP and the port number, which is 4000 in my case, and run this command.

This 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 ).

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linuxCheck Port Using Telnet

As you can see, the output of ls ( while.sh in my case) has also been sent to the client, indicating a successful TCP Connection!

To show you that the port is indeed open, we can use nmap to check this.

How to open port linux. Смотреть фото How to open port linux. Смотреть картинку How to open port linux. Картинка про How to open port linux. Фото How to open port linuxCheck Open Port

Indeed, our port has been opened! We have successfully opened a new port on our Linux system!

NOTE: nmap only lists opened ports which 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 we reboot the system.

Need to update rules after every reboot

The approach presented in this article will only temporarily update the firewall rules until the system shuts down/reboots. So similar steps must be repeated to open the same port again after a restart.

For ufw Firewall

The ufw rules are not reset on reboot, so if you’re a Ubuntu user, you need not worry about this part!

For firewalld

For example, you can open the TCP Port 4000 permanently using the below command:

For iptables

For the iptables firewall, although this inconvenience cannot be avoided, we could minimize the hassle.

We can then retrieve it from the config file after we reboot, using the below command:

Now, the iptables rules are now updated, and our ports are opened again!

Conclusion

In this tutorial, we showed you how you could open a new port on Linux and set it up for incoming connections.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

3 Ways to Open a port in Linux

How to open a port on Linux is a common question when testing a firewall-related problem. Today we will use nc command to open a tcp port manually on Linux and check if this port is working or not.

The following Linux commands can be used to open a port in Linux.

Use nc or ncat to open a port on Redhat/Centos Linux

The best Linux command to open a port is using nc command. Open the terminal and type nc –listen –source-port port number. The port will be opening on our Linux system. Nc command is delivered as part of nmap-ncat rpm in Linux. We can use yum or dnf to install it.

In the below example we open port 1234

]# nc –listen –source-port 1234

Open another terminal of this server and check port status

Next on another terminal, you can check the port status for port 1234
[root@centos-8

Use nc to open a port on Ubuntu Linux

Use Python code to open a Port on Linux

how to check tcp port status in Linux

understanding TCP connection status in netstat command

The LISTEN state in netstat means that the system is listening for incoming connections on that port. The TIME_WAIT state in netstat means that the system is waiting for a certain amount of time before closing the connection. The SYN_SENT status in netstat means that the system is trying to establish a connection with a remote host. The CLOSE_WAIT status in netstat means that the system is waiting for the remote host to close the connection.

What is the nc command in linux?

The nc command in linux is a networking utility that can be used to create and manage TCP and UDP connections. It can be used to send and receive data, as well as to listen for incoming connections.

What are the different options for the nc command?

Источники информации:

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

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