0

I need to get all running ports from the server, like the unix command 'netstat -an | grep tcp46'

OUTPUT:

tcp46        0       0  *.8009                 *.*                    LISTEN
tcp46        0       0  *.8080                 *.*                    LISTEN

Then I need to iterate the ports and form a command like below.

curl http://serverhost.com:${iterative ports}/app/version

eg.

curl http://serverhost.com:8080/app/version

Can anyone please help me with the shell script or any easy commands available?

Charles
  • 50,943
  • 13
  • 104
  • 142
Ezhilan Mahalingam
  • 2,838
  • 3
  • 16
  • 16

2 Answers2

0

My netstat -an output looks different from yours, so I'm going in blind here:

for i in netstat -an | grep tcp46 | cut -d' ' -f18 | sed 's/*.//g'; do echo curl http://serverhost.com:$i/app/version; done

That is a one liner that should work, but it assumes the output is the same as you said, if the number of spaces change then it won't work correctly. Just remove the echo if you want to run the command directly.

GriffinG
  • 662
  • 4
  • 13
0

You can use regular expressions (REGEX) in sed to get to the output you need from the grep input stream. Then in a bash for loop, execute your curl command for every port you find. Note: the following doesn't check for duplicate ports.

for port in $(netstat -an | grep tcp46 | sed 's/[a-zA-Z]\{1,3\}[ 0-9.]*:\{1,3\}//g' | sed 's/ \+.*//g');
do echo "curl http://serverhost.com:$port/app/version" >> commandFile.txt;
done

I invoke sed twice: once to remove the first portion of the string and a second time to remove the trailing portion.

The output of this script is sent to commandFile.txt in your current directory.

If you would rather run each curl command rather than send to a file, simply remove the echo as follows:

for port in $(netstat -an | grep tcp46 | sed 's/[a-zA-Z]\{1,3\}[ 0-9.]*:\{1,3\}//g' | sed 's/ \+.*//g');
do curl http://serverhost.com:$port/app/version;
done
bhass1
  • 338
  • 2
  • 7