Linux get listen ports

How can I see what ports are open on my machine?

I would like to see what ports are open on my machine, e.g. what ports my machine is listening on. E.g. port 80 if I have installed a web server, and so on. Is there any command for this?

10 Answers 10

If the netstat command is not available, install it with:

sudo apt install net-tools 

-l already filters for listening. grep LISTEN won’t help beyond hiding 2 lines of header information.

-t : tcp, -l : listening socket, -p : show pid and program name, -n : print 127.0.0.1:80 instead of localhost:http . Reference: linux.die.net/man/8/netstat

The expanded command is sudo netstat —tcp —listening —programs —numeric . There’s no need to use grep unless you want to eliminate column headers.

nmap (install)

Nmap («Network Mapper») is a free and open source utility for network exploration or security auditing.

Use nmap 192.168.1.33 for internal PC or nmap external IP address .

More information man nmap .

Zenmap is the official GUI frontend.

Remember that there is a difference between nmap localhost and nmap 192.168.0.3 (or what ever you machine IP is)

I think netstat is a better answer to this. netstat will list what the system is listening on directly, and without using an additional application or doing unnecessary calls over localhost or thought the network.

This is stupid. If you have access to the computer, just use netstat -ln . You’ll instantly see all the open ports.

nmap localhost didn’t find services that were bound only to localhost. For example, I run influxd with bind-address:localhost:8086 . That didn’t show up in sudo nmap localhost , but did show up in sudo netstat -tulpn .

Other good ways to find out what ports are listenting and what your firewall rules are:

To list open ports use the netstat command.

 $ sudo netstat -tulpn | grep LISTEN tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN 5452/dnsmasq tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 1037/cupsd tcp6 0 0 ::1:631 . * LISTEN 1037/cupsd 

In the above example three services are bound to the loopback address.

IPv4 services bound to the loopback address «127.0.0.1» are only available on the local machine. The equivalent loopback address for IPv6 is «::1». The IPv4 address «0.0.0.0» means «any IP address», which would mean that other machines could potentially connect to any of the locally configured network interfaces on the specific port.

Another method is to use the lsof command:

 $ sudo lsof -nP -i | grep LISTEN cupsd 1037 root 9u IPv6 11276 0t0 TCP [::1]:631 (LISTEN) cupsd 1037 root 10u IPv4 11277 0t0 TCP 127.0.0.1:631 (LISTEN) dnsmasq 5452 nobody 5u IPv4 212707 0t0 TCP 127.0.0.1:53 (LISTEN) 

For more details see man netstat or man lsof .

Читайте также:  What is better linux or window

Источник

4 Ways to Find Out What Ports Are Listening in Linux

The state of a port is either open, filtered, closed, or unfiltered. A port is said to be open if an application on the target machine is listening for connections/packets on that port.

In this article, we will explain four ways to check open ports and also will show you how to find which application is listening on what port in Linux.

1. Using Netstat Command

Netstat is a widely used tool for querying information about the Linux networking subsystem. You can use it to print all open ports like this:

The flag -l tells netstat to print all listening sockets, -t shows all TCP connections, -u displays all UDP connections and -p enables printing of application/program name listening on the port.

Check Open Ports Using Netstat Command

To print numeric values rather than service names, add the -n flag.

Show Numeric Values

You can also use grep command to find out which application is listening on a particular port, for example.

$ sudo netstat -lntup | grep "nginx"

Find Port of Running Application

Alternatively, you can specify the port and find the application bound to, as shown.

$ sudo netstat -lntup | grep ":80"

Find Application Using a Port Number

2. Using ss Command

ss command is another useful tool for displaying information about sockets. It’s output looks similar to that of netstat. The following command will show all listening ports for TCP and UDP connections in numeric value.

Find Open Ports Using ss Command

3. Using Nmap Command

Nmap is a powerful and popular network exploration tool and port scanner. To install nmap on your system, use your default package manager as shown.

$ sudo apt install nmap [On Debian/Ubuntu] $ sudo yum install nmap [On CentOS/RHEL] $ sudo dnf install nmap [On Fedora 22+]

To scan all open/listening ports in your Linux system, run the following command (which should take a long time to complete).

$ sudo nmap -n -PN -sT -sU -p- localhost

4. Using lsof Command

The final tool we will cover for querying open ports is lsof command, which is used to list open files in Linux. Since everything is a file in Unix/Linux, an open file may be a stream or a network file.

To list all Internet and network files, use the -i option. Note that this command shows a mix of service names and numeric ports.

List Open Network Files Using lsof Command

To find which application is listening on a particular port, run lsof in this form.

Find Application Using Port

That’s all! In this article, we have explained four ways to check open ports in Linux. We also showed how to check which processes are bound upon particular ports. You can share your thoughts or ask any questions via the feedback form below.

Источник

How to Check for Listening Ports In Linux (Ports in use)

The options used in this command have the following meaning:

-t - Show TCP ports. -u - Show UDP ports. -n - Show numerical addresses instead of resolving hosts. -l - Show only listening ports. -p - Show the PID and name of the listener’s process. This information is shown only if you run the command as root or sudo user.

The output of netstat -tunlp will be list of all the ports, To go through the list pipe it to less

Читайте также:  Unzip с заменой linux

Then identified the ports you are looking for , another way is pipe it to grep if you know know the port you are looking for

