简体   繁体   中英

How to skip an IP when using Nmap in Python?

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?


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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM