Linux list opened port

How to check opened/closed ports on my computer?

@Justgivemeaname: nmap is a tool to check for open ports on another host. If you can run netstat on a machine, it’s much faster and reliable to use it.

@DavidFoerster: Didn’t know about netstat , so I learned that. It says in the link that it should be used from another host, though. Thanks!

8 Answers 8

There’s a few parameters to netstat that are useful for this :

  • -l or —listening shows only the sockets currently listening for incoming connection.
  • -a or —all shows all sockets currently in use.
  • -t or —tcp shows the tcp sockets.
  • -u or —udp shows the udp sockets.
  • -n or —numeric shows the hosts and ports as numbers, instead of resolving in dns and looking in /etc/services.

You use a mix of these to get what you want. To know which port numbers are currently in use, use one of these:

netstat -atn # For tcp netstat -aun # For udp netstat -atun # For both 

In the output all port mentioned are in use either listening for incoming connection or connected to a peer** all others are closed. TCP and UDP ports are 16 bits wide (they go from 1-65535)

** They can also be connecting/disconnecting from the peer.

If it shows some process its used. Its closed(not used) if there is no output.

Another alternative command line easy to use to find out which process is using a port:

lsof -n -i4TCP:$PORT | grep LISTEN 

I added the next function in my .bash_profile,

and now run «pslisten 5060» to see who is grabing my SIP port.

It’s work with Apple Mac OS X too.

Is the port status «LISTENING» indicated that the port is opened?

Yes. It means that some service is listening to that port on your computer for incoming connection i.e. this port is open for establishing new connections.

Any port that are not shown in the output indicated that it’s closed?

Yes. Remember netstat -a will show all active (listening) and passive (non-listening) connections i.e. the ports that are acting as both server (some services are listening to these ports for connections from a different machine/process) and established (connections are established on these ports regardless of the fact the host/a service can be a server or client)

All TCP and UDP ports belong to a category called sockets and there are a whole lot of those. To view socket info you can check man ss .

Thanks. you wrote that -a means server and established. Does «server» means ports that are being listened at by some services? Does «established» mean ports where there are existing connections regardless of it is a client or server’s port? Then what kinds of ports does -a not show?

Читайте также:  Какую версию linux ставят

I don’t think the -a option means «all active» sockets; it just means «all». netstat shows all active sockets by default, but leaves out the passive sockets (open, listening). By using the -a option both active and passive sockets are shown.

@heemayl The second part of your answer is still not correct. A TCP socket in the «listening» state can never be a connection; it is not connected to anything, it is only listening. Listening TCP sockets are also called passive sockets because of this. If a client attempts to connect to a (listening) socket on a server, a new socket will be created on the server to establish a connection with the client. A socket which is part of an established connection is called an active socket.

Another option is ss. It’s much easier to use.

The below command will only output a list of current listening sockets.

root@server:~# ss -l Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port u_dgr UNCONN 0 0 * 23353 * 23352 u_dgr UNCONN 0 0 * 568 * 362 u_dgr UNCONN 0 0 * 14836 * 14837 u_dgr UNCONN 0 0 * 20446 * 369 u_dgr UNCONN 0 0 * 22877 * 369 u_dgr UNCONN 0 0 * 504 * 347 u_dgr UNCONN 0 0 * 16298 * 369 u_dgr UNCONN 0 0 * 23343 * 369 u_dgr UNCONN 0 0 * 24125 * 369 u_dgr UNCONN 0 0 * 24617 * 369 u_dgr UNCONN 0 0 * 23352 * 23353 u_dgr UNCONN 0 0 * 23334 * 369 u_dgr UNCONN 0 0 * 17113 * 369 u_dgr UNCONN 0 0 * 16957 * 369 u_dgr UNCONN 0 0 * 14793 * 362 u_dgr UNCONN 0 0 * 23345 * 362 u_dgr UNCONN 0 0 * 24070 * 369 udp UNCONN 0 0 *:sunrpc *:* udp UNCONN 0 0 *:981 *:* udp UNCONN 0 0 . sunrpc . * udp UNCONN 0 0 . 981 . * tcp LISTEN 0 128 127.0.0.1:85 *:* tcp LISTEN 0 128 *:ssh *:* tcp LISTEN 0 128 *:3128 *:* tcp LISTEN 0 100 127.0.0.1:smtp *:* tcp LISTEN 0 128 *:8006 *:* tcp LISTEN 0 128 *:sunrpc *:* tcp LISTEN 0 128 . ssh . * tcp LISTEN 0 100 ::1:smtp . * tcp LISTEN 0 128 . sunrpc . * 

Источник

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

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

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

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

1. netstat

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

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

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

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. Инструментов не так много как для просмотра информации об оперативной памяти или процессоре, но их вполне хватает. А какими программами пользуетесь вы? Напишите в комментариях!

Читайте также:  Linux создание раздела parted

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

Источник

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 .

Источник

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