代码命令:
from libnmap.parser import NmapParser
import getopt
import sys
summary= False
port=''
os =''
file_path=''
#参数解析
options,useless = getopt.getopt(sys.argv[1 :],'f:sp:o:')
for i in options:
if i[0]=='-s':
summary = True
elif i[0]=='-p':
port= i[1]
elif i[0]=='-f':
file_path= i[1]
else:
os=i[1]
report = NmapParser.parse_fromfile(file_path)
system_map={}
service_map={}
for host in report.hosts:
if len(host.os_class_probabilities()):
osfamily = host.os_class_probabilities()[0].osfamily
if system_map.__contains__(osfamily):
system_map[osfamily].append(osfamily+'\t'+host.os_class_probabilities()[0].osgen+'\t'+host.address)
else:
system_map[osfamily] = []
system_map[osfamily].append(osfamily+'\t'+host.os_class_probabilities()[0].osgen+'\t'+host.address)
for serv in host.services:
key= str(serv.port)
if service_map.__contains__(key):
service_map[key].append(str(serv.port)+'\t'+host.address+'\t'+serv.protocol+'\t\t'+serv.state+'\t'+serv.service)
else:
service_map[key] = []
service_map[key].append(str(serv.port)+'\t'+host.address+'\t'+serv.protocol+'\t\t'+serv.state+'\t'+serv.service)
def get_summary():
print('--------------summary-----------------')
print('Total host:%d'%report.hosts_total)
print('Hosts is up:%d'%report.hosts_up)
print('Hosts is down:%d'%report.hosts_down)
for i in system_map.keys():
print('%d hosts is%s'%(len(system_map[i]),i))
for i in service_map.keys():
print('%d hosts opened %s'%(len(service_map[i]),i))
print ('\n\n')
def get_port():
print ('-----port summary-----')
print ('port\taddress\t\tprotocol\tstate\tservice')
if service_map.__contains__(port):
for i in service_map[port]:
print (i)
print ('\n\n')
def get_os():
print ('os summary')
print ('os\tosgen\tadress')
if system_map.__contains__(os):
for i in system_map[os]:
print (i)
print ('\n\n')
if summary:
get_summary()
if port:
get_port()
if os:
get_os()
测试流程:
先执行:
sudo nmap -Pn -vv -O -oX test.xml 192.168.16.1
效果图:
然后执行:
sudo python3 ./infosearch/namp.py -f './test.xml' -s -o Linux -p 139
效果图:
常见问题:
AttributeError: 'dict' object has no attribute 'has_key'
问题原因:
python版本的兼容问题。has_key方法在python2中是可以使用的,在python3中删除了。
解决方法:
将has__key(key)用__contains__(key)代替