Search code examples
bashloopsnmap

Use nmap to loop over each ip?


I am looking for a way to clean up nmap's output and loop over each ip running ssh pi@<ip> for each until a match is found. Is this possible? I've been searching around but I can't find any case of someone looping over nmap output?

Closest I got was this:

➜ nmap -n -sP xxx.xxx.x.13/24 | grep "Nmap scan report for"  
Nmap scan report for xxx.xxx.x.1
Nmap scan report for xxx.xxx.x.2
Nmap scan report for xxx.xxx.x.6
Nmap scan report for xxx.xxx.x.7
Nmap scan report for xxx.xxx.x.9
Nmap scan report for xxx.xxx.x.10
Nmap scan report for xxx.xxx.x.11
Nmap scan report for xxx.xxx.x.13
Nmap scan report for xxx.xxx.x.19
Nmap scan report for xxx.xxx.x.22

Solution

  • I am looking for a way to clean up nmap's output

    nmap -n -sP xxx.xxx.x.13/24 | awk '/^Nmap scan report for [[:digit:].]+$/ {print $NF}'
    

    and loop over each ip running ssh pi@ for each until a match is found. Is this possible?

    A while read loop maybe?

    #!/usr/bin/env bash
    
    while read -ru9 ips; do
      ssh "pi@$ips"
    done 9< <(nmap -n -sP xxx.xxx.x.13/24 | 
      awk '/^Nmap scan report for [[:digit:].]+$/ {print $NF}'
    )