How to open the ports in linux

HowTo: UNIX / Linux Open TCP / UDP Ports

H ow do I open the TCP or UDP ports under UNIX / Linux like operating systems?

A port is an application-specific or process-specific software construct serving as a communications endpoint and it is identified by its number such as TCP port number 80 . It is used by TCP and UDP of the Internet Protocol Suite. A port number is a 16-bit unsigned integer, thus ranging from 0 to 65535.

In the above example Apache process associates its input and output channel file descriptors (fd) with a port number 80 and an IP address 202.54.1.1. This is known as binding. It is used to send and receive web pages via UNIX / Linux operating system’s networking stack (software). In other words communication is done using application ports. When you start the Apache you open port 80 for communication. Common services such as web, mail, pop3 et all use use specifically reserved, well-known port numbers for receiving service requests from client hosts. The well-known ports are defined the Internet Assigned Numbers Authority (IANA). Type the following command to see list well-known of TCP and UDP port numbers:
$ less /etc/services
grep -w 80 /etc/services
Sample outputs:

Privileged Ports

Typically port number less than 1024 are used by well know network servers such as Apache. Under UNIX and Linux like oses root (super user) privileges are required to open privileged ports. Almost all clients uses a high port numbers for short term use. This is also known as an ephemeral port. For example Apache use TCP port 80

The port numbers are divided into three ranges:

  1. Well Known Ports: those from 0 through 1023.
  2. Registered Ports: those from 1024 through 49151
  3. Dynamic and/or Private Ports: those from 49152 through 65535

You can increase local port range by typing the following command (Linux specific example):
# echo 1024 65535 > /proc/sys/net/ipv4/ip_local_port_range
You can also increase or decrease socket timeout (Linux specific example):
# echo 2000 > /proc/sys/net/ipv4/tcp_keepalive_time

Common Well Known Port Numbers

The following are used by UNIX / Windows / Linux / BSD / OS X and all other server operating systems or network devices (see /etc/services file):

  • 21: FTP Server
  • 22: SSH Server (remote login)
  • 25: SMTP (mail server)
  • 53: Domain Name System (Bind 9 server)
  • 80: World Wide Web (HTTPD server)
  • 110: POP3 mail server
  • 143: IMAP mail server
  • 443: HTTP over Transport Layer Security/Secure Sockets Layer (HTTPDS server)
  • 445: microsoft-ds, Server Message Block over TCP

How Do I See Open Ports and Socket Information Under UNIX or Linux?

You can use the netstat command:
# netstat -tulpn
FreeBSD specific example:
# sockstat -l
To list open IPv4 connections use the lsof command:
# lsof -Pnl +M -i4
The ss command is used to dump socket statistics. It allows showing information similar to netstat command. It can display more TCP and state information than other tools
# ss -s
# ss -l
# ss -pl
# ss -o state established ‘( dport = :smtp or sport = :smtp )’

Читайте также:  Локальная сеть через линукс

Examples

Each TCP or UDP port is opened using a UNIX service or daemon such as Apache web server. You can also write a program using C, C++, Perl, Shell or Bash to open any port. You can also use utilities such as nc command .

Apache Server Example (open TCP port 80)

Start the Apache web server under FreeBSD as follows to open TCP port 80:
# /usr/local/etc/rc.d/apache22 forcestart
OR
# /usr/local/etc/rc.d/apache22 start
To displays listening sockets (open ports) under FreeBSD, enter:
# sockstat -l
OR
# netstat -nat | grep LISTEN
You should see port 80 opened under FreeBSD. Under CentOS or Redhat (RHEL) Linux, you can open port 80 using the following commands:
# service httpd start
# chkconfig httpd on
# netstat -tulpn | grep :80

  • 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

Firewall Configuration

All port numbers are encoded in the transport protocol packet header, and they can be read by other components of the network stack such as firewall. Firewall can be used for port forwarding or denying access to open port. For example, block an abusing IP address called 1.2.3.4 using UNIX firewall. In other words, Apache port is open but it may be blocked by UNIX (pf) or Linux (iptables) firewall. You also need to open port at firewall level. In this example, open tcp port 80 using Linux iptables firewall tool:
# /sbin/iptables -A INPUT -m state —state NEW -m tcp -p tcp —dport 80 -j ACCEPT
# service iptables save

