Scanning with Netcat
Understanding Netcat (nc): The TCP/IP Swiss Army Knife
Netcat (nc
) is a powerful command-line utility often referred to as the TCP/IP Swiss Army Knife. It is widely used in networking, system administration, and penetration testing due to its flexibility and simplicity.
What Can Netcat Do?
Beyond simple port scanning, Netcat can be used for various tasks:
Establishing communication between two computers (chatting)
Banner grabbing for service identification
Transferring files
Setting up reverse or bind shells for remote access
Debugging network services
Note: Netcat traffic is not encrypted. To enable encryption, consider using ncat
from the Nmap suite.
Netcat as a Port Scanner
Netcat can scan TCP or UDP ports to check their availability. Though slower than Nmap, Netcat may occasionally discover ports Nmap misses.
Basic Syntax:
nc -nv -w 1 -z <target-ip> <port-range>
Option Breakdown:
-n
: Skip DNS resolution-v
: Verbose output-w 1
: Set timeout to 1 second-z
: Scan mode (no data sent)-u
: Use UDP mode (optional; less reliable)
Automating Scans with Bash
To scan multiple hosts efficiently, Bash scripting can be used to automate Netcat commands.
Step 1: Identify Live Hosts
nmap 192.168.1.1/24 -sn -n -oG - | awk '/Up$/{print $2}' > ip-list.txt
Explanation:
-sn
: Ping scan only-n
: Disable DNS resolution-oG -
: Output in grepable format to stdoutawk '/Up$/{print $2}'
: Filters and extracts IP addresses of live hosts> ip-list.txt
: Saves output to a text file
Step 2: Bash One-liner to Scan Port 80
while read ip; do nc -nv -w 1 -z $ip 80; done < ip-list.txt
Automating Scans with Python
A Python script can accomplish the same task with more control and flexibility.
Example: netcat-scan.py
netcat-scan.py
#!/usr/bin/python3
import os
with open('ip-list.txt', 'r') as file:
for line in file:
ip = line.strip()
command = f'nc -nv -w 1 -z {ip} 80'
os.system(command)
Comparing Bash and Python Output
The diff
command can be used to compare the outputs from the Bash and Python scripts:
diff -y bash_output.txt python_output.txt
This is helpful when checking for inconsistencies due to hosts going offline or changes in network conditions.
Netcat Demo Commands
Manually connecting to a web server:
nc -vn 192.168.1.161 80
GET / HTTP/1.0
Checking a custom port:
nc -vn 192.168.1.161 1337
Troubleshooting Common Errors
Permission Issues:
chmod 777 netcat-scan.py
./netcat-scan.py
Helpful History Commands:
history | grep awk
history | grep while
Hands-on Quiz Questions
Use the three scanners on a network you are authorized to test and see what you like/don't like.
Compare the outputs and speeds of the three scanners.
Use the bash script and python script and change it to scan other ports or multiple ports.
Last updated