Search code examples
awkcommand-linetext-processingnetstat

How do I get a specific output of whether a port is Listening or not on AIX?


Let's say I'm looking at for example port 22. So I use

netstat -an | grep 22

what can I do to make it so that the output of the command is just the column that says "LISTEN", "ESTABLISHED", etc.

I need a command or short script that takes in the port as input and has an output like the one below.

Expected output:

LISTEN

I tried doing something like

netstat -an | grep .22 | awk '{print $7}' 

the problem with this one is that, I also seem to get some other ports like 2279 and 1022. I don't know how to fix this for a netstat output, and I can't use length-based filtering because I might need to input a 3 or 4 digit port too.

I only want the output for a specific port, in this example, 22.


Solution

  • With your shown samples, please try following code. Simply sending output of netstat command to awk code as an input, then checking if 4th field is ending with :22(to check port 22) then print its last column which is its status.

    netstat -an | awk '$4~/:22$/{print $NF}'