I have a list of my ip's in my python script, and I'm trying to run a nmap scan on each of them to find open ports. I keep getting this error:
Traceback (most recent call last):
File "rscan.py", line 33, in <module>
main()
File "rscan.py", line 30, in main
vulnscan(nm, L)
File "rscan.py", line 6, in vulnscan
for port in nm[item].all_tcp():
File "build/bdist.linux-x86_64/egg/nmap/nmap.py", line 567, in __getitem__
KeyError: u'IP ADDRESS HERE'
(There is an actual ip address in the "IP ADDRESS HERE" part, though.)
The scanning part of my code that I tried is is:
for item in L:
for port in nm[item].all_tcp():
state= nm[item]['tcp'][port]['state']
if state== 'open':
print state
'L' is the list that contains my ip addresses.
What is the proper way to scan a small list of ip addresses for open ports using nmap?
Like this, based on your code:
for item in L:
if item in nm.all_hosts():
for port in nm[item].all_tcp():
state = nm[item]['tcp'][port]['state']
if state == 'open':
print state
Checking if specified ip
address is in nm.all_hosts()
(which returns a list of ips
) allows you to safely query nm[item]
afterwards.
Note that you could make this code a bit cleaner by simply intersecting your L list with the list of ip addresses returned by nm.all_hosts():
items = list(set(L) & set(nm.all_hosts()))
for item in items:
for port in nm[item].all_tcp():
state = nm[item]['tcp'][port]['state']
if state == 'open':
print state