我没有使用 csv 库,因为您的 csv 没有标头并且具有可变数量的开放端口。它更容易,代码/部门更少。这边。
不带 csv 包的版本 1
import os, sys
from collections import defaultdict
def main(csv):
# use defaultdict so there is no need to initialize
# use set to remove duplicate entries
port_ip_map = defaultdict(set)
# open with, handles errors open closing file handles etc.
with open(csv, 'r') as f:
# read lines
lines = f.readlines()
for line in lines:
# ip must always be the first entry
# port lists can have a variable length
ip, *ports = line.split(',')
for port in ports:
# save ips by port
port = int(port.strip())
port_ip_map[port].add(ip)
for port, ips in port_ip_map.items():
line = ' '.join(ips)
with open('{}.txt'.format(port), 'w') as f:
f.write(line)
if __name__ == '__main__':
# main(sys.argv[1]) # pass csv file by cli
main('./test1.csv')
带有 csv 包的版本 2
import os, sys, csv
from collections import defaultdict
def main(csv_path):
# use defaultdict so there is no need to initialize
# use set to remove duplicate entries
port_ip_map = defaultdict(set)
# open with, handles errors open closing file handles etc.
with open(csv_path, 'r') as f:
# read lines
reader = csv.reader(f)
for row in reader:
# ip must always be the first entry
# port lists can have a variable length
ip, *ports = row
for port in ports:
# save ips by port
port = int(port.strip())
port_ip_map[port].add(ip)
for port, ips in port_ip_map.items():
line = ' '.join(ips)
with open('{}.txt'.format(port), 'w') as f:
f.write(line)
if __name__ == '__main__':
# main(sys.argv[1]) # pass csv file by cli
main('./test1.csv')
样本输入:test1.csv
192.168.10.49,22,80,21
192.168.10.45,80,443,20,21,8080
样本输出:
defaultdict(<class 'set'>, {22: {'192.168.10.49'}, 80: {'192.168.10.45', '192.168.10.49'}, 21: {'192.168.10.45', '192.168.10.49'}, 443: {'192.168.10.45'}, 20: {'192.168.10.45'}, 8080: {'192.168.10.45'}})