Open Ports Scanner using NMAP¶
A minimal Bash script that scans open TCP ports on one or more hosts using nmap. Designed for quick diagnostics, learning, and lightweight network visibility.
Features¶
- Scans multiple hosts from a file
- Supports:
- Top common ports (default)
- All TCP ports (1–65535)
- Outputs only open ports
- Clean, script-friendly output format:
host port - Read-only (does not modify any files)
Verify if NMAP is installed¶
nmap --version
Input File Format¶
The script expects a plain text file containing one host per line.
Example: hosts.txt
127.0.0.1
localhost
1.1.1.1
google.com
# comments and empty lines are ignored
Supported entries:
- IP addresses
- Hostnames
- localhost
- 127.0.0.1
Usage¶
Basic scan (top 1000 common ports)¶
./all-open-ports-nmap.sh hosts.txt
Scan top N ports¶
./all-open-ports-nmap.sh hosts.txt --top 100
Scan all TCP ports (1–65535)¶
./all-open-ports-nmap.sh hosts.txt --all
Output Format¶
Each open port is printed on its own line:
127.0.0.1 3306
1.1.1.1 53
1.1.1.1 80
1.1.1.1 443
If a host has no open ports, nothing is printed for that host.
Output is sent to stdout (terminal). To save results:
./all-open-ports-nmap.sh hosts.txt --all > results.txt
Script: all-open-ports-nmap.sh¶
#!/usr/bin/env bash
set -euo pipefail
# Scan open TCP ports on hosts listed in a file
# Output format: "host port"
MODE="top"
TOPN="1000"
HOSTS_FILE="${1:-}"
if [[ -z "$HOSTS_FILE" || ! -f "$HOSTS_FILE" ]]; then
echo "Usage: $0 <hosts_file> [--top N | --all]" >&2
exit 1
fi
shift || true
while [[ $# -gt 0 ]]; do
case "$1" in
--top) MODE="top"; TOPN="${2:-1000}"; shift 2 ;;
--all) MODE="all"; shift ;;
-h|--help)
echo "Usage: $0 <hosts_file> [--top N | --all]"
exit 0
;;
*) echo "Unknown option: $1" >&2; exit 1 ;;
esac
done
command -v nmap >/dev/null 2>&1 || {
echo "Error: nmap is required (install with: brew install nmap)" >&2
exit 1
}
while IFS= read -r raw || [[ -n "$raw" ]]; do
host="$(echo "$raw" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
[[ -z "$host" || "$host" =~ ^# ]] && continue
if [[ "$MODE" == "all" ]]; then
nmap -p- --open -T4 "$host" 2>/dev/null \
| awk -v h="$host" '/^[0-9]+\/tcp[[:space:]]+open/ {
split($1,a,"/");
print h, a[1]
}'
else
nmap --top-ports "$TOPN" --open -T4 "$host" 2>/dev/null \
| awk -v h="$host" '/^[0-9]+\/tcp[[:space:]]+open/ {
split($1,a,"/");
print h, a[1]
}'
fi
done < "$HOSTS_FILE"