我已经在这几个小时了,我无法弄明白。该脚本应该扫描端口22的服务器。但是,代码的最后一行错误输出“KeyError”。令人困惑的是,只有在我使用FOR循环或创建函数并将其传递给值时才会发生这种情况。
如果代码不在循环中,则最后一行无论是硬编码IP还是变量。
如果在最后一行我输入loop_1而没有单引号我得到以下错误: [host]的类型错误,应该是一个字符串'netaddr.ip.IPAddress'
我通过在代码的最后一行之前添加将其转换为字符串。
value = str(loop_1)
这反过来给出了一个错误: KeyError:'10 .0.0.0'
这是脚本。
import nmap
from netaddr import *
nm = nmap.PortScanner()
for loop_1 in IPNetwork('10.0.0.0/26'):
print nm.scan('loop_1', '22')
print nm['loop_1']['tcp'][22]['state']
答案 0 :(得分:3)
如果地址未启动且无法访问,您将收到来自nmap的错误消息:
import nmap
from netaddr import IPNetwork
nm = nmap.PortScanner()
for loop_1 in IPNetwork('10.0.0.0/26'):
print(nm.scan(loop_1.format(), '22'))
try:
print(nm[loop_1.format()]['tcp'][22]['state'])
except KeyError as e:
pass
在ipython中工作:
In [5]: paste
import nmap
from netaddr import IPNetwork
nm = nmap.PortScanner()
for loop_1 in IPNetwork('192.168.43.65/30'):
print(loop_1)
print(nm.scan(loop_1.format(), '22'))
try:
print(nm[loop_1.format()]['tcp'][22]['state'])
except KeyError as e:
pass
## -- End pasted text --
192.168.43.64
{'nmap': {'scanstats': {'uphosts': u'0', 'timestr': u'Wed Dec 24 02:41:51 2014', 'downhosts': u'1', 'totalhosts': u'1', 'elapsed': u'3.06'}, 'scaninfo': {u'tcp': {'services': u'22', 'method': u'connect'}}, 'command_line': u'nmap -oX - -p 22 -sV 192.168.43.64'}, 'scan': {}}
192.168.43.65
{'nmap': {'scanstats': {'uphosts': u'0', 'timestr': u'Wed Dec 24 02:41:55 2014', 'downhosts': u'1', 'totalhosts': u'1', 'elapsed': u'3.05'}, 'scaninfo': {u'tcp': {'services': u'22', 'method': u'connect'}}, 'command_line': u'nmap -oX - -p 22 -sV 192.168.43.65'}, 'scan': {}}
192.168.43.66
{'nmap': {'scanstats': {'uphosts': u'1', 'timestr': u'Wed Dec 24 02:42:01 2014', 'downhosts': u'0', 'totalhosts': u'1', 'elapsed': u'6.14'}, 'scaninfo': {u'tcp': {'services': u'22', 'method': u'connect'}}, 'command_line': u'nmap -oX - -p 22 -sV 192.168.43.66'}, 'scan': {u'192.168.43.66': {'status': {'state': u'up', 'reason': u'syn-ack'}, 'hostname': u'lab', 'vendor': {}, 'addresses': {u'ipv4': u'192.168.43.66'}, u'tcp': {22: {'product': '', 'state': u'open', 'version': '', 'name': u'ssh', 'conf': u'10', 'extrainfo': u'protocol 2.0', 'reason': u'syn-ack', 'cpe': ''}}}}}
open # only address up so only open or closed received
如果你想要一个ips列表以及端口是否打开,可以使用nmap:
nm = nmap.PortScanner()
nm.scan(hosts='10.0.0.0/26',ports="22")
results = [[ip, nm[ip]['tcp'][22]['state']] for ip in nm.all_hosts()]
print("ip {}".format(" ".join(*results)))
ip 10.0.0.1 open
....
答案 1 :(得分:0)
您的循环代码已损坏:
for loop_1 in IPNetwork('10.0.0.0/26'):
print nm.scan('loop_1', '22')
print nm['loop_1']['tcp'][22]['state']
顶部的 loop_1
是一个变量,它是要扫描的地址。但后来你使用了一个不是变量的文字字符串'loop_1'
。你说如果你使用loop_1
没有引号你会得到一个错误,说需要一个字符串而不是一个IPAddress ...所以你必须简单地阅读IPAddress类的文档,找到如何将它转换为字符串(也许只需将str(loop_1)
?)放入括号中。