0

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

3
  • Maybe I am missing something, but 192.168.20.0/24 is 2**24 ca. 16 millions IPs. You need to loop and check each individually.
    – MegaIng
    Jun 20, 2021 at 7:13
  • 1
    Can you try to use [result['scan'][f"192.168.20.{i}"]["tcp"][port]['state'] for i in range(256)]? That should check 256 of the IPs
    – MegaIng
    Jun 20, 2021 at 7:18
  • @Megalng: That's not a general, flexible approach as it only works with /24 CIDR blocks. Jun 20, 2021 at 7:49

1 Answer 1

0

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}")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.