0

I'd like to print only the IP address and open ports field from a given a gnmap file.

Host: 123.123.123.123 ()  Ports: 80/open/tcp//http?///, 443/open/tcp//https?///, 8083/closed/tcp//us-srv///, 65001/closed/tcp/////        Ignored State: filtered (65531) Seq Index: 262  IP ID Seq: Randomized
Host: 123.123.123.124 ()  Ports: 80/open/tcp//http?///, 443/open/tcp//https?///, 10443/open/tcp//https///, 65001/closed/tcp/////        Ignored State: filtered (65531) Seq Index: 262  IP ID Seq: Randomized
Host: 123.123.123.125 ()  Ports: 80/open/tcp//http?///, 443/open/tcp//https?///, 8083/closed/tcp//us-srv///, 8445/open/tcp//https///, 65001/closed/tcp/////        Ignored State: filtered (65531) Seq Index: 262  IP ID Seq: Randomized
Host: 123.123.123.126 ()  Ports: 1337/open/tcp//https?///, 8083/closed/tcp//us-srv///, 65001/closed/tcp/////        Ignored State: filtered (65531) Seq Index: 262  IP ID Seq: Randomized

Expected output is

123.123.123.123 80/open/tcp//http?///, 443/open/tcp//https?///
123.123.123.124 80/open/tcp//http?///, 443/open/tcp//https?///, 10443/open/tcp//https///
123.123.123.125 80/open/tcp//http?///, 443/open/tcp//https?///

I have already tried a number of different commands, one among which is the below command.

cat targets_osdetection.gnmap | awk '/open/{print $2 " " $5 " "$6 " " $7}'

But it only prints the fields corresponding to the $Number field and since each IP may not have same number of open ports, this command is not so efficient.

Can someone please provide the awk solution for this?

2
  • 8445/open/tcp//https/// was missed from your 3rd output line. Why? Jul 3, 2018 at 9:24
  • Sorry, I didnt notice it. But definitely meant that all open ports to be included in the output.
    – DevD
    Jul 3, 2018 at 9:58

2 Answers 2

0
awk '/\/open\//{
  l=$2
  for (i=3;i<=NF;++i) {
    if ($i~/\/open\//) l=l" "$i;
  };
  print l
 }'

Explanation:

If /open/ matches the line:

  1. Create a variable with the IP ($2)
  2. Loop through fields $3-NF and add the field to the variable if /open/ matches.
  3. Print the variable.
0

Since you have a static file format sed substitution will also do the job:

sed -E 's/(Host:|Ports:|\(\)) +|[^ ]+closed[^ ]+| +Ignored State:.*//g' targets_osdetection.gnmap

The output:

123.123.123.123 80/open/tcp//http?///, 443/open/tcp//https?///,  
123.123.123.124 80/open/tcp//http?///, 443/open/tcp//https?///, 10443/open/tcp//https///, 
123.123.123.125 80/open/tcp//http?///, 443/open/tcp//https?///,  8445/open/tcp//https///, 
123.123.123.126 1337/open/tcp//https?///,  

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.