-1

I'm getting following nmap output from a scan:

PORT     STATE  SERVICE
113/tcp  closed ident
443/tcp  open   https
5060/tcp open   sip

I want to extract only open ports and save them into a variable while my script progress is below:

#!/bin/bash
echo Please enter your IP/domain address for nmap vulnerability scanning:
read IP
echo Your results against $ip will be output in sometime
nmap -sS -oG output.txt $ip
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

2 Answers2

3

Grep them

nmap -sS -oG output.txt $ip | grep open

To store in var

open_ports=$(nmap -sS -oG output.txt $ip | grep open)
open_ports=${open_ports//[^0-9]/ } # remove text

Convert to an array

open_ports_arr=( $open_ports )
Ivan
  • 6,188
  • 1
  • 16
  • 23
2

Here is how you can filter and extract open ports using awk and read the results into a bash array:

#!/usr/bin/env bash

# Read prompt ip address
read \
  -p 'Please enter your IP/domain address for nmap vulnerability scanning: ' \
  -r ip

# Print format info to user
printf 'Your results against %s will be output in sometime.\n' "$ip"

# Read the output of the nmap | awk commands into the ports array
IFS=$'\n' read -r -d '' -a ports < <(
  # Pipe the result of nmap to awk for processing
  nmap -sS -oG output.txt "$ip" |
    awk -F'/' '
      /[[:space:]]+open[[:space:]]+/{
        p[$1]++
      }
      END{
      for (k in p)
        print k
    }'
)

# If the resulting pors array is not empty iterate print format its content
if [ ${#ports[@]} -gt 0 ]; then
  printf 'List of open ports on host IP: %s\n' "$ip"
  for p in "${ports[@]}"; do
    printf '%d\n' "$p"
  done
fi
Léa Gris
  • 17,497
  • 4
  • 32
  • 41