2021-09-11-解析namp扫描结果的xml的保存方式

import os


import xml.etree.ElementTree as ET
from urllib.parse import urlparse

currDir = os.path.dirname(os.path.realpath(__file__))
rootDir = os.path.abspath(os.path.join(currDir, "../../.."))

batch_target = 'http://223.4.72.2'
batch_target = urlparse(batch_target).hostname
result_dir = os.path.join(rootDir, f"lib/core/infoCollection/result/{batch_target}.xml")
cmd = f"nmap -A -oX {result_dir} {batch_target}"
os.system(cmd)


d = [
    {"path": "address", "el": "addr"},
    {'path': 'hostnames/hostname', 'el': 'name'},
    {"path": "os/osmatch/osclass", "el": "osfamily"},
]

if "./result/223.4.72.2.xml":
    tree = ET.parse("./result/223.4.72.2.xml")
    root = tree.getroot()
    for i in root.iter("host"):
        for h in d:
            e = i.find(h['path'])
            if e is not None:
                print(e.get(h["el"]))
            else:
                print("UNKNowN ", (h["path"]))
#
# #  test-2
import json
from bs4 import BeautifulSoup
with open('./result/223.4.72.2.xml', 'r', encoding='utf-8') as file:
    read_result = file.read()
soup = BeautifulSoup(read_result, 'lxml')
for host in soup.find_all('host'):
    if host.status['state'] == 'up':
        ip = host.address['addr']
        ports = []
        for port in host.ports.find_all('port'):
            ports.append({
                'protocol': port['protocol'],
                'portid': port['portid'],
                'state': port.state['state'],
                'service': port.service['name']
            })
        print(json.dumps(ports, indent=4))

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念