Home > database >  how to Iterate an Array List inside 2 bash loops
how to Iterate an Array List inside 2 bash loops

Time:10-17

I have 2 arrays in bash. Array number 1 is the vlan subnet without the last octet. Array number 2 is a list of octets i want to ignore, while scanning the subnet with Nmap. lets assume every subnet has 254 pingable ip's (class c subnet) I want the script to scan each subnet, and exclude ip's that ends with 1,2,3,252,253,254 which are Usually routers / firewalls / switches. I manages to run 2 iterations, but failed on the if [[ $host == $host."${ignore[@]" ]] to identify the relevant ip (sunbet ignore string) Would really appreciate your help.

#!/bin/bash

# lets assume each subnet has 254 ips and all ignore ip's like 10.6.114.1 10.6.115.1 and 10.5.120.1
declare -a vlans=(
10.6.114
10.6.115
10.5.120
)

declare -a ignore=(
1
2
3
252
253
254
)

for vlan in "${vlans[@]}"; do

        nmap -sn "$vlan" | grep Nmap | awk "{print $5}" | sed -n '1!p' | sed -e "$d" | sort > /tmp/vlan_ips.txt
        readarray -t hosts < /tmp/vlan_ips.txt

        for host in "${hosts[@]}"; do

                check=$(echo "$host" | cut -d"." -f1-3)

                if [ $host == $check."${ignore[@]}" ]; then
                        echo 'skipping record'
                fi

        done
done

CodePudding user response:

This might work for you:

for vlan in "${vlans[@]}"; do
  
  for ign in "${ignore[@]}"; do
    printf '%s.%s\n' "$vlan" "$ign"
  done >/tmp/ignore

  nmap -n -sn "$vlan.0/24" -oG - 2>/dev/null |
  grep -vwFf /tmp/ignore |
  awk '/Host:/{print $2}' |
  while read -r host; do
    echo "$host"
  done
done
  • Related