比第一版多的功能是:可以提取指定端口了
# coding: utf-8
import os
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
reload(__import__('sys')).setdefaultencoding('utf-8')
'''
nmap -Pn -n -vv -F -oX d:\\xxx.xml 10.129.246.1/24
nmap -n -vv --open -oX d:\\vm.xml 192.168.106.1/24
--open这个参数必须加
nmap -Pn -n -vv -p80 -oX d:\\xxx.xml 10.129.246.1/24 检测单一端口的就不用执行端口提了
'''
def deal_nmap_xml(xml_name, city_name):
root = ET.fromstring(xml_name)
ip_list = []
res = open(city_name + '.txt', 'w') # 轻易不要改动
for host in root.findall('host'):
if len(host) > 3:
print '\n', str(len(host)), # 打印host标签中子元素个数
if host[0].get('state') == "up": # 判断IP是否存活
ip = host[1].get('addr') # 提取IP地址
print ip,
ip_list.append(ip) # 验证存活IP个数
ip_ = '\n' + ip + '\t'
res.writelines(ip_)
# 提取端口
if len(host) == 6:
for port in host[4][1:]: # 若确认端口开放,但没有提取出端口请修改host[4][此处+1试试:],加一后为host[4][2:],下面的几处方法一样
print port.get('portid'),
port_ = str(port.get('portid')) + ','
res.write(port_)
elif len(host) == 5:
for port in host[3][2:]:
# print port.tag,
print port.get('portid'),
port_ = str(port.get('portid')) + ','
res.write(port_)
elif len(host) == 4:
for port in host[3][1:]:
print port.get('portid'),
port_ = str(port.get('portid')) + ','
res.write(port_)
elif len(host) < 4:
print host[0].get('state')
res.close()
print '\n Alive IP Total:{} '.format(len(ip_list))
def get_ip(ip_list, port):
with open(ip_list, 'r') as xx:
# print xx.read()
with open(port + '-' + ip_list.split('.')[0] + '.txt', 'w+') as save_file:
for line_info in xx.readlines():
# print line_info.split('\t')
try:
if port in line_info.split('\t')[1]:
# print line_info.split('\t')[0]
save_file.writelines(line_info.split('\t')[0] + '\n')
except:
pass
print u"{} 处理完成".format(port)
if __name__ == "__main__":
# Method 1
path = os.getcwd()
city_name = r'fujian05.xml' #要处理的nmap扫描xml文件
file_path = path + '\\' + city_name
file_name = city_name.split('.')[0]
bd = open(city_name, 'r').read() # nmap的扫描结果文件
print u'开始提取IP和端口'
deal_nmap_xml(bd, file_name)
print u'开始提取IP和端口提取完毕\n'
# Method 2
# tree = ET.parse('xxx.xml')
# root = tree.getroot()
if os.path.exists(os.getcwd() + '\\' + file_name + '.txt'):
print u'开始提取端口'
get_ip(file_name + '.txt', '7001')
#get_ip(file_name + '.txt', '22')
#get_ip(file_name + '.txt', '23')
#get_ip(file_name + '.txt', '3306')
#get_ip(file_name + '.txt', '1433')
else:
print u"NMAP结果处理文件不存在,请确保在同一目录下!!"