0

I want to print 2 fields together, all open ports and the application using it. This is my command but it only prints the port numbers and still missing the program field:

netstat -lnt -u -p | awk '{print $4}' | sed 's/.*://' | sort -n | uniq

How can I modify this to print also the Program name as in "PID/Program name" will return "java"

A sample of "netstat -lnt -u -p" looks like this:

tcp , 0 , 0 , 10.194.194.21:36195 , 0.0.0.0:* , LISTEN , 2969/java

And I want to see only the port number and the program name:

 36195 java
  • @AFSHIN every time you edit last 2 fields disappear from the command output. please be careful – Spring Aug 17 '17 at 11:13
  • No, I'm just formatting it, nothing more! nothing going disappear there. – αғsнιη Aug 17 '17 at 18:32
1

Shortened solution:

netstat -lpunt | awk -F' +|:+|/' '$5{print $5,$10}' | sort -n
  • -F' +|:+|/' - field separator (space(s), colon(s) or slash)

  • $5 - port number

  • $10 - program name

  • thanks it works well, could you explain a bit for future reference? – Spring Aug 17 '17 at 10:14
  • @Spring, the main trick here is in field separator, which allows to access the needed fields by its numbers/positions. We can visually determine which fields should be printed – RomanPerekhrest Aug 17 '17 at 10:17
  • tnx and how did you calculate the number 10? program name is the 7th field – Spring Aug 17 '17 at 13:44
  • @Spring, again, compound field separator will separate the filed containing a potential delimiter into several fields, e.g. 10.194.194.21:36195 will be divided into 2 fields 10.194.194.21 and 36195 – RomanPerekhrest Aug 17 '17 at 14:26
  • ok in this case using double "$5" is not really necessary right? I see {print $5,$10} also works – Spring Aug 17 '17 at 14:46
2

You need to print out the 6th field as well as 4th

This should return what you expected to have. (as I don't know the command result and surely there will be a more efficient way.)

netstat -lnt -u -p | awk '{print $4,$6}' | sed 's/.*://' | sort -n | uniq

Here is the way you could get the only port and programName (no extra sed Is needed and sort command can uniqe with its -u option):

netstat -lnt -u -p | awk -F"[,:/]" '{print $5,$NF}'| sort -un
36195  java
  • @tnx it almost worked but I dont wanna see the pid either, now it looks like this: 2014 2969/java – Spring Aug 17 '17 at 9:56
  • I updated the question – Spring Aug 17 '17 at 10:04
  • could you print the full command I couldnt make this work – Spring Aug 17 '17 at 10:09
  • hmm that prints nothing for me..but RomanPerekhrest answer worked well. Thanks for your time – Spring Aug 17 '17 at 10:12
  • thanks, that's maybe because the output is different that you posted in your question, – αғsнιη Aug 17 '17 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.