Network administrators and security experts often need to scan ports to identify open or closed services and evaluate the security of their networks. While there are robust tools like nmap for this purpose, sometimes you might need to create a custom solution that fits your specific requirements. In this article, we will be discussing how to create a Bash script for scanning a range of ports.
Basics of Port Scanning
Port scanning is the act of systematically checking a system for open ports. A port in this context is a logical construct that identifies a specific process or a type of network service. Port numbers range from 0 to 65535, with the first 1024 known as “well-known ports” allocated to common protocols such as HTTP (port 80) and FTP (port 21).
Scanning ports allow us to identify which services are running and listening for connections, and this can be particularly useful for detecting potential security vulnerabilities.
Bash Script for Port Scanning
Bash (Bourne Again SHell) is a powerful shell that can be used to create scripts for automating tasks in Linux environments. Our script will take two arguments – the IP address to be scanned and the range of ports to be scanned.
Here’s a simple Bash script that scans a range of ports:
How the Script Works
- First Line (#!/bin/bash): This is known as a shebang. It tells the system that this script should be executed using the Bash shell.
- Lines 3-5: The script accepts three arguments. $1 is the IP address, $2 is the start port number, and $3 is the end port number.
- Lines 7-12: This defines a function portscan which scans each port in the given range. It tries to redirect echo output to the specific port at the IP address. If it successfully writes to the port (meaning the port is open), it outputs the port number followed by “open”.
Using the Script
To use the script, you need to give it executable permissions and run it with an IP address and a range of ports to scan.
- Save the script to a file, e.g., portscan.sh
- Make the script executable: chmod +x portscan.sh
- Run the script with an IP address and a range of ports: ./portscan.sh 192.168.1.1 20 80
- This will scan ports 20 through 80 on the IP address 192.168.1.1.
While this script works for a basic port scan, it lacks many features found in more advanced tools like nmap, such as service detection, OS detection, and more advanced port scanning methods. However, it provides a starting point for understanding how port scanning works and how it can be performed using a simple Bash script.
Also, remember to use tools like these responsibly. Port scanning can be seen as a hostile act if performed without permission and could potentially be against the law depending on your jurisdiction. Always ensure you have the necessary permissions before performing a port scan.