Python将CSV中多行的数据合并(连接)到另一个CSV中的一个单元格中

2024-09-30 18:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我每天都在运行一些nmap扫描报告,我试图用Python完全自动化。我有一个带有IP和端口号的CSV,每行一个。我试图把端口号合并成一个列表。以下是输入csv的示例:

    address       port
    192.168.3.5   80
    192.168.3.5   443
    192.168.3.5   3389
    192.168.3.5   137
    192.168.4.77  80
    192.168.4.77  445

输出应如下所示:

^{pr2}$

以下是整个脚本:

import subprocess

# Function to run peepingtom
def run_peepingtom(dir):

    scanfile = dir + '/nmap-scan.xml'

    subprocess.call(["python", "peepingtom/peepingtom.py", "-x", scanfile, "-o", dir + "/peepcaptures/"])


# Function to run NMAP on a list of IPs. The scan results will be in "dir" location
def run_nmap(dir):

    targets = dir + '/targets.txt'

    subprocess.call(["nmap", "-vv", "-A", "-sV", "-Pn", "-T4", "-iL", targets, "-oA", dir + "/nmap-scan"])

    # Create an HTML report
    subprocess.call(["xsltproc", dir + "/nmap-scan.xml", "-o", dir + "/nmap-scan.html"])


# Function to convert NMAP output to CSV
def run_nmap_parser(dir):

    scanfile = dir + '/nmap-scan.xml'

    subprocess.call(["python", "nmap-parser-xml-to-csv/nmap-parser-xml-to-csv.py", scanfile, "-s", ",", "-o", dir + "/nmap-scan.csv"])


def main():

    outputdir= '2015-07-20'

    run_nmap(outputdir)

    run_peepingtom(outputdir)

    run_nmap_parser(outputdir)


if __name__ == '__main__':
    main()

我写了一个Python脚本来完成扫描和创建CSV输出等等,我使用了一些开源工具来获得我需要的东西。我需要做更多的手动格式化后,这是我试图自动化。我在Python方面的技能非常有限,因此如果有任何帮助,请从哪里开始?在


Tags: csvtorunparserscandefdirxml
1条回答
网友
1楼 · 发布于 2024-09-30 18:19:51

下面的脚本可以处理您输入的CSV文件。它读取CSV报告登录的每一行,并为每个IP地址将其添加到字典中。每个字典条目包含一个用于给定IP地址的端口的set。输出按IP地址排序。在

import csv, collections, socket

d_ip = collections.defaultdict(set)

with open("report_log.csv", "r") as f_input:
    csv_input = csv.reader(f_input, skipinitialspace=True)
    headers = next(csv_input)

    for row in csv_input:
        d_ip[row[0]].add(row[1])
        #d_ip[row[0]].append(row[1])   # if a list is preferred

with open("port_usage.csv", "wb") as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(headers)
    print "%-20s %s" % (headers[0], headers[1])

    # Sort by IP address
    ip_sorted = d_ip.keys()
    ip_sorted.sort(key=lambda x: socket.inet_aton(x))

    for ip in ip_sorted:
        l_ports = list(d_ip[ip])
        l_ports.sort(key=lambda x: int(x))
        csv_output.writerow([ip, ", ".join(l_ports)])
        print "%-20s %s" % (ip, ", ".join(l_ports))

将打印以下输出:

^{pr2}$

如果需要所有端口(不仅仅是唯一的端口),只需将其改为defaultdict(list),将.add()改为{},并注释掉{}。在

相关问题 更多 >