- How to check open ports in Linux using the CLI
- What the hell are a TCP and UDP ports?
- Port numbers
- Check open ports in Linux
- Using netstat to list open ports
- Use ss to list open ports
- Listening ports and applications using lsof command
- nmap command
- The open port doesn’t mean anyone from outside can access those ports
- Conclusion
- 12 ss Command Examples to Monitor Network Connections
- 1. Listing all Connections
- 2. Listing Listening and Non-listening Ports
- 3. Listing Listening Sockets
- 4. List all TCP Connections
- 5. List all Listening TCP Connections
- 6. List all UDP Connections
- 7. List all Listening UDP Connections
- 8. Display PID (Process IDs) of Sockets
- 9. Display Summary Statistics
- 10. Display IPv4 and IPv6 Socket Connections
- 11. Filter Connections by Port Number
- 12. Check Man Pages for ss Command
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Утилита ss в Linux
- Общая информация
- Опции утилиты ss
- Примеры использования
- Мониторинг сетевых подключений
- Просмотр статистики статистики сетевых подключений
- Фильтрация по протоколу
- Фильтрация по состоянию соединения
- Фильтрация по адресу и номеру порта
- Выводы
How to check open ports in Linux using the CLI
I need to list all open ports in Linux cloud server. How do I check open ports in Linux using the CLI? Can you give me the command to check open ports in Linux operating system?
To troubleshoot server problems and to avoid security issue, one needs to find out open TCP and UDP ports. In this tutorial, you will learn the different Linux commands to check open ports in Linux for auditing and securing the server.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | Linux command line |
Est. reading time | 5 minutes |
What the hell are a TCP and UDP ports?
A port is nothing but a 16-bit number between 0 to 65535. For example, TCP port number 22 may be forwarded to the OpenSSH server. Therefore, 22 port number is a way to identify the sshd (OpenSSH server) process.
Port numbers
- The Well Known Ports are those from 0 through 1023.
- The Registered Ports are those from 1024 through 49151.
- The Dynamic and Private Ports are those from 49152 through 65535.
A registered port is a network port assigned by the Internet Assigned Numbers Authority (IANA) and stored in /etc/services file. Use the cat command or grep command/egrep command to view port numbers and service mappings:
Display a list of applications and their ports assigned by IANA
Check open ports in Linux
The procedure to monitor and display open ports in Linux is as follows:
- Open a Linux terminal application
- Use ss command to display all open TCP and UDP ports in Linux.
- Another option is to use the netstat command to list all ports in Linux.
- Apart from ss / netstat one can use the lsof command to list open files and ports on Linux based system.
- Finally, one can use nmap command to check TCP and UDP ports too.
Let us see all commands and examples in details.
Using netstat to list open ports
- 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 ➔
- -t : All TCP ports
- -u : All UDP ports
- -l : Display listening server sockets
- -p : Show the PID and name of the program to which each socket belongs
- -n : Don’t resolve names
- | grep LISTEN : Only display open ports by applying grep command filter.
Use ss to list open ports
The ss command is used to dump socket statistics. It allows showing information similar to netstat. It can display more TCP and state information than other tools. The syntax is:
sudo ss -tulpn
Sample outputs:
Listening ports and applications using lsof command
Let us run the following to check open TCP and UDP ports using the lsof command:
sudo lsof -i -P -n | grep LISTEN
Where,
- -i : Look for listing ports
- -P : Inhibits the conversion of port numbers to port names for network files. Inhibiting the conversion may make lsof run a little faster. It is also useful when port name lookup is not working properly.
- -n : Do not use DNS name
- | grep LISTEN : Again only show ports in LISTEN state using the grep command as filter.
nmap command
In addition, to above commands one can use the nmap command which is an open source tool for network exploration and security auditing. We are going to use nmap to find and list open ports in Linux:
$ sudo nmap -sT -O localhost
$ sudo nmap -sU -O 192.168.2.254 ##[ list open UDP ports ]##
$ sudo nmap -sT -O 127.0.0.1 ##[ list open TCP ports ]##
$ sudo nmap -sTU -O 192.168.2.24
Sample outputs:
The open port doesn’t mean anyone from outside can access those ports
So far, you know how to find and list open TCP and UDP ports on Linux. However, those ports can still be blocked by software, cloud, or hardware firewall. Hence, you need to verify that your corporate firewall is not blocking incoming or outgoing access. For instance on Linux server we list or dump firewall rules using the following syntax:
sudo iptables -S
# IPv6
sudo ip6tables -S
Conclusion
In conclusion, finding out open ports is one of the most fundamental duties of a Linux system administrator for security reasons. Therefore, close down all unwanted ports and configure firewall such as UFW and FirewallD to open or block ports as per your requirements. After reading this tutorial, you should have a good understanding of how to check for open ports in Linux. See IANA’s offical list of TCP, UDP and other ports here for more information.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
12 ss Command Examples to Monitor Network Connections
ss command is a tool that is used for displaying network socket related information on a Linux system. The tool displays more detailed information that the netstat command which is used for displaying active socket connections.
In this guide, we delve in and see how the ss command can be used to display varied socket connection information in Linux.
1. Listing all Connections
The basic ss command without any options simply lists all the connections regardless of the state they are in.
List All Connections in Linux
2. Listing Listening and Non-listening Ports
You can retrieve a list of both listening and non-listening ports using the -a option as shown below.
List All Ports in Linux
3. Listing Listening Sockets
To display listening sockets only, use the -l flag as shown.
List Listening Sockets in Linux
4. List all TCP Connections
To display all TCP connection, use the -t option as shown.
List TCP Connections in Linux
5. List all Listening TCP Connections
To have a view of all the listening TCP socket connection use the -lt combination as shown.
List Listening TCP Connections in Linux
6. List all UDP Connections
To view all the UDP socket connections use the -ua option as shown.
List UDP Socket Connections in Linux
7. List all Listening UDP Connections
To list listening UDP connections use the -lu option.
List Listening UDP Connections in Linux
8. Display PID (Process IDs) of Sockets
To display the Process IDs related to socket connections, use the -p flag as shown.
Find Process ID of Sockets in Linux
9. Display Summary Statistics
To list the summary statistics, use the -s option.
Find Summary Statistics
10. Display IPv4 and IPv6 Socket Connections
If you are curious about the IPv4 socket connections use the -4 option.
Find IPv4 Socket Connections in Linux
To display IPv6 connections, use the -6 option.
Find IPv6 Socket Connections in Linux
11. Filter Connections by Port Number
ss command also lets you filter socket port number or address number. For example, to display all socket connections with a destination or source port of ssh run the command.
Filter Connections by Port Number
Alternatively, you can run the command.
Filter Connections by Service
12. Check Man Pages for ss Command
To get more insights into the ss command usage, check the man pages using the command.
Find ss Command Usage and Options
Those are some of the commonly used options that are used with ss command. The command is considered more superior to netstat command and provide detailed information about network connections.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Утилита ss в Linux
Иногда бывает необходимо посмотреть какие сетевые подключения Linux открыты, какие IP адреса используются или какие порты прослушиваются. Раньше для таких целей использовалась утилита netstat. Её, без сомнения, знают все системные администраторы и специалисты по безопасности. Но она больше не поставляется по умолчанию в новых дистрибутивах. Вместо неё используется новая утилита под названием ss.
Netstat сканирует директорию /proc для получения необходимой информации, но в новых версиях ядра была реализована специальная подсистема для мониторинга сети в Linux. Её и использует ss, с помощью этой утилиты вы можете получить больше информации о сетевых подключениях и работает она гораздо быстрее.
Как вы уже поняли в этой статье мы рассмотрим мониторинг сетевых подключений в Linux с помощью утилиты из пакета iproute — ss linux. Начнем, как обычно, с синтаксиса и основных опций.
Общая информация
Как уже было сказано работает утилита ss в Linux на основе подсистемы ядра. Синтаксис очень простой — сама команда и ее опции:
$ ss опции [ фильтр_состояния] [фильтр_адреса]
Для удобства вывод команды ss можно фильтровать с помощью grep:
$ ss опции | grep шаблон
Опции указывает различные параметры отображения и фильтрации информации. Фильтры по состоянию и адресу очень интересная вещь, они позволяют выполнять мониторинг сетевых подключений в Linux, только тех что нужно. Например, только открытых, закрытых или находящихся на этапе подключения. Подробнее мы рассмотрим это в конце статьи.
Опции утилиты ss
Для сетевых подключений в Linux с помощью утилиты ss можно использовать такие опции:
- -V — Version показать версию утилиты.
- -n — Numeric не определять имена служб.
- -r — Resolve определять сетевые имена адресов с помощью DNS.
- -a — All отобразить все сокеты (открытые соединения).
- -l — Listening показать только прослушиваемые сокеты.
- -o — Options показать информацию таймера.
- -e — Extended выводить расширенную информацию о сокете.
- -p — Processes, показать процессы, использующие сокет.
- -i — Internal, посмотреть внутреннюю информацию TCP.
- -s — Summary, статистика использования сокета.
- -D — экспортировать текущее состояние TCP сокетов в файл.
- -F — работать с информацией, взятой из файла.
Кроме того, можно вывести сокеты только нужного протокола:
- -4, —ipv4 — только сокеты протокола IP версии 4.
- -6 —ipv6 — только сокеты протокола IP версии 6.
- -0, —packet — только PACKET сокеты.
- -t, —tcp — TCP сокеты.
- -u, —udp — UDP сокеты.
- -d, —dhcp — DHCP сокеты.
- -r, —raw — RAW сокеты.
- -x, —unix — UNIX сокеты.
Для фильтрации протоколов можно использовать не только эти опции, но и универсальную опцию -f, передав ей в параметре название протокола. Здесь собраны самые основные опции, если вам нужно больше информации — смотрите справку команды.
Примеры использования
А теперь давайте рассмотрим примеры использования утилиты ss Linux. Возможно, из описания опций вы мало что поняли, но с примерами все встанет на свои места.
Мониторинг сетевых подключений
Сначала смотрим все сетевые подключения:
Посмотрим только TCP соединения:
Теперь только Unix:
Для отображения UDP сокетов используйте опцию u. По умолчанию будут показаны только подключенные соединения. Если хотите получить все, нужно использовать опцию a. Поскольку UDP, это протокол без постоянного соединения, то без опции -a мы ничего не увидим:
По умолчанию утилита не пытается определять имена хостов через dns, но можно ее попросить делать это опцией -r:
Обратная опция -n, не будет выполняться не только dns резолвинг, но и определение протоколов портов, зато мониторинг сети в Linux работать будет быстрее:
Теперь просмотрим только прослушиваемые tcp сокеты.
Здесь мы видим только имена служб, это не всегда удобно, указав опцию n, мы получим номера портов. Так же само можно посмотреть прослушиваемые udp сокеты:
Также мы можем попытаться узнать название и PID процесса, использующего сокет:
Просмотр статистики статистики сетевых подключений
Для просмотра статистики по использованию сетевых подключений наберите:
С помощью опции -о можно посмотреть информацию о таймере и состоянии подключения.
Фильтрация по протоколу
Мы можем отображать только нужный нам протокол. Например только ipv4:
sudo ss -tl -f inet4
Так же само можно отобразить только соединения ipv6:
Фильтрация по состоянию соединения
В синтаксисе команды мы описали два дополнительных параметра. Фильтрация состояния и фильтрация по адресу. Рассмотрим теперь как ими пользоваться. Сокет TCP может находиться в одном из нескольких состояний. Например, так утилита ss linux выведет только подключенные сокеты.
ss -t4 state established
Или сокеты в состоянии ожидания:
sudo ss -t4 state time-wait
В параметр state можно передать одно из следующих значений:
- established
- syn-sent
- syn-recv
- fin-wait-1
- fin-wait-2
- time-wait
- closed
- close-wait
- last-ack
- closing
- all — все состояния
- connected — все кроме прослушиваемых и закрытых
- synchronized — все кроме syn-sent
- bucket — time-wait и syn-recv
- big — все кроме bucket
Не все состояния подключений можно увидеть просто выполнив команду. Например, syn-sent и syn-recv вряд ли получиться словить, потому что соединения находятся в этом состоянии очень короткое время. Для их отображения удобно использовать команду watch:
watch -n 1 «ss -t4 state syn-sent»
После запуска команды откройте любой сайт в браузере. Вы увидите как появится одно или несколько соединений на несколько секунд.
Фильтрация по адресу и номеру порта
Кроме фильтрации по состоянию, tcp сокеты можно фильтровать по адресам или портам соединений.
Например, отберем все сетевые подключения linux с портом источником или приемником ssh, то есть все входящие и исходящие соединения ssh:
ss -at ‘( dport = :ssh or sport = :ssh )’
Или сокеты с портом назначения 80 или 443:
ss -nt ‘( dst :443 or dst :80 )’
Такой синтаксис тоже будет работать:
ss -nt dst :443 or dst :80
Еще несколько примеров фильтрации:
Фильтрация по адресу:
ss -nt dst 74.125.236.178
Фильтрация по адресу и подсети:
ss -nt dst 74.125.236.178/16
И по адресу и порту:
ss -nt dst 74.125.236.178:80
Если вы хотите фильтровать сетевые соединения по порту, перед портом ставьте двоеточие:
ss -nt dport = :80
Можно использовать такие операторы сравнения:
- = или ge — больше или ровно порту.
- == или eq — точное соответствие.
- != или ne — не равно.
- или lt — больше.
Выводы
Вот и всё. Основную информацию о том, как выполнять мониторинг сети в Linux с помощью утилиты ss рассмотрели. Если вам нужно больше информации и примеров смотрите документацию по утилитам набора iproute.
Источник