Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用Nmap时如何跳过IP?_Python_Try Catch_Nmap_Network Scan - Fatal编程技术网

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

在Python中使用Nmap时如何跳过IP?,python,try-catch,nmap,network-scan,Python,Try Catch,Nmap,Network Scan,我正在python中使用nmap,并尝试使用文本文件扫描网络。所有扫描范围都在文本文件中,如下所示: 192.168.1.1-100 192.168.1.120-200 但是,假设扫描没有找到主机192.168.1.3,因为它处于脱机状态。程序将崩溃。有没有办法让我避开这次撞车事件?我可以用像Try/Catch这样的东西吗 计数器=0 打开('range.txt')作为范围文件: content=rangefile.readlines() 当计数器

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

192.168.1.1-100 192.168.1.120-200

但是,假设扫描没有找到主机192.168.1.3,因为它处于脱机状态。程序将崩溃。有没有办法让我避开这次撞车事件?我可以用像Try/Catch这样的东西吗


计数器=0
打开('range.txt')作为范围文件:
content=rangefile.readlines()
当计数器
这是代码示例

  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'}
文件“c:\…\nmapscan.py”,第63行,在therehost=Host.objects.get(ipv4\u address=hosts)va.assessment.models.DoesNotExist:主机匹配查询不存在。查找参数为{'ipv4_地址:u'134.250.16.103'}

这是错误

nmap
采用两个参数进行排除
--exclude
获取主机名,
--excludefile
获取包含需要排除的主机名的文件。根据需要使用其中一个。 有关设置目标的更多信息,请参见页面

这是我的测试结果-

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服务器。

它是如何崩溃的?它能提供追踪吗?如果是,那么您可以尝试/排除该异常。您考虑过subprocess.Popen而不是nmap模块吗?如果有的话,您使用的是什么模块?请注意,如果捕获到异常(假设存在异常),则可能会发现扫描的其余部分未完成。Popen几乎就像在命令行中运行nmap一样。您能提供一段崩溃信息或错误吗?您正在使用什么nmap选项?非常感谢您的快速回复!但是,在python中使用nmap时,必须导入nmap,并使用诸如nm.PortScanner()之类的命令。我认为nmap库没有读取文件的方法。python中的nmap只是python中
nmap
的实现。它使用
subprocess.Popen()
执行在终端中使用的
nmap
命令。那么,如果python nmap确实满足了您的需求,为什么您不自己实现
nmap
?使用open('range.txt')作为rangefile:content=rangefile.readlines()nm=nmap.PortScanner()counter=0,而countertry: nm.scan(content[counter], '517', '-sU -sT') except: #handle exception...