Python

Mastering Network Scanning with Python

Network scanning is the process of discovering devices on a network and identifying their open ports and services. It is an essential part of network security, allowing system administrators to identify potential vulnerabilities and attack vectors. In this article, we will explore network scanning techniques using Python.

Port Scanning

Port scanning is a technique used to identify open ports on a target machine. Python provides several libraries for implementing port scanning, including the socket and nmap libraries.

Using the socket Library

To perform a basic port scan using the socket library, you can use the following code:

import socket

target_host = "192.168.1.1"
target_ports = [21, 22, 80, 443]

for port in target_ports:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)
    result = s.connect_ex((target_host, port))
    if result == 0:
        print("Port {} is open".format(port))
    s.close()

This code creates a socket for each port in the target_ports list and attempts to connect to the target_host. If the connection is successful, the port is considered open.

Using the nmap Library

The nmap library is a more advanced port scanning tool that provides additional functionality, such as OS detection and service identification. To use the nmap library, you can use the following code:

import nmap

nm = nmap.PortScanner()

target_host = "192.168.1.1"
target_ports = "21,22,80,443"

nm.scan(hosts=target_host, arguments="-p " + target_ports)

for host in nm.all_hosts():
    print("Host : %s" % host)
    for port in nm[host]['tcp'].keys():
        print("Port : %s\tState : %s" % (port, nm[host]['tcp'][port]['state']))

This code creates an instance of the nmap.PortScanner() class and uses the scan() method to perform a port scan on the target_host using the specified target_ports. The results are then printed to the console.

Network Discovery

Network discovery is the process of identifying devices on a network. Python provides several libraries for implementing network discovery, including the scapy and netifaces libraries.

Using the scapy Library

To perform network discovery using the scapy library, you can use the following code:

from scapy.all import ARP, Ether, srp

target_ip = "192.168.1.0/24"

# Create ARP request
arp = ARP(pdst=target_ip)

# Create Ethernet frame
ether = Ether(dst="ff:ff:ff:ff:ff:ff")

# Combine Ethernet and ARP requests
packet = ether/arp

# Send packet and capture response
result = srp(packet, timeout=3, verbose=0)[0]

# Extract results
devices = []
for sent, received in result:
    devices.append({'ip': received.psrc, 'mac': received.hwsrc})

# Print results
for device in devices:
    print("IP Address: {}\tMAC Address: {}".format(device['ip'], device['mac']))

This code creates an ARP request for the target_ip and sends it to the network using the srp() function. The response is then captured and parsed to extract the IP and MAC addresses of the devices on the network.

Using the netifaces Library

The netifaces library is a simpler tool that can be used to retrieve information about the network interfaces on a machine. To use the netifaces library, you can use the following code:

import net

Using the netifaces Library (continued)

import netifaces

# Get network interfaces
interfaces = netifaces.interfaces()

# Print information for each interface
for interface in interfaces:
    iface = netifaces.ifaddresses(interface)
    if netifaces.AF_INET in iface:
        ip = iface[netifaces.AF_INET][0]['addr']
        netmask = iface[netifaces.AF_INET][0]['netmask']
        broadcast = iface[netifaces.AF_INET][0]['broadcast']
        print("Interface: {}\tIP Address: {}\tNetmask: {}\tBroadcast: {}".format(interface, ip, netmask, broadcast))

This code retrieves a list of network interfaces on the machine using the interfaces() function and retrieves the IP address, netmask, and broadcast address for each interface using the ifaddresses() function.

Conclusion

Network scanning is an important part of network security, allowing system administrators to identify potential vulnerabilities and attack vectors. In this article, we explored network scanning techniques using Python, including port scanning and network discovery. By using these techniques, you can better understand the devices and services on your network and take steps to secure them.

References