在Python中使用Nmap时如何跳过IP?

问题描述 投票:0回答:1

我正在python中使用nmap,并尝试使用文本文件扫描网络。所有扫描范围都在文本文件中,如下所示:

192.168.1.1-100192.168.1.120-200...

尽管,可以说扫描没有找到主机192.168.1.3,因为它处于脱机状态。该程序将崩溃。有什么办法可以解决这个崩溃的问题?我可以使用“尝试/捕获”之类的东西吗?


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')

这是代码示例

  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'}

这是错误

python try-catch nmap network-scan
1个回答
2
投票

nmap接受两个自变量。 --exclude使用主机名,--excludefile使用包含需要排除的主机名的文件。根据需要使用其中之一。有关设置目标的更多信息,请参见man页面。

这是我的测试结果-

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': ''}}}
>>> 

您可以使用try-catch-

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

由于您没有关闭哪些服务器,因此可以在继续进行nmap扫描之前对服务器进行ping操作。

© www.soinside.com 2019 - 2024. All rights reserved.