Mac os find process by port

Find the Process Listening to Port on Mac OS X

Step-by-Step

To find the process that is listening to a port on Mac OS X, we’ll use the lsof command to find the process ID (PID), and the ps command to show the name.

Find the Process ID (PID)

There are two different ways we can use to find the process that is listening to a port on Mac OS X.

Find the Process ID (PID) Using lsof

Using the lsof command we can find the process ID (PID) for a specific port that is in a LISTEN state. In a terminal type the following and replace the “

” with our port number.

This generates output that looks like this:

In the output above the PID (process ID) is the second value, in this example output the process ID (PID) is “63851”. This command will also print out the port number, which is 9999 in the above output example.

Find the Process ID (PID) Using netstat

Using the nestat command we can find the process ID (PID) for a specific port. In a terminal type the following and replace the “

” with our port number.

This generates output that looks like this:

In the output above the PID (process ID) is the ninth value (the fourth value from the end), in this example output the process ID (PID) is “63851”. This command will also print out the port number, which is 9999 in the above output example.

Find the Process Name

We can now use the process status command ps to display the process name for the process ID (PID).

This generates output that looks like this:

In the output above the process name is the last value “the-process.” Now we know the name of the process that is listening to the port. The reason as to why the grep command is listed twice is to avoid displaying the process ID (PID) for the grep command itself.

Other Useful Commands

How to Kill or Stop the Process by PID

You can kill the process by process ID (PID) using the kill command. Replace “

” with the process ID from lsof or netstat.

The lsof Command

The lsof command lists open files. Network sockets count as files, so each open network socket, either listening or actively in use is listed by lsof. In addtion you can run the man lsof command to display all the different options for lsof.

lsof can take a very long time to execute, so I suggest that you use -n (inhibits the conversion of network numbers to host names for network files) and -P (inhibits the conversion of port numbers to port names for network files) to speed it up.

Читайте также:  Линукс фурнитура для стекла

Источник

How do I see which processes have open TCP/IP ports in Mac OS X?

How do I see which processes have open TCP/IP ports in Mac OS X?

6 Answers 6

One alternative is the use of the lsof utility; specifically, lsof -i 4tcp will list all processes with some sort of TCP IPv4 network sockets open. The manpage of lsof will provide you with detailed information on how to use the utility and how to interpret the output.

If you are interested in a specific port, you can use this example:

If you would only like to get the process id, you can run this:

I use the command below when I want to see everything that’s on a specific port for either TCP or UDP. The -n option disables attempting to resolve the IP addresses into domain names, and the -P disables attempting to figure out the name of a particular port. Also, running as root will show you more processes than running as a normal user.

sudo lsof -iTCP:53 -iUDP:53 -n -P

The following code example lists all running TCP servers on your local macOS machine:

LISTEN shows only sockets listening for connections. That is, servers.

The first line shows a server bound to localhost , aka 127.0.0.1 , port 2022 . It will answer to local requests, but not Internet-based requests.

The second line is a server bound to all addresses, ie * , port 3141 . It will answer Internet queries.

To list ports used by clients and servers, use the following:

Источник

How to find and stop a process on a Mac

How can I find the process id and stop the process that is running on port 8080 on a Mac?

On Ubuntu this works:

and I can find the process and run:

ps -aux didn’t seem to work, how can I do this on Mac OS X Lion?

5 Answers 5

For historical reasons, ps ‘s options are a tangled and inconsistent mess. On OS X Lion, any of these should work:

I don’t have an ubuntu box handy to test, but according to the man page, ps -aux isn’t the right way to do it there either:

If you wish to find and kill all processes which conform to a string, you can also use the following on a Mac OSX:

Basically what this will do is that it will find (grep) all the processes currently running on your system matching the , AWK gets the PID, which in the PS command is the second column and the last one takes the arguments from AWK and kills the processes.

Use SUDO, only if the current user does not have some rights to kill a process and if you have SUDO access on your system.

Applications -> Utilities -> Activity Monitor

I believe ps -ef on Mac is nearly equivalent to ps -aux on linux.

To get what PID has port 8080 in use: lsof -P | grep 8080

The fields map out to:

I started up ttcp -rs which listens on port 5001.

and indeed, PID 27999 corresponds to the PID of the ttcp process I launched.

Источник

Найти (и убить) процесс блокировки порта 3000 на Mac

Как мне найти (и уничтожить) процессы, которые прослушивают / используют мои порты tcp? Я на Mac OS X

Иногда, после сбоя или некоторой ошибки, мое приложение rails блокирует порт 3000. Я не могу найти его с помощью ps -ef .

Адрес уже используется — bind (2) (Errno :: EADDRINUSE)

Чтобы завершить некоторые из ответов ниже: После выполнения команд kill может потребоваться удаление файла pid. rm

Читайте также:  Ошибка при запуске games windows live

Ты можешь попробовать netstat

Для macOS El Capitan и новее (или если ваш netstat не поддерживает -p ), используйте lsof

Для Centos 7 использовать

/.bash_profile : findandkill() < port=$(lsof -n -i4TCP:$1 | grep LISTEN | awk '< print $2 >‘) kill -9 $port > alias killport=findandkill так что теперь мне просто нужно набрать killport 8080 текст, и это экономит мне несколько секунд

прежде чем прибегнуть к -9 безопасности.

недостаточно / опасно / неполноценно?

Ничто из вышеперечисленного не помогло мне. Любой другой с моим опытом может попробовать следующее (работал для меня):

затем проверьте статус сообщенного PID:

наконец-то, «смирись с этим»:

Однострочное извлечение PID процесса с использованием порта 3000 и его уничтожение.

Флаг -t удаляет все, кроме PID, из вывода lsof, что упрощает его уничтожение.

Самое простое решение :

Для одного порта:

Убить несколько портов с помощью одной строки:

82500 (идентификатор процесса / PID)

Завершает процессы 82499 и 82500 в одной команде.

Для использования этого в package.json скриптах:

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

npx kill-port 3000

Для более мощного инструмента с поиском:

PS: они используют сторонние пакеты javascript. npx поставляется с Node.js.

Вы можете использовать lsof -i:3000 .

Это «Список открытых файлов». Это дает вам список процессов и какие файлы и порты они используют.

В вашем .bash_profile , создайте ярлык для terminate процесса 3000:

Затем позвоните, $terminate если он заблокирован.

Чтобы принудительно убить такой процесс, используйте следующую команду

Где 3000 — номер порта, на котором запущен процесс

это возвращает идентификатор процесса (PID) и запуска

Замените PID на число, которое вы получите после выполнения первой команды

Это даст вам только pid, протестированный на MacOS.

Выполните в командной строке на OS-X El Captain:

Краткая опция lsof возвращает только PID.

Одним из способов уничтожения процесса в порту является использование библиотеки python: freeport ( https://pypi.python.org/pypi/freeport/0.1.9 ). После установки просто:

Чтобы просмотреть процессы, блокирующие порт:

netstat -vanp tcp | grep 3000

Убить процессы, блокирующие порт:

kill $(lsof -t -i :3000)

Найти открытое соединение

Убить по идентификатору процесса

Эта единственная командная строка проста и работает правильно.

Возможные способы достижения этого:

Вверх

Команда top — это традиционный способ просмотреть использование ресурсов вашей системы и увидеть процессы, которые занимают большинство системных ресурсов. В верхней части отображается список процессов, причем те, которые используют наибольшее количество процессоров, находятся вверху.

п.с.

Команда ps выводит список запущенных процессов. Следующая команда выводит список всех процессов, запущенных в вашей системе:

Вы также можете передать вывод через grep для поиска определенного процесса без использования каких-либо других команд. Следующая команда будет искать процесс Firefox:

Наиболее распространенный способ передачи сигналов программе — команда kill.

Lsof

Список всех открытых файлов и процессов, которые их открыли.

Источник

Mac os find process by port

Try to use the command lsof -i TCP and you get a more complete list and more details (in FreeBSD).

I don’t know what I’m doing at all, but I decided to combine two of the suggestions already posted by johnqsmith, tice, and doctype to come up with:

sudo lsof -nP | grep TCP
and
sudo lsof -nP | grep UDP

The first one gave me the most information that I could somewhat understand. But in either case, they both gave me more information than any of the other suggestions by themselves.

Читайте также:  Пропадают символы windows 10

Using sudo lsof -nP | grep TCP, I got:

mDNSRespo 33 root 11u IPv4 0x0333eca0 0t0 TCP *:* (CLOSED)
netinfod 34 root 7u IPv4 0x02358e8c 0t0 TCP localhost:netinfo-local (LISTEN)
netinfod 34 root 8u IPv4 0x0333f69c 0t0 TCP localhost:netinfo-local->localhost:956 (ESTABLISHED)
netinfod 34 root 10u IPv4 0x023573ec 0t0 TCP localhost:netinfo-local->localhost:1021 (ESTABLISHED)
Directory 45 root 6u IPv4 0x02357740 0t0 TCP localhost:1021->localhost:netinfo-local (ESTABLISHED)
Directory 45 root 11u IPv4 0x02f473ec 0t0 TCP *:* (CLOSED)
Directory 45 root 33u IPv4 0x03340a94 0t0 TCP *:* (CLOSED)
cupsd 367 root 0u IPv4 0x02d587e4 0t0 TCP localhost:ipp (LISTEN)
Safari 2519 admin 25u IPv4 0x02e56d44 0t0 TCP 192.168.2.20:52459->scds77.ord.llnw.net:http (CLOSED)
lookupd 3770 root 6u IPv4 0x02e56348 0t0 TCP localhost:956->localhost:netinfo-local (ESTABLISHED)

And using sudo lsof -i UDP, I got:

mDNSRespo 33 root 7u IPv4 0x01fb1ad0 0t0 UDP *:mdns
mDNSRespo 33 root 8u IPv6 0x01fb1a00 0t0 UDP *:mdns
mDNSRespo 33 root 9u IPv4 0x01fb0340 0t0 UDP 10.0.1.2:52066
mDNSRespo 33 root 12u IPv4 0x01fb0000 0t0 UDP *:mdns
netinfod 34 root 6u IPv4 0x01fb1e10 0t0 UDP localhost:netinfo-local
syslogd 35 root 17u IPv4 0x01fb1d40 0t0 UDP *:*
Directory 45 root 10u IPv4 0x01fb0750 0t0 UDP *:*
Directory 45 root 31u IPv4 0x01fb1860 0t0 UDP *:*
ntpd 193 root 5u IPv4 0x01fb1ba0 0t0 UDP *:ntp
ntpd 193 root 6u IPv4 0x01fb1790 0t0 UDP localhost:ntp
ntpd 193 root 7u IPv4 0x01fb1c70 0t0 UDP 192.168.2.20:ntp
automount 228 root 8u IPv4 0x01fb0b60 0t0 UDP localhost:1023
automount 234 root 8u IPv4 0x01fb12b0 0t0 UDP localhost:1022
cupsd 367 root 6u IPv4 0x01fb1110 0t0 UDP *:ipp

While I don’t know what all that means, what I can do is run these commands randomly and keep a log of the results. So I’d then have something to compare with if I’m concerned that something is not going right.

I think what might work is to log into my «clean admin» account, run both commands, and log what came up. Then I’d have a baseline to work with that isn’t so highly affected by my personal user activities.

Does anyone see any problems with this?

Just kidding. I put the two in a shell script like this: And I made it executable by owner, with owner root. That will remind me to run it with sudo, for more complete results.
For a few records to compare, you could put something like that into a daily or hourly cron job & direct the output into a log file.

Never use setuid on a shell script! Simply by making a softlink from your script to a file named «-i», anyone can root you. Google it for details, but basically adding #!/bin/sh to the beginning of the file will cause the shell to take the name of the script ($0) and create a new command with /bin/sh and then the name of the script. If the filename of the script is -i, then the command becomes «/bin/sh -i», and your attacker just got an interactive root shell.

hi, netstat -an | grep LISTEN should work on osx i tried it on my macbook .. works fine and btw. lsof -i | grep LISTEN returned with nothing netstat sais i have something on .1033 on localhost maybe that lsof bypasses loopback ifaces ?

Источник

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