Источник

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

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

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

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

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

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

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

Читайте также:  Linux виртуальная память процесса

    Откройте меню и запустите «Терминал». Сделать это также можно, используя стандартную горячую клавишу Ctrl + Alt + T.

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

Ожидайте завершения инсталляции и можете убедиться в активности работы инструмента, просмотрев стандартный список правил, задействовав sudo iptables -L .

Как видите, в дистрибутиве теперь появилась команда iptables , отвечающая за управление одноименной утилитой. Еще раз напомним, что работает этот инструмент от прав суперпользователя, поэтому в строке обязательно должна содержаться приставка sudo , а уже потом остальные значения и аргументы.

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

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

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

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

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

Осталось только обеспечить нормальное взаимодействие указанных выше правил, чтобы сервер смог отправлять обратно пакеты. Для этого нужно запретить новые соединения, а старые — разрешить. Производится это через sudo iptables -A INPUT -m state —state ESTABLISHED,RELATED -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 -L .

Придать ей читабельный вид и вывести все детали можно с помощью дополнительного аргумента, тогда строка будет такой: sudo iptables -nvL .

Поменяйте политику на стандартную через sudo iptables -P INPUT DROP и можете смело приступать к работе между узлами.

В случае когда уже администратор компьютера внес свои правила в инструмент, организовал сброс пакетов при подходе к точке, например, через sudo iptables -A INPUT -j DROP , вам нужно использовать другую команду sudo iptables: -I INPUT -p tcp —dport 1924 -j ACCEPT , где 1924 — номер порта. Она добавляет необходимый порт в начало цепи, и тогда пакеты не сбрасываются.

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

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

Читайте также:  Изменить расположение папки мои документы при установке windows

Помимо этой статьи, на сайте еще 12315 инструкций.
Добавьте сайт Lumpics.ru в закладки (CTRL+D) и мы точно еще пригодимся вам.

Отблагодарите автора, поделитесь статьей в социальных сетях.

Источник

How to Open a Port in Linux?

Here, you will learn how to open a port in Linux, as the users of this OS may need to know this for various purposes and go through ‘iptables’ and the firewalls to find out how can they access a particular port.

Like it? Share it!

Here, you will learn how to open a port in Linux, as the users of this OS may need to know this for various purposes and go through ‘iptables’ and the firewalls to find out how can they access a particular port.

The answer to the question is pretty simple. However, you need to first verify whether the particular port is already open or not. The command for opening a particular port varies, depending on whether you want to open it for TCP or UDP connection.

So, let us first try to understand how to verify if a port is open or not. Here we have taken up the command line approach to perform these tasks, after all, it is the command line approach that makes Linux the wonderful operating system that it is.

How to Verify if a Port is Open?

The command is as follows:

★ netstat -nap | grep : portno
where portno should be replaced with the numerical port number you want to check, if it is open or not. From the output of this command, you can make out if a port is open or not in Linux. All Linux versions do not support this command.

There are few other commands that can be used to check whether a particular port is open or not.

★ netstat -tulp or netstat -tulpn
The output of this command will give you a table with a Local Address column where all the open ports will be mentioned.

★ nmap -sT -O localhost
The output of this command, when issued from the console will give a list of ports that are listening to the TCP connections on the network.

★ lsof -i
This command will give a list of all the open ports.

★ lsof -i | grep portno
Where portno is the number of the port that you wish to check.

★ netcat targetHost portno
If you wish to check the open ports from a remote machine, you can use the nmap or netcat commands.

How to Open a Port in Linux?

This can be done with the following command.:

★ iptables -A INPUT -p tcp -dport portno -j ACCEPT
where portno needs to be replaced with the numerical port number that you want to open.

For opening a UDP port, type the following command:

★ iptables -A INPUT -p udp -sport portno -j ACCEPT
where portno needs to be replaced with the numerical port number that you want to open.

Here, we have assumed that you have logged in as the root user and have the superuser access. This should clear your concepts on how to open a port in Linux.

IT Jobs

Источник

Оцените статью