【问题标题】:Parse Output of Command into Variable LIVE (Network Traffic Monitoring)将命令的输出解析为变量 LIVE(网络流量监控)
【发布时间】:2015-11-17 10:33:54
【问题描述】:

我正在用 bash 编写网络监控脚本。我使用的基本命令是ettercap -T -M ARP -i en1 // //。然后我将egrep --color 'Host:|GET' 输入其中。

我得到的示例输出如下所示:

GET /images/srpr/logo11w.png HTTP/1.1.
Host: www.google.com.
GET /en-us/us/products HTTP/1.1.
Host: www.caselogic.com.

我想要的输出是这样的:

Title: logo11w.png
URL: www.google.com/images/srpr/logo11w.png HTTP/1.1.

Title: Products - Case Logic
URL: www.caselogic.com/en-us/us/products

注意事项:HTTP/1.1. 和主机末尾的. 不见了。它们也组成一个URL,每个Title/URL 列表后面都有一个空行。我尝试通过将命令输出解析成一个变量来将它们形成一个 URL

var=`sudo ettercap -T -M ARP -i en1 // // | egrep --color 'Host:|GET'` | echo $var

但显然这不起作用,因为变量的输入是一个命令,直到用户请求停止 (CTRL + C) 才完成。

要获取 HTML 页面的标题,我使用命令 wget -qO- 'https://url.goes/here' | perl -l -0777 -ne 'print $1 if /<title.*?>\s*(.*?)\s*<\/title/si'。如果是没有标题的东西,比如图片,没有标题也没问题。

非常感谢任何帮助,如果我写的内容难以阅读,请随时提出问题。

【问题讨论】:

    标签: macos bash perl sed grep


    【解决方案1】:

    试试这个:

    title_host.pl

    #!/usr/bin/env perl
    
    use warnings;
    use strict;
    use WWW::Mechanize;
    
    my $mech = WWW::Mechanize->new();
    
    my ($get,$host,$title);
    while (<>) {
        if (m|^GET (\S+) |) {
            $get = $1;
        } elsif ( m|^Host: (\S+)\.| ) {
            $host = $1;
        } else {
            # Unrecognized line...reset
            $get = $host = $title = '';
        }
    
        if ($get and $host) {
            my ($title) = $get =~ m|^.*\/(.+?)$|; # default title
            my $url = 'http://' . $host . $get;
            $mech->get($url);
            if ($mech->success) {
                # HTML may have title, images will not
                $title = $mech->title() || $title;
            }
            print "Title: $title\n";
            print "URL: $url\n";
            print "\n";
    
            $get = $host = $title = '';
        }
    }
    

    输入

    GET /images/srpr/logo11w.png HTTP/1.1.
    Host: www.google.com.
    GET /en-us/us/products HTTP/1.1.
    Host: www.caselogic.com.
    

    现在只需将您的输入输入到 perl 脚本中:

    cat input | perl title_host.pl
    

    输出:

    Title: logo11w.png
    URL: http://www.google.com/images/srpr/logo11w.png
    
    Title: Products - Case Logic
    URL: https://www.caselogic.com/en-us/us/products
    

    【讨论】:

    • 谢谢,我试试看!
    • 无论如何我可以在 bash 脚本中包含 Perl 以使其可移植吗?如果没有,那很好。
    • 是的,您可以在 heredoc 中包含 perl 脚本:stackoverflow.com/questions/17751199/…
    • 非常感谢!像魅力一样工作!
    • 您意识到提供命令的脚本需要 (1) 在您的 PATH 中,并且 (2) 被授予可执行权限?这里已经有很多问题和答案描述了必要的步骤。
    猜你喜欢
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多