【问题标题】:CSV File FormattingCSV 文件格式
【发布时间】:2011-07-24 19:17:46
【问题描述】:

我编写了一个 perl 脚本来输出一个包含我扫描到 Microsoft excel 中的 IP 地址和端口的文本文件。现在数据在 excel 中,我的老板希望我以 csv 格式组织文件,例如

Server, port, protocol, random, random, random
ns1,    25,   tcp,      stuff,  stuff,  stuff

有谁能帮帮我吗?

代码:

#!/usr/bin/perl

$input = `Cat /cygdrive/c/Windows/System32/test11.txt | grep -v 'SYN Stealth'`;
chomp input;
$output =" /cygdrive/c/Users/bpaul/Desktop/194.csv ";
if (! -e "$output")
{
`touch $output`;
}
open (OUTPUTFILE, ">$output") || die "Can't Open file $output";
print OUTPUTFILE "$input\n";
close (OUTPUTFILE);

这是我的一份文件

Nmap scan report for 69.25.194.2 Host is up (0.072s latency). Not shown: 9992 filtered ports PORT STATE SERVICE 25/tcp open smtp
80/tcp open http
82/tcp open xfer
443/tcp open
https 4443/tcp closed
pharos 5666/tcp closed
nrpe 8080/tcp closed
http-proxy 9443/tcp closed tungsten-https

到目前为止,我的代码获取了我的 txt 文件并将其输出到 excel 现在我需要像这样格式化数据:

期望的输出:

Server, port, protocol, random, random, random
ns1,    25,   tcp,      stuff,  stuff,  stuff

【问题讨论】:

    标签: perl parsing csv


    【解决方案1】:

    当你说ns1时,我假设你的意思是69.25.194.2

    use strict;
    use warnings;
    
    use Text::CSV_XS qw( );
    
    my $csv = Text::CSV_XS->new({ binary => 1, eol => "\n" });
    
    $csv->print(\*STDOUT, [qw(
        Server
        port
        protocol
        random
        random
        random
    )]);
    
    my $host = '[unknown]';
    
    while (<>) {
        $host = $1 if /Nmap scan report for (\S+)/;
    
        my ($port, $protocol) = m{(\d+)/(\w+) (?:open|closed)/
            or next;
    
        $csv->print(\*STDOUT, [
            $host,
            $port,
            $protocol,
            'stuff',
            'stuff',
            'stuff',
        ]);
    }
    

    用法:

    grep -v 'SYN Stealth' /cygdrive/c/Windows/System32/test11.txt | perl to_csv.pl > /cygdrive/c/Users/bpaul/Desktop/194.csv
    

    Text::CSV_XS

    更新:将硬编码的ns1 替换为扫描机器的地址。

    更新:将通用用法替换为 OP 将使用的用法。

    【讨论】:

    • 谢谢,但有没有办法不使用 Text::CSV_XS qw( );当我尝试使用它时,我通常会在 cygwin 中收到错误消息。
    • @kingp,什么错误信息?您是否安装了 Text::CSV_XS? (cpan Text::CSV_XS)
    猜你喜欢
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 2020-10-28
    • 2015-09-27
    • 1970-01-01
    相关资源
    最近更新 更多