Filtering netstat command output

Hi All,

I am trying to collect the listen ports info from netstat command in centos 7

From that info i am trying to collect all the foreign address IP for those ports.

I am using below script to do the same.

netstat -an |grep -w  "LISTEN" |grep -v "127.0.0.1" |awk '{print $4}' > /tmp/q1

sed 's/::/ALL/g' /tmp/q1 > /tmp/q2

for i in $(cat /tmp/q2 |awk -F ":" '{print $2}' |sort |uniq);do


abc=$(netstat -an |grep -w  "ESTABLISHED" |grep -v "127.0.0.1" | awk -v chr="$i" '$4 ~ chr'|awk '{print $5}' |awk -F ":" '{print $1}'|sort |uniq)

echo "$abc"


done

I am getting the required output now.

OUPUT :

192.168.20.232
192.168.10.114
192.168.10.175
192.168.10.183
192.168.10.7
192.168.10.93
192.168.20.120
192.168.20.154
192.168.20.170

my questions are

1) Now i want to ignore these ports records and print remaining records.
I tried with by changing the syntax of below variable in the script

abc=$(netstat -an |grep -w  "ESTABLISHED" |grep -v "127.0.0.1" | awk -v  chr="$i" '$4 !~ chr'|awk '{print $5}' |awk -F ":" '{print $1}'|sort  |uniq)

but it's printing duplicate values
Can someone please help me on this issue

This should be close to what you were doing.

netstat -an | awk '
/LISTEN/ && ! /127.0.0.1/ {
   gsub("::", "ALL", $0)
   if ($4 ~ ":") { RECV[$2] }
}
/ESTABLISHED/ && ($2 in RECV) {
   gsub(/:.*/,"",$5)
   if (!($5 in FOUND)) {
      print $5
      FOUND[$5]
   }
}'
1 Like

Can you please explain the script which you wrote.

Thanks

/LISTEN/ && ! /127.0.0.1/
Match lines containing LISTEN and not 127.0.0.1

gsub("::", "ALL", $0)
Replace :: with ALL on entire line

if ($4 ~ ":") { RECV[$2] }
if field #4 contains : store field #2 in RECV array

/ESTABLISHED/ && ($2 in RECV)
Match lines that contain ESTABLISHED and field #2 previously stored in RECV array

gsub(/:.*/,"",$5)
Remove from : to end of field in field #5

if (!($5 in FOUND)) {
   print $5
   FOUND[$5]
}

if field #5 has not already been printed (not in FOUND array) then print it and add field #5 to FOUND array.

1 Like