2

I have several remote devices that create reverse ssh connections back to my server, so that I ssh to them and manage them remotely. They connect back to me via a custom port. When I do a netstat -an | grep 127.0.0.0.1: on my server, I get a list of devices that are currently connected. The output looks like this:

tcp        0      0 127.0.0.1:6001          0.0.0.0:*               LISTEN

tcp        0      0 127.0.0.1:6002          0.0.0.0:*               LISTEN

tcp        0      0 127.0.0.1:6003          0.0.0.0:*               LISTEN

Where 600x is the port the device is connected on. My question is this. I want to make a script that i can run on my server that shows which devices are current connected. I want to have config file that the script would read that lists my devices like this:

NORTH:6001

SOUTH:6002

EAST:6003

WEST:6004

and the script would parse the output of the netstat command and the output would look like this:

Active connections: NORTH, SOUTH, EAST

Inactive connections: WEST

I hope this isn't too confusing. Is this something that can be done with grep and awk?

2

There are three steps here

  1. Just extract active port names from netstat

    netstat -an | grep 127.0.0.1: | awk -F "[ :]+" '{print $5}'

the awk specifies group of spaces and colons as separators and picks up the port id only.

  1. Compare these ports from the device list file (say named device_list.txt), by using grep and output of the command in step 1 as pattern

    netstat -an | grep 127.0.0.1: | awk -F "[ :]+" '{print $5}' | grep -f - device_list.txt

This will give an output like this

NORTH:6001
SOUTH:6002
EAST:6003
  1. The inactive connections can be obtained by using a -v in the grep

    netstat -an | grep 127.0.0.1: | awk -F "[ :]+" '{print $5}' | grep -v -f - device_list.txt

The output of this is

WEST:6004

You could then script around the above to print in any format you want

  • 1
    I thought that your code didnt work, but I see that you added an extra .0 in the netstat command. This code works just fine. Exactly what I needed. Thanks! – Randy Adams Mar 8 '17 at 19:54

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.