netcat (NC) listen for open ports

The nc (or netcat) utility is used for just about anything under the sun involving TCP or UDP. It can open TCP connections, send UDP packets, listen on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6. Unlike telnet(1), nc scripts nicely, and separates error messages onto standard error instead of sending them to standard output, as telnet(1) does with some.

Example to listen for 443
nc -z 10.0.1.1 443

This is what a successful result will look like
Connection to 10.0.1.1 port 80 [tcp/http] succeeded!

What follows is a macos bash script that prompts the user for a comma delimited list of hostnames in terminal, if there is more than one and processes the following netcat terminal command(s) to derive open port information for each hostname and subsequent IP address on an array of hardcoded ports.

#!/bin/bash
# Prompt user for comma-delimited hostnames
read -p "Enter comma-delimited hostnames: " input
IFS=',' read -ra HOSTNAMES <<< "$input"
# Define the array of ports
PORTS=(443 8443 2197 139 3306 80 8088)
# Get the current timestamp
timestamp=$(date +"%Y%m%d%H%M%S")
# Set the output file path
output_file="/Users/Shared/${timestamp}_netcat.csv"
# Add CSV headers
echo "Hostname,IP,Port,Status" > "$output_file"
# Function to check ports using netcat
check_ports() {
for port in "${PORTS[@]}"; do
# Use netcat to check the port
nc -z -G 2 "$1" "$port" 2>&1
# Capture the result, success or failure
if [ $? -eq 0 ]; then
echo "$2,$1,$port,Open" >> "$output_file"
else
echo "$2,$1,$port,Closed" >> "$output_file"
fi
done
}
# Iterate over the hostnames
for hostname in "${HOSTNAMES[@]}"; do
# Get the IP address from nslookup
ip=$(nslookup "$hostname" | awk '/^Address: / { print $2 }')
# Check if the IP address was found
if [ -n "$ip" ]; then
# Check the ports for the IP address
check_ports "$ip" "$hostname"
else
# Log an error if the IP wasn't found
echo "$hostname,ERROR,ERROR,IP not found" >> "$output_file"
fi
done
echo "Netcat checks complete. Results saved to $output_file"

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *