首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python 3:如何从嵌套列表生成表作为输入

问Python 3:如何从嵌套列表生成表作为输入
EN

Stack Overflow用户
提问于 2019-05-31 13:08:00
回答 2查看 575关注 0票数 0

因此,我得到了下面的嵌套列表(我从一个Nmap XML输出文件中解析了这个列表)。它基本上是一个IP地址列表,以及它们所有的开放端口:

代码语言:javascript
复制
[['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
 ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']],
 ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']],
 ['192.168.228.211', ['80']],
 ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]]

我想从这个数据创建一个表,其中每个第一项(所有IP地址)都被打印为行。然后,我希望迭代每个第二项(每个IP地址的所有端口的列表),并计算每个唯一的端口号。我希望这个新统计的唯一端口列表被打印为我的表的列标题。然后,我的空表应该大致如下所示:

代码语言:javascript
复制
                 53  80  88  135  139  389  445  3389  5800  5900
192.168.23.78
192.168.27.243
192.168.99.164
192.168.228.211
192.168.171.74

然后,我希望在每个具有给定开放端口的IP地址的正确单元格中放置X,如下所示:

代码语言:javascript
复制
                 53  80  88  135  139  389  445  3389  5800  5900
192.168.23.78    X   X       X    X    X         X
192.168.27.243               X    X         X    X     X     X
192.168.99.164               X    X         X    X     X     X
192.168.228.211      X
192.168.171.74               X    X         X    X     X     X

我如何用我的数据集来做这件事呢?

我是一个完全的新手,但我可能会弄清楚如何迭代所有的端口号,并得到一个唯一的端口列表。但我完全不知道如何在桌子上,在正确的单元格里画X

到目前为止,这是我的代码:

代码语言:javascript
复制
#!/usr/bin/env python

from pprint import pprint
import xml.etree.ElementTree as ET

def loopy(item):
    for port in host.findall('ports/port'):
        if port.get('protocol') == "tcp":
            portid = port.get('portid')
            for state in port.findall('state'):
                if state.get('state') == "open":
                    if item == "address":
                        list_addr.append(addr)
                        return
                    elif item == "portid":
                        list_portid.append(portid)

root = ET.parse('scan5.xml').getroot()
result = []
for host in root.findall('host'):
    list_portid = []
    list_addr = []
    address = host.find('address')
    addr = address.get('addr')
    loopy("address")
    loopy("portid")
    if list_addr:
        result.append([list_addr[0], list_portid])

pprint(result)

我的嵌套列表现在在result中,但是我不知道如何从它创建一个表。

到目前为止,我的代码只生成原始列表:

代码语言:javascript
复制
[['10.133.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
 ['10.133.27.243', ['135', '139', '445', '3389', '5800', '5900']],
 ['10.133.99.164', ['135', '139', '445', '3389', '5800', '5900']],
 ['10.135.228.211', ['80']],
 ['10.133.171.74', ['135', '139', '445', '3389', '5800', '5900']]]
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-31 13:33:52

您可以使用安装和使用精美的包来可视化漂亮的表。

第一pip install prettytable

然后编码

代码语言:javascript
复制
from prettytable import PrettyTable

data = [['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
        ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']],
        ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']],
        ['192.168.228.211', ['80']],
        ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]]

ports = sorted(set([int(port) for _, open_ports in data for port in open_ports]))

my_table = PrettyTable()
header = ['ip']
header.extend(ports)
my_table.field_names = header
for ip_address, open_ports in data:
    row = [ip_address]
    row.extend('X' if str(port) in open_ports else '' for port in ports)
    my_table.add_row(row)

print(my_table)

输出

代码语言:javascript
复制
+-----------------+----+----+----+-----+-----+-----+-----+------+------+------+
|        ip       | 53 | 80 | 88 | 135 | 139 | 389 | 445 | 3389 | 5800 | 5900 |
+-----------------+----+----+----+-----+-----+-----+-----+------+------+------+
|  192.168.23.78  | X  |    | X  |  X  |  X  |  X  |  X  |  X   |      |      |
|  192.168.27.243 |    |    |    |  X  |  X  |     |  X  |  X   |  X   |  X   |
|  192.168.99.164 |    |    |    |  X  |  X  |     |  X  |  X   |  X   |  X   |
| 192.168.228.211 |    | X  |    |     |     |     |     |      |      |      |
|  192.168.171.74 |    |    |    |  X  |  X  |     |  X  |  X   |  X   |  X   |
+-----------------+----+----+----+-----+-----+-----+-----+------+------+------+
票数 0
EN

Stack Overflow用户

发布于 2019-05-31 13:48:27

使用numpy和pandas可以做到

代码语言:javascript
复制
import pandas as pd
import numpy as np

table = [['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
         ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']],
         ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']],
         ['192.168.228.211', ['80']],
         ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]]

# Collect the ip_addresses
ip_addresses = [el[0] for el in table]

# Collect the column names. Temporarily convert to integers to sort them properly
columns = sorted(np.unique([c for el in table for c in el[1]]), key = lambda x: int(x))


# Initialize numpy matrix to hold strings
table_matrix = np.zeros((len(ip_addresses), len(columns)), str)

for row in table:
    # Get the row index of the IP address
    for i, ip in enumerate(ip_addresses):
        if row[0] == ip:
            rdx = i
    # Check which columns have values in the row that corresponds to the IP address    
    for c in row[1]:
        for j, col in enumerate(columns):
            # Add an X if the row has that column
            if c == col:
                table_matrix[rdx, j] = 'X'

# Create DataFrame
df = pd.DataFrame(table_matrix, index = ip_addresses, columns = columns)

输出:

代码语言:javascript
复制
Out[24]: 
                53 80 88 135 139 389 445 3389 5800 5900
192.168.23.78    X     X   X   X   X   X    X          
192.168.27.243             X   X       X    X    X    X
192.168.99.164             X   X       X    X    X    X
192.168.228.211     X                                  
192.168.171.74             X   X       X    X    X    X
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56395717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档