喜 我编写了一个perl脚本,我将填充了ip和端口扫描的文本文件中的列存储到变量中。变量包含许多ip addreses,端口,协议,状态和服务,现在我需要一个while循环,它将所有ip存储在ip变量中,并将它们与相应的端口协议和状态等相匹配,并且看起来如此: 192.168.3 45 tcp open smtp
继承我的代码
$ip_address = `cat /cygdrive/c/Windows/System32/test11.txt |
grep 'Nmap scan report for'`;
$state = `cat /cygdrive/c/Windows/System32/test11.txt | grep -v 'PORT'|
grep -v 'filtered'| grep -v 'latency'| grep -v 'Nmap' | grep -v 'Discovered' |
grep -v 'Raw' | grep -v 'SYN' | grep -v 'DNS'| grep -v 'Ping' |
grep -v 'Scanning' `;
$port = `cat /cygdrive/c/Windows/System32/test11.txt | grep -v 'Discovered'|
grep -v 'Nmap' | grep -v 'PORT' | grep -v 'ports'| grep -v 'Read' |
grep -v 'Raw'| grep -v 'Completed'| grep -v 'DNS' | grep -v 'hosts' |
grep -v 'Ping' | grep -v 'SYN' | grep -v 'latency' `;
$protocol = `cat /cygdrive/c/Windows/System32/test11.txt | grep -v 'Discovered'|
grep -v 'Nmap' | grep -v 'PORT' | grep -v 'ports'| grep -v 'Read' |
grep -v 'Raw' | grep -v 'Completed'| grep -v 'DNS' | grep -v 'hosts' |
grep -v 'Ping' | grep -v 'SYN' | grep -v 'latency' `;
{
$service = `cat /cygdrive/c/Windows/System32/test11.txt | grep -v 'Nmap' |
grep-v 'Host' | grep -v 'filtered' | grep -v 'PORT' | grep -v 'Raw'|
grep -v 'Scanning'| grep -v 'Completed'| grep -v 'Ping' |grep -v 'DNS' |
grep -v 'Discovered'| grep -v 'SYN'`;
while($ip_address, $port, $protocol, $state, #service)
{
chomp ($ip_address, $port, $protocol, $state, #service);
print "$ip_address, $port, $protocol, $state, #service";
exit 0;
}
答案 0 :(得分:1)
通常我会说使用您理解的工具,并且可以执行从Perl调用awk
之类的操作。但对于这段代码我会做一个例外。您应该使用内置Perl
命令执行此任务。即,数组和Perl的grep
运算符。以下是我将如何开始重写此内容。
# do this once instead of `cat ...` several times.
open my $fh, '<', '/cygdrive/c/Windows/System32/test11.txt';
my @the_input = <$fh>;
close $fh;
# do this instead of `| grep -v ... | grep -v ...`
my @ip_addresses = grep { /Nmap scan report for/ } @the_input;
my @states = grep {
!/PORT|filtered|latency|Nmap|Discovered|Raw|SYN|DNS|Ping|Scanning/
} @the_input;
my @ports = grep {
!/Discovered|Nmap|PORT|ports|Read|Raw|Completed|DNS|hosts|Ping|SYN|latency/
} @the_input;
my @protocols = grep {
!/Discovered|Nmap|PORT|ports|Read|Raw|Completed|DNS|hosts|Ping|SYN|latency/
} @the_input;
my @services = grep {
!/Nmap|Host|filtered|PORT|Raw|Scanning|Completed|Ping|DNS|Discovered|SYN/
} @the_input;
答案 1 :(得分:1)
我通常会尝试一次性完成这些事情,比如......
#!/usr/bin/perl
open(F, "/cygdrive/c/Windows/System32/test11.txt");
while(<F>) {
# If the current line has something that matches an IP
# address, store the matched pattern in $ip. We'll
# use this as we process the remaining lines.
#
$ip = $1 if ( /Nmap scan report for (\d+\.\d+\.\d+\.\d+)/ );
# Try to match lines like "ddd/www www www wwww"
#
( $port, $protocol, $state, $service) = ( m|(\d+)/(\w+)\s+(\w+)\s+(\w+)| );
print "$ip, $port, $protocol, $state, $service\n" if $port;
}