以 ip:port 格式解析工作“masscan”的结果

我开始学习编程,我正在尝试编写一个简单的解析器,但我很困惑。如果有人帮助我,我会很高兴。


文件.txt


# Masscan 1.0.3 scan initiated Sun Dec 23 23:00:31 2018

# Ports scanned: TCP(1;80-80) UDP(0;) SCTP(0;) PROTOCOLS(0;)

Host: 192.168.1.1 ()    Ports: 80/open/tcp////

Host: 192.168.1.1 ()    Ports: 801/open/tcp////

Host: 192.168.1.2 ()    Ports: 801/open/tcp////

Host: 192.168.1.2 ()    Ports: 445/open/tcp////

Host: 192.168.1.3 ()    Ports: 80/open/tcp////

Host: 192.168.1.3 ()    Ports: 8080/open/tcp////

Host: 192.168.1.3 ()    Ports: 21/open/tcp////

# Masscan done at Sun Dec 23 23:00:45 2018

我想以一种格式接收数据:


192.168.1.1 80, 801

192.168.1.2 801, 445

192.168.1.3 80, 8080, 21

脚本文件


#!/usr/bin/env python

import sys, re, os


ports = []

ip = None


with open('mres.txt','r') as f:


for elem in f.readlines():


    if not elem.startswith('#'):

          if ip != None:

              if elem.split(' ')[1] == ip:

                  ports.append(elem.split(' ')[3].split('/')[0])

                  continue

              else:

                  print(ip + str(ports))

                  ports=[]

          else:

              #print('Unic: '+str(ip) + ' port: '+ str(elem.split(' ')[3].split('/')[0]))

              ip = elem.split(' ')[1]

              ports.append(elem.split(' ')[3].split('/')[0]) 


万千封印
浏览 262回答 2
2回答

白衣染霜花

你最好使用dict来处理数据:1)IP可以是Dict中的key 2)List可以是Dict中的值。如果需要,我可以为您创建示例代码。

哆啦的时光机

这将操作您的数据,并打印您想要的输出。我已经尝试在下面的评论中尽可能地解释它,但请提出任何不清楚的问题。from collections import defaultdictimport socket# build a dictionary of ip -> set of ports# default dict is cool becasue if the key doesn't exist when accessed,# it will create it with a default value (in this case a set)# I'm using a set because I don't want to add the same port twiceip_to_ports = defaultdict(set)with open('mres.txt') as fp:    for line in fp:        # grab only the lines we're interested in        if line.startswith('Host:'):            parts = line.strip().split()            ip = parts[1]            port = parts[-1]            # split it by '/' and grab the first element            port = port.split('/')[0]            # add ip and ports to our defaultdict            # if the ip isn't in the defaultdict, it will be created with            # an empty set, that we can add the port to.            # if we run into the same port twice,             # the second entry will be ignored.            ip_to_ports[ip].add(port)# sort the keys in ip_to_ports by increasing addressfor ip in sorted(ip_to_ports, key=socket.inet_aton):    # sort the ports too    ports = sorted(ip_to_ports[ip])    # create a string and print    ports = ', '.join(ports)    print(ip, ports)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python