Enhance Your Network Security with a Python-Based Network Scanner

Enhance Your Network Security with a Python-Based Network Scanner

August 27, 2024

In the world of cybersecurity and network administration, understanding your network’s security posture is crucial. One of the most fundamental tasks is scanning your network to identify active hosts and open ports. While there are several well-known tools for this purpose, such as Nmap, Python offers a powerful alternative for those who want to automate or customize their network scanning process. In this blog post, we’ll introduce a Python-based network scanner script that you can use to enhance your network security. This script is versatile, easy to use, and perfect for quick network audits.

Why Use Python for Network Scanning?

Python is a popular programming language known for its readability and flexibility. It is widely used in cybersecurity for tasks ranging from network scanning to penetration testing and data analysis. Using Python for network scanning offers several advantages:

  • Cross-Platform Compatibility: Python scripts can run on various operating systems, including Windows, Linux, and macOS.
  • Customizability: You can easily modify and extend the script to suit your specific needs.
  • Integration: Python integrates well with other tools and libraries, making it a great choice for complex workflows.

Introducing the Python Network Sweep Script

Our Python script allows you to scan a network range or a single IP address for open ports, with options to specify an output file and port range. It mimics some of the functionalities of tools like Nmap but is lightweight and easily customizable.

Key Features:

  • IP Range and Single IP Scanning: The script supports scanning both single IP addresses and entire ranges specified in CIDR notation.
  • Port and Port Range Scanning: It allows you to specify individual ports or ranges of ports to scan.
  • Optional Output to File: You can choose to save the results to a file or display them directly in the console.
  • Concurrent Scanning: Using Python’s ThreadPoolExecutor, the script can scan multiple IP addresses in parallel, speeding up the process.

Python Script Breakdown:

Here’s the complete Python script:


import socket import ipaddress import argparse from concurrent.futures import ThreadPoolExecutor def show_usage(): usage_text = """ Usage: python3 NetworkSweep.py --ip [--outputfile ] [--ports ] Examples: python3 NetworkSweep.py --ip "192.168.1.0/24" --outputfile "ScanResults.txt" --ports "22,80,443" python3 NetworkSweep.py --ip "192.168.1.100" --outputfile "SingleHostScan.txt" --ports "21-23,80" Description: This script performs a network sweep to identify hosts and open ports within a given IP range or for a single IP address. It mimics some of the functionality of the nmap -A option by scanning specified ports and providing a report of the open ports. Parameters: --ip Specifies the IP or IP range to scan. --outputfile Specifies the file to which the scan results will be saved. (optional) --ports Specifies the ports or range of ports to scan. (optional, default is "21,22,23,80,443,3389") """ print(usage_text) def parse_ports(ports_str): """ Parse the ports string to generate a list of ports. Supports individual ports separated by commas or ranges specified with a dash. """ ports = set() for part in ports_str.split(','): if '-' in part: start, end = map(int, part.split('-')) ports.update(range(start, end + 1)) else: ports.add(int(part)) return sorted(ports) def is_port_open(ip, port): """ Check if a given port is open on a given IP address. """ try: with socket.create_connection((ip, port), timeout=1) as sock: return True except (socket.timeout, ConnectionRefusedError, OSError): return False def scan_ip(ip, ports): """ Scan an IP address for open ports. """ results = [] for port in ports: if is_port_open(ip, port): results.append(f"{ip} has port {port} open") else: results.append(f"{ip} has port {port} closed") return results def expand_ip_range(ip_range): """ Expand an IP range specified in CIDR notation or return a single IP. """ try: ip_network = ipaddress.ip_network(ip_range, strict=False) return [str(ip) for ip in ip_network.hosts()] except ValueError: return [ip_range] def main(): parser = argparse.ArgumentParser(description="Network Sweep Script") parser.add_argument('--ip', required=True, help='Specifies the IP or IP range to scan.') parser.add_argument('--outputfile', help='Specifies the file to which the scan results will be saved.') parser.add_argument('--ports', default="21,22,23,80,443,3389", help='Specifies the ports or range of ports to scan.') args = parser.parse_args() # Parse the ports ports = parse_ports(args.ports) # Expand the IP range ip_list = expand_ip_range(args.ip) # Prepare to scan IPs results = [] with ThreadPoolExecutor(max_workers=10) as executor: futures = {executor.submit(scan_ip, ip, ports): ip for ip in ip_list} for future in futures: results.extend(future.result()) # Output results if args.outputfile: with open(args.outputfile, 'w') as file: for line in results: file.write(line + "\n") else: for line in results: print(line) if __name__ == "__main__": main()
Copied...

How to Use the Script:

  1. Download or Copy the Script: Copy the script code provided above into a file named NetworkSweep.py.
  2. Run the Script from the Command Line:

To scan an IP range and save results to a file:
python3 NetworkSweep.py –ip “192.168.1.0/24” –outputfile “ScanResults.txt” –ports “22,80,443”

To scan a single IP and display the results on the console:
python3 NetworkSweep.py –ip “192.168.1.100”

To specify a custom range of ports:
python3 NetworkSweep.py –ip “192.168.1.0/24” –ports “80-90,443”

Benefits of Using This Script:

  • Simple and Lightweight: The script is easy to use and doesn’t require any external dependencies apart from Python itself.
  • Customizable: You can easily modify the script to add more features or customize its behavior.
  • Educational: If you’re new to network scanning or Python scripting, this script provides a great learning opportunity.

Conclusion:

With this Python script, you can perform network scans quickly and efficiently, whether you’re auditing a large network or checking the security of a single host. It’s a flexible tool that you can easily adapt to meet your needs, and it’s perfect for both beginners and experienced network administrators.

Feel free to download the script, try it out, and modify it as you see fit. Happy scanning!

Call to Action:

Do you have any suggestions for enhancing this script further? Leave a comment below, or reach out to us directly! If you found this guide helpful, please share it with your network and subscribe for more Python scripting tutorials.

Leave a Reply

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

Share:

Facebook
Twitter
LinkedIn

Related tags

no tags found

Send Us A Message

Unlock Your Free Cybersecurity Essentials Guide!

Are you confident your business is protected from cyber threats? Don’t miss out on our exclusive guide:

Cybersecurity Essentials for Business Owners
Learn vital protection strategies and insights tailored for today’s digital challenges.

Simply fill out your details and we’ll send the PDF straight to your inbox. Gain the knowledge to safeguard your business effectively!