netstat -tunlp | egrep :22 tcp 0 0 0.0.0.0[01;31m[K:22[m[K 0.0.0.0:* LISTEN 3827/sshd tcp6 0 0 ::[01;31m[K:22[m[K . * LISTEN 3827/sshd
netstat -tunlp | egrep :8000 tcp 0 0 127.0.0.1[01;31m[K:8000[m[K 0.0.0.0:* LISTEN 30240/python

Another Great Utility is lsof; To get a list of all listening TCP ports

lsof -nP -iTCP -sTCP:LISTEN | head -5 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd 1 root 40u IPv4 28515588 0t0 TCP *:111 (LISTEN) systemd 1 root 43u IPv6 28515590 0t0 TCP *:111 (LISTEN) ZMQbg/1 1594 root 12u IPv4 53188107 0t0 TCP 127.0.0.1:58229 (LISTEN) ZMQbg/1 1594 root 14u IPv4 53188109 0t0 TCP 127.0.0.1:58411 (LISTEN)

To find out who is listening on port 8000

lsof -nP -iTCP:8000 -sTCP:LISTEN COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME python 30240 root 10u IPv4 50135397 0t0 TCP 127.0.0.1:8000 (LISTEN)

Or As explained before, you can also Pipe to egrep or less

lsof -nP -iTCP -sTCP:LISTEN | egrep :8000 python 30240 root 10u IPv4 50135397 0t0 TCP 127.0.0.1[01;31m[K:8000[m[K (LISTEN)

Similarly We can find any listening port such as for mysql on 443

lsof -nP -iTCP:443 -sTCP:LISTEN

For checking MongoDB listening on 27017

lsof -nP -iTCP:27017 -sTCP:LISTEN

For checking ElasticSearch listening on 9200

lsof -nP -iTCP:9200 -sTCP:LISTEN

Источник

Как посмотреть открытые порты в Linux

Сетевые порты — это механизм, с помощью которого операционная система определяет какой именно программе необходимо передать сетевой пакет. Здесь можно привести пример с домом. Например, почтальону необходимо доставить посылку. Он доставляет посылку к дому, это IP адрес компьютера. А дальше в самом доме уже должны разобраться в какую квартиру направить эту посылку. Номер квартиры — это уже порт.

Если порт открыт это означает, что какая либо программа, обычно сервис, использует его для связи с другой программой через интернет или в локальной системе. Чтобы посмотреть какие порты открыты в вашей системе Linux можно использовать множество различных утилит. В этой статье мы рассмотрим самые популярные способы посмотреть открытые порты Linux.

Как посмотреть открытые порты linux

1. netstat

Утилита netstat позволяет увидеть открытые в системе порты, а также открытые на данный момент сетевые соединения. Для отображения максимально подробной информации надо использовать опции:

  • -l или —listening — посмотреть только прослушиваемые порты;
  • -p или —program — показать имя программы и ее PID;
  • -t или —tcp — показать tcp порты;
  • -u или —udp показать udp порты;
  • -n или —numeric показывать ip адреса в числовом виде.

Открытые порты Linux, которые ожидают соединений имеют тип LISTEN, а перед портом отображается IP адрес на котором сервис ожидает подключений. Это может быть определенный IP адрес или */0.0.0.0 что означают любой доступный адрес:

Читайте также:  Pam red hat linux

2. ss

Утилита ss — это современная альтернатива для команды netstat. В отличие от netstat, которая берет информацию из каталога /proc, утилита ss напрямую связывается со специальной подсистемой ядра Linux, поэтому работает быстрее и её данные более точные, если вы хотите выполнить просмотр открытых портов это не имеет большого значения. Опции у неё такие же:

Можно вывести только процессы, работающие на 80-том порту:

3. lsof

Утилита lsof позволяет посмотреть все открытые в системе соединения, в том числе и сетевые, для этого нужно использовать опцию -i, а чтобы отображались именно порты, а не названия сетевых служб следует использовать опцию -P:

Ещё один пример, смотрим какие процессы работают с портом 80:

4. Nmap

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

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

Если это публичный сервер, то результат скорее всего не будет отличатся от локального сканирования, но на домашнем компьютере все немного по другому. Первый вариант — используется роутер и в сеть будут видны только порты роутера, еще одним порогом защиты может стать NAT-сервер провайдера. Технология NAT позволяет нескольким пользователям использовать один внешний IP адрес. И так для просмотра открытых внешних портов сначала узнаем внешний ip адрес, для надежности воспользуемся онлайн сервисом:

Дальше запускаем сканирование:

В результате мы видим, что открыт порт 80 веб-сервера и 22 — порт службы ssh, я их не открывал, эти порты открыты роутером, 80 — для веб-интерфейса, а 22 для может использоваться для обновления прошивки. А еще можно вообще не получить результатов, это будет означать что все порты закрыты, или на сервере установлена система защиты от вторжений IDS. Такая проверка портов может оказаться полезной для того, чтобы понять находится ли ваш компьютер в безопасности и нет ли там лишних открытых портов, доступных всем.

5. Zenmap

Программа Zenmap — это графический интерфейс для nmap. Она не делает ничего нового кроме того, что может делать nmap, просто предоставляет ко всему этому удобный интерфейс. Для её установки выполните:

Запустить программу можно из главного меню или командой:

Затем введите адрес localhost в поле Цель и нажмите кнопку Сканирование:

После завершения сканирования утилита вывела список открытых портов Linux.

Выводы

В этой статье мы рассмотрели инструменты, которые вы можете использовать для того чтобы узнать узнать открытые порты linux. Инструментов не так много как для просмотра информации об оперативной памяти или процессоре, но их вполне хватает. А какими программами пользуетесь вы? Напишите в комментариях!

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

Источник

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