- The Funk Blog
- The profound rantings of the one like Tom Atkinson… and now art gallery and shop.
- netstat macos Show Listening Ports TCP Sockets with Grep
- Show Server Port and Process ID in Netstat Mac
- About Netstat
- Pipe netstat Into Grep To Remove Junk From The End
- The Little Snitch Command — Who’s phoning home?
- Linux Equivalent
- How to Use the Netstat Command on Mac
- See open ports and those in use
- What to Know
- How to Run Netstat
- Netstat Flags and Options
- Syntax
- Useful Flags
- Netstat Examples
- Accessing Netstat Through Network Utility
- Supplementing Netstat With Lsof
- Lsof Flags and Options
- lsof Examples
- Other Networking Commands
- Как использовать команду Netstat на Mac
- Запуск Netstat
- Флаги и параметры Netstat
- Синтаксис
- Полезные флаги
- Примеры Netstat
- Доступ к Netstat через сетевую утилиту
- Дополнение Netstat с помощью Lsof
- Флаги и параметры Lsof
- lsof Примеры
- Другие сетевые команды
The Funk Blog
The profound rantings of the one like Tom Atkinson… and now art gallery and shop.
netstat macos Show Listening Ports TCP Sockets with Grep
Show only servers — that is ports that are listening waiting for an inbound connection:
netstat -Waltn | grep LISTEN
Show Server Port and Process ID in Netstat Mac
Instead of netstat you need to use LSOF (lists open files and sockets), piped into grep which will only shows lines with LISTEN in them:
sudo lsof -Pnl +M -i | grep LISTEN
Use -i4 for ip4 and -i6 for ip6. -i seems to work for all internet traffic. Handy for tracking down what program is running a server on your machine.
About Netstat
If you’re looking to list open network ports the Mac equivalent to the linux command netstat -Walntpc might be what you’re after. You are not alone, I get about 6,000 unique visitors per year here! Realtime list of all open connections and listening sockets: watch netstat -Walnt (No DNS much faster) watch netstat -Walt (with DNS lookups) The beauty of this command is that it gets you past that over long list of (non-internet surely?) unix sockets and kexts, why Apple put this into netstat I have no idea, perhaps the blame is with Darwin BSD kernel. But it should be more like Linux netstat in my opinion! That’s because I can even see the process names and get continuous updates my adding pc with
Pipe netstat Into Grep To Remove Junk From The End
Listening socket / server processes ports macOS quickly: netstat -Waltn | grep tcp Every internet port fast with no DNS lookups: netstat -Waltn | grep -E «(tcp|udp)(4|6)» Like above but with DNS lookups but takes literally forever up to minutes: netstat -Walt | grep -E «(tcp|udp)(4|6)»
The Little Snitch Command — Who’s phoning home?
How to use LSOF to discover which app or process is listening to which ports: lsof -Pnl +M -i -cmd | grep -E «LISTEN|TCP|UDP» I prefer to use -n to speed up the listing of netstat results by turning off DNS lookups ip to name resolution. The l is used to also show ipv6. To show all internet connections, whether ipv4 or ipv6, tcp or udp, listening, connected or closing — the lot: netstat -Waltn | grep p[46] Show only TCP connections: netstat -anp tcp To see which apps have listening sockets open: sudo lsof -n -P | grep LISTEN Some other good linux ones here: http://www.commandlinefu.com/commands/matching/netstat/bmV0c3RhdA==/sort-by-votes
Linux Equivalent
This one is good for checking ssh tunnels: sudo netstat -tulpn
Posted by tomachi on January 12th, 2016 filed in Mac, Unix
Источник
How to Use the Netstat Command on Mac
See open ports and those in use
What to Know
- To run netstat and see detailed data about your Mac’s network, open a new Terminal window, type netstat, and press Enter.
- Limit netstat’s output with flags and options. To see netstat’s available options, type man netstat at the command prompt.
- Use the lsof command to make up for netstat’s missing or limited functionality, including displaying any files currently open in any apps.
This article explains how to run the netstat Terminal command in macOS so that you can see detailed information about your Mac’s network communications, including the ways your Mac is talking to the outside world, across all ports and all applications.
How to Run Netstat
Learning how to use netstat can help you understand the connections your computer is making and why. The netstat command is available on Macs by default. You don’t need to download or install it.
Go to Finder > Go > Utilities.
Double-click Terminal.
In the new Terminal window, type netstat and press Return (or Enter) to execute the command.
A huge amount of text will begin scrolling on your screen. If you don’t use any of the available flags (see below), netstat reports the active network connections on your Mac. Considering the number of functions a modern network device performs, you can expect the list to be lengthy. A standard report can run over 1,000 lines.
Netstat Flags and Options
Filtering netstat’s output is essential to understanding what’s happening on your Mac’s active ports. Netstat’s built-in flags allow you to set options, limiting the command’s scope.
To see all netstat’s available options, type man netstat at the command prompt to reveal netstat’s man (short for «manual») page. You can also view an online version of netstat’s man page.
Syntax
It’s important to note that netstat on macOS doesn’t work the same way as netstat on Windows and Linux. Using flags or syntax from those implementations of netstat may not result in the expected behavior.
To add flags and options to netstat on macOS, use the following syntax:
netstat [-AabdgiLlmnqrRsSvWx] [-c queue] [-f address_family] [-I interface] [-p protocol] [-w wait]
If the above shorthand looks completely incomprehensible, learn how to read command syntax.
Useful Flags
Here are some of the most commonly used flags:
- -a includes server ports in netstat’s output, which are not included in the default output.
- -g displays information associated with multicast connections.
- -Iinterface provides packet data for the specified interface. All available interfaces can be viewed with the -i flag, but en0 is typically the default outgoing network interface. (Note the lowercase letter.)
- -n suppresses the label of remote addresses with names. This speeds up netstat’s output while eliminating only limited information.
- -pprotocol lists traffic associated with a specific networking protocol. The full list of protocols is available at /etc/protocols, but the most important ones are udp and tcp.
- -r displays the routing table, showing how packets are routed around the network.
- -s shows the network statistics for all protocols, whether or not the protocols are active.
- -v increases verbosity, specifically by adding a column showing the process ID (PID) associated with each open port.
Netstat Examples
Consider these examples:
netstat -apv TCP
This command returns only TCP connections on your Mac, including open ports and active ports. It also uses verbose output, listing the PIDs associated with each connection.
netstat -a | grep -i «listen»
This combination of netstat and grep reveals open ports, which are ports that are listening for a message. The pipe character | sends the output of one command to another command. Here, the output of netstat pipes to grep, letting you search it for the keyword «listen» and find the results.
Accessing Netstat Through Network Utility
You also can access some of netstat’s functionality through the Network Utility app, which is included in macOS versions up to Catalina (it’s not included in Big Sur).
To get to Network Utility, type Network Utility into Spotlight Search to launch the app, then select the Netstat tab to access the graphical interface.
Options within Network Utility are more limited than those available through the command line. Each of the four radio button selections runs a preset netstat command and displays the output.
The netstat commands for each radio button are as follows:
- Display routing table information runs netstat -r.
- Display comprehensive network statistics for each protocol runs netstat -s.
- Display multicast information runs netstat -g.
- Display the state of all current socket connections runs netstat.
Supplementing Netstat With Lsof
The macOS implementation of netstat doesn’t include much of the functionality users expect and need. Although it has its uses, netstat isn’t as useful on macOS as it is on Windows. A different command, lsof, replaces much of the missing functionality.
Lsof displays files currently open in apps. You can also use it to inspect app-associated open ports. Run lsof -i to see the list of applications communicating over the internet. This is typically the goal when using netstat on Windows machines; however, the only meaningful way to accomplish that task on macOS is not with netstat, but with lsof.
Lsof Flags and Options
Displaying every open file or internet connection is typically verbose. That’s why lsof comes with flags for restricting results with specific criteria. The most important ones are below.
For information on more flags and technical explanations of each, check out lsof’s man page or run man lsof at a Terminal prompt.
- -i displays open network connections and the name of the process that is using the connection. Adding a 4, as in -i4, displays only IPv4 connections. Adding a 6 instead (-i6) displays only IPv6 connections.
- The -i flag also can be expanded to specify further details. -iTCP or -iUDP returns only TCP and UDP connections. -iTCP:25 returns only TCP connections on port 25. A range of ports can be specified with a dash, as it -iTCP:25-50.
- Using -i@1.2.3.4 returns only connections to the IPv4 address 1.2.3.4. IPv6 addresses can be specified in the same fashion. The @ precursor can also be used to specify hostnames in the same way, but both remote IP addresses and hostnames cannot be used simultaneously.
- -s typically forces lsof to display file size. But when paired with the -i flag, -s works differently. Instead, it allows the user to specify the protocol and status for the command to return.
- -p restricts lsof to a particular process ID (PID). Multiple PIDs can be set by using commons, such as -p 123,456,789. Process IDs can also be excluded with a ^, as in 123,^456, which would specifically exclude PID 456.
- -P disables the conversion of port numbers to port names, speeding up output.
- -n disables the conversion of network numbers to hostnames. When used with -P above, it can significantly speed up lsof’s output.
- —uuser only returns commands owned by the named user.
lsof Examples
Here are a few ways to use lsof.
lsof -nP -iTCP@lsof.itap:513
This complex-looking command lists the TCP connections with the hostname lsof.itap and the port 513. It also runs lsof without connecting names to IP addresses and ports, making the command run noticeably faster.
lsof -iTCP -sTCP:LISTEN
This command returns every TCP connection with the status LISTEN, revealing the open TCP ports on the Mac. It also lists the processes associated with those open ports. This is a significant upgrade over netstat, which lists PIDs at most.
sudo lsof -i -u^$(whoami)
Other Networking Commands
Other Terminal networking commands that might be of interest in examining your network include arp, ping, and ipconfig.
Источник
Как использовать команду Netstat на Mac
Команда netstat в macOS — это команда терминала, которая отображает подробную информацию о сетевых соединениях вашего компьютера. Сетевые коммуникации включают все способы, которыми ваш Mac общается с внешним миром, через все порты и все приложения. Завоевание netstat может помочь вам понять, какие соединения устанавливает ваш компьютер и почему.
Запуск Netstat
Команда netstat доступна на Mac по умолчанию. Вам не нужно скачивать или устанавливать его.
Чтобы запустить netstat, откройте окно терминала по адресу применение > коммунальные услуги > терминал, Тип NetStat и нажмите вводить выполнить команду.
вакила / Getty Images
На вашем экране начнет прокручиваться огромное количество текста. Если вы не используете ни один из доступных флагов (см. Ниже), NetStat сообщит обо всех активных сетевых подключениях на вашем Mac. Учитывая количество функций, которые выполняет современное сетевое устройство, можно ожидать, что список будет длинным. Стандартный отчет может содержать более 1000 строк.
Фильтрация вывода netstat необходима для понимания того, что происходит на активных портах вашего Mac. Его встроенные флаги позволяют вам устанавливать параметры, ограничивая область действия команды.
Флаги и параметры Netstat
Чтобы увидеть все доступные параметры netstat, введите человек netstat в командной строке, чтобы открыть справочную страницу netstat. Вы также можете просмотреть онлайн-версию справочной страницы netstat.
«Человек» — это сокращение от «руководство».
Синтаксис
Чтобы добавить флаги и параметры в netstat, используйте следующий синтаксис:
netstat [-AabdgiLlmnqrRsSvWx] [-c очередь] [-f семейство_адресов] [-I интерфейс] [-p протокол] [-w ждать]
Netstat в macOS не работает так же, как netstat в Windows и Linux. Использование флагов или синтаксиса из этих реализаций netstat может не привести к ожидаемому поведению.
Если приведенное выше сокращение кажется совершенно непонятным, научитесь читать синтаксис команд.
Полезные флаги
Вот некоторые из наиболее часто используемых флагов:
- -a включает порты сервера в вывод netstat, которые не включаются в вывод по умолчанию.
- -g отображает информацию, связанную с многоадресными соединениями.
- -I interface предоставляет пакетные данные для указанного интерфейса. Все доступные интерфейсы можно просмотреть с помощью -i флаг, но en0 обычно является исходящим сетевым интерфейсом по умолчанию. (Обратите внимание на строчную букву.)
- -n подавляет помеченные имена удаленных адресов. Это значительно ускоряет вывод netstat, жертвуя только ограниченной информацией.
- -p Протокол перечисляет трафик, связанный с определенным сетевым протоколом. Полный список протоколов доступен на / и т.д. / протоколы, но самые важные из них UDP и TCP.
- -r отображает таблицу маршрутизации, показывающую, как пакеты маршрутизируются по сети.
- -s показывает сетевую статистику для всех протоколов, активны они или нет.
- -v увеличивает детализацию, в частности, путем добавления столбца, показывающего идентификатор процесса (PID), связанный с каждым открытым портом.
Примеры Netstat
Рассмотрим эти примеры:
netstat -apv TCP
Эта команда возвращает только TCP-соединения на вашем Mac, включая открытые и активные порты. Он также использует подробный вывод, в котором перечислены идентификаторы PID, связанные с каждым подключением.
netstat -a | grep -i «слушать»
Это сочетание NetStat и GREP показывает открытые порты — порты, которые ожидают сообщения. Характер трубы | отправляет вывод одной команды другой команде. Здесь вывод NetStat трубы к GREP, что позволит вам выполнить поиск по ключевому слову «слушать» и найти результаты.
Доступ к Netstat через сетевую утилиту
Вы также можете получить доступ к некоторым из netstat’s функциональность через приложение Network Utility по адресу Платформа > Библиотека > CoreServices > применение.
Нажмите Netstat Вкладка для доступа к графическому интерфейсу.
Параметры в Network Utility гораздо более ограничены, чем те, которые доступны через командную строку. При выборе каждого из четырех переключателей запускается предварительно установленный netstat. команда и отображает вывод.
Команды netstat для каждой радиокнопки следующие:
- Отображение информации таблицы маршрутизации работает netstat -r.
- Отображение исчерпывающей сетевой статистики для каждого протокола работает netstat -s.
- Отображение информации многоадресной рассылки работает netstat -g.
- Отображение состояния всех текущих подключений сокетов работает NetStat.
Дополнение Netstat с помощью Lsof
Реализация netstat в macOS не включает в себя большую часть функций, которые пользователи ожидают и в которых нуждаются. Хотя netstat имеет свое применение, он не так полезен в macOS, как в Windows. Другая команда, Lsof, заменяет большую часть отсутствующих функций.
Lsof отображает все файлы, открытые в настоящее время в любых приложениях. Вы также можете использовать его для проверки открытых портов, связанных с приложением. Пробег lsof -i, и вы увидите список всех приложений, обменивающихся данными через Интернет. Обычно это цель при использовании netstat на машинах Windows; однако единственный значимый способ выполнить эту задачу в macOS — не с помощью netstat, а с помощью lsof.
Флаги и параметры Lsof
Отображение каждого открытого файла или подключения к Интернету обычно является подробным. Вот почему lsof поставляется с флагами для ограничения результатов по определенным критериям. Самые важные из них — ниже.
Для получения информации о дополнительных флагах и технических пояснениях каждого из них, посетите страницу руководства lsof или запустите человек Исоф в командной строке терминала.
- -i отображает все открытые сетевые подключения и имя процесса, использующего подключение. Добавление 4, Как в -i4, будут отображаться только соединения IPv4. Добавление 6 вместо (-i6) будут отображаться только соединения IPv6.
- Это -i Флаг также может быть расширен, чтобы указать дополнительные сведения. -iTCP или -iUDP вернут только TCP и UDP-соединения. -iTCP: 25 вернет только TCP-соединения на порт 25. Диапазон портов можно указать с помощью дефиса, например -iTCP: 25-50.
- Использование [email protected] вернет только соединения с IPv4-адресом 1.2.3.4. Таким же образом можно указать IPv6-адреса. @Preursor также можно использовать для указания имен хостов таким же образом, но и удаленные IP-адреса, и имена хостов не могут использоваться одновременно.
- -s обычно заставляет lsof отображать размер файла. Но в паре с -i флаг, -s работает иначе. Вместо этого он позволяет пользователю указать протокол и статус для возврата команды.
- -p ограничивает lsof определенным идентификатором процесса (PID). Несколько PID могут быть установлены с помощью общих символов, например -p 123,456,789. Идентификаторы процесса также могут быть исключены с помощью символа ^, например, 123, ^ 456, что специально исключает PID 456.
- -P отключает преобразование номеров портов в имена портов, ускоряя вывод.
- -n отключает преобразование сетевых номеров в имена хостов. При использовании с -P выше, это может значительно ускорить вывод lsof.
- —u user возвращает только команды, принадлежащие указанному пользователю.
lsof Примеры
Вот несколько способов использования lsof.
Эта сложная на вид команда перечисляет все TCP-соединения с именем хоста lsof.itap и порт 513). Он также запускает lsof без привязки имен к IP-адресам и портам, что значительно ускоряет выполнение команды.
lsof -iTCP -sTCP: СЛУШАТЬ
Эта команда возвращает каждое TCP-соединение со статусом СЛУШАТЬ, показывая все открытые порты TCP на вашем Mac. В нем также перечислены процессы, связанные с этими открытыми портами. Это значительное обновление по сравнению с NetStat, в котором перечислены не более PID.
sudo lsof -i -u ^ $ (уами)
Эта команда возвращает все соединения, не принадлежащие текущему авторизованному пользователю.
Каретка (^) означает отрицание. В результатах не будет ничего, что соответствует тексту после каретки. Вы можете получить имя текущего авторизованного пользователя, запустив Whoami внутри Lsof команда, окруженная $ () позволить Lsof получить доступ к его выводу в виде текста. Запуск с помощью sudo позволяет вам видеть задачи, не принадлежащие вам. Выполнение этой команды без sudo возвращает пустой список.
Другие сетевые команды
Другие сетевые команды терминала, которые могут быть интересны при проверке вашей сети, включают arp, ping и ipconfig.
Источник