πŸ› οΈ Python Port Scanning Tutorial: Build Your Own Scanner

Arborist Rope

πŸ“Œ Table of Contents

  1. Introduction
  2. Prerequisites
  3. Building a Basic Port Scanner
  4. Enhancing the Scanner with Threading
  5. Advanced Features
  6. Best Practices
  7. Common Use Cases
  8. Troubleshooting
  9. Additional Resources
  10. πŸ”— Friendly Links

🧭 Introduction

Port scanning is a critical technique in network diagnostics and cybersecurity. It helps identify which ports are open on a host and what services may be running. By building your own scanner in Python, you’ll learn more about:

  • TCP connections
  • Networking protocols
  • Threading for performance

πŸ“‹ Prerequisites

Before starting, ensure you have:

  • Python 3.x installed
  • Familiarity with:
    • Basic Python syntax
    • Sockets and the TCP/IP model
  • A terminal or IDE to run your code
  • Authorization to scan your chosen target IP (scanning external networks without permission is illegal)

πŸ”§ Building a Basic Port Scanner

Let’s create a simple scanner that checks for open TCP ports from 1 to 1024.

βœ… Step 1: Import Required Libraries

python import socket
from datetime import datetime

βœ… Step 2: Define the Target

python


target = input("Enter the host to be scanned: ")

βœ… Step 3: Port Scanning Loop

python print(f"Scanning target {target}")
start_time = datetime.now()

for port in range(1, 1025):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.setdefaulttimeout(1)
    result = s.connect_ex((target, port))
    if result == 0:
        print(f"Port {port}: Open")
    s.close()

end_time = datetime.now()
print(f"Scanning completed in: {end_time - start_time}")

πŸ§ͺ Test it locally using 127.0.0.1 or localhost.


⚑ Enhancing the Scanner with Threading

Speed up the scan using Python’s threading module.

βœ… Step 1: Add Threading

python


import threading

βœ… Step 2: Define a Threaded Scan Function

python def scan_port(port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(1)
        result = s.connect_ex((target, port))
        if result == 0:
            print(f"Port {port}: Open")
        s.close()
    except:
        pass

βœ… Step 3: Launch Multiple Threads

python for port in range(1, 1025):
    thread = threading.Thread(target=scan_port, args=(port,))
    thread.start()

🧠 You can also use concurrent.futures.ThreadPoolExecutor for even more control.


πŸš€ Advanced Features

πŸ“‘ 1. Banner Grabbing

pythondef grab_banner(port):
    try:
        s = socket.socket()
        s.settimeout(2)
        s.connect((target, port))
        banner = s.recv(1024)
        print(f"Port {port} Banner: {banner.decode().strip()}")
        s.close()
    except:
        pass

πŸ›Ž 2. Service Detection

python common_ports = {
    21: 'FTP',
    22: 'SSH',
    23: 'Telnet',
    25: 'SMTP',
    53: 'DNS',
    80: 'HTTP',
    110: 'POP3',
    443: 'HTTPS',
}

Use this mapping for user-friendly output.

πŸ’Ύ 3. Save Results to File

python with open('scan_results.txt', 'a') as file:
    file.write(f"Port {port}: Open\n")

βœ… Best Practices

  • βœ… Only scan with permission
  • ⏱ Use reasonable timeouts (0.5–2 seconds)
  • πŸ” Log results to avoid losing data
  • 🧯 Handle exceptions to prevent crashes

πŸ” Common Use Cases

  • πŸ” Security auditing & vulnerability scanning
  • πŸ–₯ System monitoring by administrators
  • πŸŽ“ Educational learning in networking or cybersecurity courses

🧰 Troubleshooting

Issue Possible Solution
Slow scans Use threading or asyncio
Access denied Use elevated privileges or avoid privileged ports
No results Check firewall or port filtering on the target

πŸ“š Additional Resources


πŸ”— Friendly Links

Check out some tools and gear our community loves:

Remaining 0% to read
All articles, information, and images displayed on this site are uploaded by registered users (some news/media content is reprinted from network cooperation media) and are for reference only. The intellectual property rights of any content uploaded or published by users through this site belong to the users or the original copyright owners. If we have infringed your copyright, please contact us and we will rectify it within three working days.