Skip to content

Instantly share code, notes, and snippets.

@ubuntupunk
Last active October 1, 2025 06:11
Show Gist options
  • Save ubuntupunk/fb7e845d9a33ed32c087fe88caba10f8 to your computer and use it in GitHub Desktop.
Save ubuntupunk/fb7e845d9a33ed32c087fe88caba10f8 to your computer and use it in GitHub Desktop.
nmap with awk output

nmap -v -sn 192.168.10/25 -oG - | awk '/Up$/{print $2}'

nmap Options Explained

nmap: The network mapper tool, used for scanning hosts and networks.

-v: Enables verbose output, giving more detail during the scan.

-sn: Stands for "ping scan" — it disables port scanning and only checks which hosts are up (i.e., responding to ping or ARP).

192.168.10.0/25: This is a CIDR subnet notation. It scans IPs from 192.168.10.0 to 192.168.10.127 — a total of 128 addresses.

-oG -: Outputs results in grepable format (-oG) and sends it to stdout (-), rather than a file.

nmap -v -sn 192.168.10.0/25 -oG - | awk '/Up$/{print $2}' | while read ip; do echo -n "$ip "; nslookup "$ip" | awk '/name =/{print $4}'; done

Added hostname lookup

while read ip; do ... done: Loops through each IP found to be up.

nslookup "$ip": Resolves the hostname for each IP.

awk '/name =/{print $4}': Extracts the canonical hostname from nslookup output.
@ubuntupunk
Copy link
Author

ubuntupunk commented Aug 25, 2025

bash function

scan_hosts() {
  local subnet="$1"
  if [[ -z "$subnet" ]]; then
    echo "Usage: scan_hosts <subnet>"
    echo "Example: scan_hosts 192.168.10.0/25"
    return 1
  fi

  echo "Scanning subnet: $subnet"
  nmap -v -sn "$subnet" -oG - | awk '/Up$/{print $2}' | while read ip; do
    hostname=$(nslookup "$ip" 2>/dev/null | awk '/name =/{print $4}')
    printf "%-15s %s\n" "$ip" "${hostname:-<no hostname>}"
  done
}

@ubuntupunk
Copy link
Author

Parallelize for Speed

scan_hosts() {
  local subnet="$1"
  if [[ -z "$subnet" ]]; then
    echo "Usage: scan_hosts <subnet>"
    echo "Example: scan_hosts 192.168.10.0/25"
    return 1
  fi

  echo "🔍 Scanning subnet: $subnet"
  nmap -sn "$subnet" -oG - | awk '/Up$/{print $2}' | while read -r ip; do
    # Resolve hostname (fallback to <no hostname> if not found)
    local hostname
    hostname=$(nslookup "$ip" 2>/dev/null | awk -F'= ' '/name =/{print $2}' | sed 's/\.$//')
    printf "%-15s %s\n" "$ip" "${hostname:-<no hostname>}"
  done
}

@ubuntupunk
Copy link
Author

Use in conjunction with:
ip -4 -br a | grep Up

ip: the modern replacement for ifconfig, used to show/manipulate network interfaces.

-4: restricts output to IPv4 addresses only.

-br (short for --brief): gives a concise, tabular output.

a (short for address): shows IP address information for all interfaces.

| grep UP

|: pipes the output of the previous command into the next.

grep UP: filters lines that contain the word UP, which indicates that the interface is active and running.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment