Advanced Network Scanning using Python

9 Min Read

Hey there Cyber-Sleuths! 👩‍💻

Alrighty then, let’s get cracking on network scanning using Python! 💻 I’m super excited to demystify this whole jingbang and help you become the Sherlock of the cyber world.

Introduction to Network Scanning using Python

So, what in the world is network scanning? It’s like having x-ray vision for the cyber realm, scanning networks to find all the nooks and crannies – the open ports, live hosts, and whatnot. And why Python, you ask? Well, it’s like the swiss army knife of programming languages – versatile, handy and oh-so-powerful! Python’s simplicity and significant libraries make it the perfect match for network scanning shenanigans.

Python Libraries for Network Scanning

Let’s get down to brass tacks. When it comes to network scanning using Python, you’ve got a whole toolbox of libraries at your disposal. From the old guard like socket to the sleek and modern Scapy, each has its own flavor and flair. It’s like picking your favorite ice cream – each one has its unique taste, but they all satisfy that sweet tooth! 🍦

Scapy vs. Socket vs. Nmap: The Showdown

Alright, so we’ve got Scapy – the cool kid on the block known for crafting packets with finesse. Then there’s good ol’ reliable Socket, a Python standard library favorite for low-level network interaction. And of course, Nmap – the OG network mapper, bringing powerful network scanning capabilities to the table.

Advanced Techniques in Network Scanning using Python

Alright, hold onto your seats, ’cause things are about to get spicy! We’re talking about advanced techniques here, folks! Let’s start with port scanning. A bit like playing hide and seek, but with ports on a network. We snoop around, knock on some doors, and find out where all the action is happenin’! Then, there’s vulnerability scanning. It’s like being a cyber detective, figuring out where the weak spots are and how to patch ’em up!

Automation in Network Scanning using Python

Now, let’s talk about automation. We’re in the 21st century, after all! Python lets you build scripts that take care of the nitty-gritty stuff for you, so you can sit back and relax while your code does all the heavy lifting. I’m talking about scripts that can run the show on their own, like a well-oiled cyber-detective machine. Plus, with Python’s scheduling mojo, you can set up routine scans that happen like clockwork. It’s like having your very own cyber butler, I tell ya!

Best Practices for Cybersecurity & Ethical Hacking in Python

Ah, the ethical conundrum! It’s like walking a tightrope, ain’t it? On one hand, you’ve got the power to crack open networks (legally, of course) and on the other, the responsibility to use your powers for good, not evil. It’s all about using your cyber prowess for the forces of good and not to cause mayhem and mischief in the cyber universe. And of course, we can’t forget about cybersecurity best practices – it’s like locking your front door, but for the cyber world, keeping everything safe and sound.

Wrapping Up

So there you have it, folks! We’ve covered the whole enchilada of network scanning using Python, from the nitty-gritty details to the grand cyber-ethics shebang. Python and network scanning are like peanut butter and jelly – they just go together!

Finally, here’s a fun fact for you – did you know that the first computer virus was written in the early 1970s by Bob Thomas and was an experimental self-replicating program? It’s like the OG cyber prank, huh?

Keep coding, stay curious, and remember – with great power comes great responsibility…and a whole lotta cyber fun! Catch you on the cyber flip side! 🌐

Program Code – Advanced Network Scanning using Python


import socket
import threading
import ipaddress
from queue import Queue

# Define the target. Here we assume a local network, but it can be any network.
network = '192.168.1.1/24'
port_range = [22, 25, 80, 443]  # Common ports to scan.

# Converts the network into a list of IP addresses.
ip_net = ipaddress.ip_network(network)
all_hosts = list(ip_net.hosts())

# Socket timeout.
socket.setdefaulttimeout(1)

# Queue for threads.
q = Queue()

# Lock for threads to prevent jumbled print statements.
print_lock = threading.Lock()

# Function to scan the port.
def port_scan(port):
    global target_ip

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        con = s.connect((target_ip, port))

        with print_lock:
            print(f'{target_ip}:{port} is open.')

        con.close()
    except:
        pass

# Threader thread pulls a worker from the queue and processes it.
def threader():
    while True:
        # gets a worker from the queue.
        worker = q.get()

        # Run the port scanner function on the worker (port to be scanned).
        port_scan(worker)

        # Completed with the job.
        q.task_done()

# Main function to handle the scanning.
def main(all_hosts, port_range):
    global target_ip

    # Creating threads that will execute the `threader` function.
    for x in range(30):
        t = threading.Thread(target=threader)
        t.daemon = True
        t.start()

    # For each host in all_hosts, run the scan for the specified port range.
    for host in all_hosts:
        target_ip = str(host)
        print(f'
Scanning IP: {target_ip}')

        for port in port_range:
            q.put(port)  # Put the port into the queue.
        
        # wait until the thread terminates.
        q.join()

# Run the main function.
main(all_hosts, port_range)

Code Output:

Scanning IP: 192.168.1.1
192.168.1.1:22 is open.
192.168.1.1:80 is open.
...
Scanning IP: 192.168.1.2
...
Scanning IP: 192.168.1.254

Code Explanation:
The code above is an advanced network scanner built using Python. It efficiently scans a network for open ports across multiple IP addresses. Here’s how it achieves its objectives:

  1. Module Imports: We’re using socket for network connections, threading for concurrency, ipaddress for network range parsing, and Queue for threading job assignments.
  2. Network and Port Range Definition: We define the subnet to scan and a list of common ports we want to check.
  3. Queue and Locks: A queue is used to hold the ports to be scanned, and threading locks ensure that console output does not get mixed up.
  4. Port Scan Function: The port_scan function attempts to open a socket connection to a target IP and port. If successful, it reports the port as open.
  5. The Threader Function: It serves workers (ports) to the port_scan function and ensures task completion.
  6. Main Function: It initializes threads, iterates through each host in the subnet, queues up the ports to scan, and waits for the threads to finish before moving to the next host.
  7. Daemon Threads: Threads are set to daemon so they will quit when the main program exits.
  8. Execution: The main function runs the scanning process across the specified network and port range. Each open port on an IP is printed to the console.
  9. Scalability: The threaded model allows scanning of multiple ports in parallel, thereby making the scanning process much faster than a linear approach.

Remember, the scanning process may be considered intrusive or illegal on certain networks; always have proper authorization before running this code.

Share This Article
Leave a comment

Leave a Reply

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

English
Exit mobile version