Monday, January 3, 2022

Script to grep ip and port number from netstat

Below script is to parse output from netstat -tulnp or ipvsadm -Ln. 

#!/bin/bash

input=$1

vipNportRe="TCP ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{2,3}).*$"

ipNportRe=".*-> ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{2,3}).*$"

netstatIpNportRe="^tcp .* 0 ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{2,3}).*$"

while read line

do

  if [[ $line =~ $ipNportRe ]]; then

    echo "${BASH_REMATCH[1]}"

  elif [[ $line =~ $netstatIpNportRe ]]; then

    echo "${BASH_REMATCH[1]}"

  fi

done < $input


# Get the lines in a.txt but not in b.txt

grep -F -x -v -f b.txt a.txt

No comments:

Post a Comment