Search code examples
python-3.xnmap

Is there a way to scan an entire network range (192.168.0./24) in python and have the data outputted to a text file?


I'm relatively new to python so I don't have the most knowledge. I'm using python-nmap to scan the network range but the problem I'm struggling with most is outputting the results to a text file. This is what I have so far

import nmap


ip = '192.168.20.1'
port = 80
nmap = nmap.PortScanner()
result = nmap.scan(ip, str(port))
port_status = (result['scan'][ip]['tcp'][port]['state'])
print(f"Port {port} is {port_status} on {ip}")
with open('nmap.txt','w') as file:
    file.write(f"Port {port} is {port_status} on {ip}")

while this works for only a singular ip, im trying to scan for an entire network range, such as 192.168.20.0/24. When I set to the ip variable to '192.168.20.0/24' I get the following error code:

    Traceback (most recent call last):
  File "c:/Users/john/Desktop/Python/Test.py", line 8, in <module>
    port_status = (result['scan'][ip]['tcp'][port]['state'])
KeyError: '192.168.20.0/24'

I feel like there is a very simple fix to this and part of me feels idiotic for posting this but help would be very much appreciated. Thank you


Solution

  • With CIDR notation you will get multiple results, while your lines 8-11 can only handle a single result. You need a loop to handle your python-nmap results.

    import nmap
    ips = '192.168.20.0/24'
    port = 80
    nmap = nmap.PortScanner()
    nmap.scan(ips, port)
    
    with open('nmap.txt','w') as file:
        for host in nmap.all_hosts():
            port_state = nmap[host]['tcp'][port]['state']
            print(f"Port {port} is {port_state} on {host}")
            file.write(f"Port {port} is {port_state} on {host}")