Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse netstat command in order to get process name and PID from it?

I'm trying to determine what application is using certain port and get netstat -tlnp | grep <port> for Linux.

This command return the following output:

(Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.)   tcp  0  0 0.0.0.0:<port>  0.0.0.0:*  LISTEN  3591/java 

I need to get in result only name of the process and PID, i.e java 3591.

What is best way to do it?

Thank you.

like image 760
yart Avatar asked Nov 22 '10 16:11

yart


People also ask

How do I find my netstat PID?

Using Netstat command: Open a CMD prompt. Type in the command: netstat -ano -p tcp. You'll get an output similar to this one. Look-out for the TCP port in the Local Address list and note the corresponding PID number.

How do I find PID of all processes?

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column. Click on any column name to sort.

What is PID in netstat?

The State column specifies the connection's state when the Netstat command executed. The PID column shows the process identifier (PID) associated with the TCP connection. The PID is the information you're. after, but few people can identify a process by its PID.


2 Answers

Try

ps -p $(lsof -ti tcp:80) o comm=,pid= 

or

netstat -tlnp | awk '/:80 */ {split($NF,a,"/"); print a[2],a[1]}' 
like image 66
Dennis Williamson Avatar answered Sep 26 '22 06:09

Dennis Williamson


(Detracting slightly from your original question), to find out which process listens to a certain port number, I usually use the lsof command. For example:

lsof -i tcp:80 

To show only the process name and PID, parse the output using:

lsof | tail -n +2 | awk '{print $1 " " $2}' 

The tail command skips the output header while awk prints out the required columns.

Why lsof

Trying to grep the output of netstat can be messy as you'll need to make sure you're matching against the correct column. A robust solution can be rather long winded and difficult (for me anyway) to produce on-demand.

lsof saves you the trouble of matching the right ports, and has lots of other uses too, e.g. the inverse of what we're doing now (find out which ports are being used by a process), or determining which process is using a file / mount point (or the inverse). See lsof manpage for more examples.

like image 29
Shawn Chin Avatar answered Sep 25 '22 06:09

Shawn Chin