Search code examples
linuxbashawklsof

Linux lsof Need help parsing output


I'm using the following command on a linux system:

lsof -i -n | egrep '\<ssh\>'|awk '{print $8,$9}'

and it produces output like this:

192.168.199.52:ssh->192.168.199.254:17598 (ESTABLISHED)
192.168.199.52:ssh->192.168.199.254:17598 (ESTABLISHED)
192.168.199.52:56448->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:56449->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:56454->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:56458->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:56460->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:56468->69.168.130.22:ssh (ESTABLISHED)
192.168.199.52:ssh->192.168.199.254:56671 (ESTABLISHED)
192.168.199.52:ssh->192.168.199.254:56671 (ESTABLISHED)
192.168.199.52:ssh->192.168.199.254:56672 (ESTABLISHED)

I want to extract just the IP Address from the left side and just the IP Address on the right side of the "->" field. How can I easily extract those two fileds and reassemble them into the following format:

192.168.199.52->192.168.199.254

Solution

  • something like:

    lsof -i -n | awk '$9 ~ /:ssh(-|$)/{ gsub(/:[^-]*/, "", $9); print $9 }'
    

    or perhaps with $8 instead of $9.

    awk command details:

    $9 ~ /:ssh(-|$)/ {           # when ":ssh" is at the end of field 9 or
                                 # followed by an hyphen
        gsub(/:[^-]*/, "", $9);  # remove all the semi-colon followed by characters that
                                 # are not an hyphen from the field 9
        print $9                 # and print it
    }