Building a network scanner with Python
Python tools provide many native modules and support for working with sockets and TCP/IP in general. Additionally, Python can use the existing third-party commands available on the system to initiate the required scan and return the result. This can be done using the subprocess
module that we discussed before, in Chapter 9, Using the Subprocess Module. A simple example is using Nmap to scan a subnet, as in the following code:
import subprocess from netaddr import IPNetwork network = "192.168.1.0/24" p = subprocess.Popen(["sudo", "nmap", "-sP", network], stdout=subprocess.PIPE) for line in p.stdout: print(line)
In this example, we can see the following:
- At the beginning, we imported the
subprocess
module to be used in our script. - Then, we defined the network that we want to scan with the
network
parameter. Notice that we used the CIDR notation, but we could use the subnet mask instead and convert that to CIDR notation using the Pythonnetaddr
module. - The...