Automated LAN Scanning with Nmap and Python – Exporting Results to JSON

Light - July 3, 2025, 11:29 a.m.

🔹 Introduction

Network administrators and cybersecurity learners often need tools to scan local networks, identify connected devices, detect operating systems, and analyze open ports.
In this tutorial, we will combine Python with Nmap to scan a local network (/24 range) and export the results as a JSON file.

🔹 Tools Required

  1. Install Nmap (on Ubuntu):

sudo apt update
sudo apt install nmap

Install Python bindings for Nmap:

pip install python-nmap

Note: If running with sudo, make sure python-nmap is installed for root:

sudo pip3 install python-nmap

🔹 Python Script for LAN Scanning

The following Python script:

Scan.py: 

import nmap
import json

def scan_network(network_range):
    scanner = nmap.PortScanner()

    print(f"[+] Scanning: {network_range}")
    scanner.scan(hosts=network_range, arguments='-O -T4')

    results = []

    for host in scanner.all_hosts():
        host_info = {
            "ip": host,
            "hostname": scanner[host].hostname(),
            "state": scanner[host].state(),
            "os": [],
            "ports": []
        }

        # OS detection
        if 'osmatch' in scanner[host]:
            for os in scanner[host]['osmatch']:
                host_info["os"].append({
                    "name": os["name"],
                    "accuracy": os["accuracy"]
                })

        # Port info
        if 'tcp' in scanner[host]:
            for port in scanner[host]['tcp']:
                port_data = scanner[host]['tcp'][port]
                host_info["ports"].append({
                    "port": port,
                    "state": port_data["state"],
                    "name": port_data.get("name"),
                    "product": port_data.get("product"),
                    "version": port_data.get("version")
                })

        results.append(host_info)

    return results


if __name__ == "__main__":
    network = "172.16.20.0/24"  # Đổi thành mạng LAN của bạn
    output_file = "nmap_results.json"

    scan_data = scan_network(network)

    with open(output_file, "w") as f:
        json.dump(scan_data, f, indent=4)

    print(f"[+] Scan completed. Results saved to: {output_file}")

Result: 

Json Example: 

💡 Tips to Speed Up the Scan

Optimization Benefit
Use -sn first Quickly find live devices
Use -T4 Increase scanning speed
Avoid -O for quick scans OS detection is slow
Scan in chunks Split /24 into /28 or smaller ranges

⚠️ Legal & Ethical Notice

This script is provided strictly for educational purposes.

Do NOT scan any network that you do not own or have explicit permission to test. Unauthorized scanning is illegal and may result in penalties or criminal charges.

Read Similars

How to Fingerprint a Device in Your Local Network Using Python

Learn how to fingerprint LAN devices using Python, Scapy, and Impacket. Collect OS info, open ports, HTTP server data, and SMB banners with a single script.

5 min read

How to Scan Local Network for Active Devices Using Python and TCP SYN

Learn how to write a Python script to scan local networks using TCP SYN packets, detect live hosts, and discover connected devices with IPs and hostnames.

5 min read

How to Scan Devices in Your Local Network Using Python and ARP

Learn how to use Python and Scapy to scan your local network, detect connected devices by IP and hostname, and quickly discover active hosts in your LAN.

5 min read

Testing Common Django Security Vulnerabilities with Python Scripts

Learn how to test common Django security vulnerabilities like XSS, CSRF, SQL Injection, and more using Python scripts.

5 min read

Automate Website Security Scans: Headers, SSL, Ports & Vulns

Scan your website for security headers, SSL issues, open ports, and vulnerabilities like SQL Injection or XSS using a Python script and generate a HTML.

5 min read