Question

I am using nmap in python, and trying to scan the network using a text file. All the scan ranges are in a text file, like so:

192.168.1.1-100 192.168.1.120-200 ...

Though, lets say if the scan did not find host 192.168.1.3, because it was offline. The program will crash. Is there a way that I can get around this crashing? Can I use something like Try / Catch?

Thanks, Jay


counter = 0
with open('range.txt') as rangefile:
    content = rangefile.readlines()

while counter < len(content):
    nm = nmap.PortScanner()
    #define the nmap scan here
    nm.scan(content[counter], '517', '-sU -sT')

This is the sample of code

  File "c:\...\nmapscan.py", line 63, in <module> therehost = Host.objects.get(ipv4_address=hosts) va.assessment.models.DoesNotExist: Host matching query does not exist. Lookup parameters were {'ipv4_address': u'134.250.16.103'}

This is the error

Was it helpful?

Solution

nmap takes two arguments for exclusion. --exclude takes host name(s) and --excludefile takes a file containing name of hosts that need to be excluded. Use one of these as your need. For more on setting target see the man page.

Here is my test result -

Python 3.2.3 (default, May  3 2012, 15:54:42) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import nmap
>>> nm=nmap.PortScanner()
>>> nm.scan('134.250.16.103','517', '-sU -sT')
{'nmap': {'scanstats': {'uphosts': '0', 'timestr': 'Sat Jul 28 12:54:27 2012', 'downhosts': '1', 'totalhosts': '1', 'elapsed': '3.06'}, 'scaninfo': {'udp': {'services': '517', 'method': 'udp'}, 'tcp': {'services': '517', 'method': 'connect'}}, 'command_line': 'nmap -oX - -p 517 -sU -sT 134.250.16.103'}, 'scan': {'134.250.16.103': {'status': {'state': 'down', 'reason': 'no-response'}, 'hostname': ''}}}
>>> 

You can use try-catch-

try:
   nm.scan(content[counter], '517', '-sU -sT')
except:
   #handle exception...

As you don't which servers are down, you can ping the server before you proceed to nmap scan.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top