0

我想筛选文本文件以查找可疑活动。我有点熟悉 bash 脚本,包括 grep、sed 和 awk。我对 stackoverflow.com、tldp.org 等的研究以及与同事的交谈表明 perl 和 python 最适合我的任务,但我对这些脚本语言的经验为零。

欢迎使用各种脚本、编译或解释语言输入。由于我的限制,请在代码中添加注释,使我能够快速理解和学习语言。

好的,任务是对按列排序的项目进行排序和计数。我 / 可以 / 使用 grep、awk 和 sed 完成其中的一部分。不幸的是,递归方面(我认为这个问题)让我很难过。

输入文本已排序,两列 ip 地址(在下面的示例中进行了简化)和一列用于目标端口(所有可能的值)。这个文件的大小可能是几兆字节,但一次可能永远不会超过 250MB,因此不需要绝对的效率。简单是。

SIP        DIP        DPt
111.100    200.150    80
111.100    200.150    443
111.100    200.155    22
111.100    200.155    80
111.100    200.155    443
111.100    200.160    80
111.100    200.165    139
111.100    200.165    443
111.100    200.165    512
115.102    225.150    80
115.102    225.150    137
115.102    225.150    443
120.125    250.175    23
120.135    250.145    23
125.155    250.165    80
125.155    250.165    139
125.155    250.175    1023

我正在工作的代码(从内存中起草......目前不在我的 linux 机器上)类似于这个......

#!/bin/bash

declare -i counter=0
SIP=null       # current source ip.
SIP_last=null  # for last ip address processed.
SIP_next=null  # not found a use for this, yet. 
               # sorting usually reqs three vars, so here it is.

for SIP in `zcat textfile.gz | awk '{ if ($3 <1024) print $1,$2,$3}'` do
# Ensure I count the first item.  This was problematic at first.
if [[ "$SIP_last" == null ]] then
SIP_last=$SIP
counter=counter+1  # counter=+ didn't work reliably.

# Do something useful.  As shown, it works.
if [[ "$SIP" == "$SIP_last" ]] then
counter=counter+1

if [[ "$SIP != "$SIP_last" ]] then
echo SIP: $SIP_last     Counter: $counter   # DIP code has not yet been added.
SIP_last=$SIP

# Ensure I always catch the last item.  Still working on this issue.
# XXX

done

使用上面提供的输入,输出应该看起来像这样......

SIP      DIP Ct   Ports
         > 2      < 1024
111.100  200.150  80, 443
111.100  200.155  20, 80, 443
111.100  200.165  139, 443, 512
115.102  225.150  80, 137, 443

查看输出,您可以看到问题的症结在于仅报告 DIP 计数 > 2 和端口 < 1024。使用提供的 awk 语句将端口限制为 < 1024 非常简单。它将 DIP 与 SIP 匹配,并保持 DPts 的运行记录,这是最重要的。

同样,这是来自记忆,所以请原谅编码错误。感谢你的协助。

艾伦。

4

1 回答 1

1

使用您发布的示例输入文件:

$ awk '
NR==1 { print; next }
$3 < 1024 {
   key = $1 "\t" $2
   if (!seen[key,$3]++) {
      cnt[key]++
      vals[key] = vals[key] sep[key] $3
      sep[key] = ", "
   }
}
END { for (key in cnt) if (cnt[key] > 1) print key "\t" vals[key] }
' file
SIP        DIP        DPt
111.100 200.155 22, 80, 443
111.100 200.165 139, 443, 512
125.155 250.165 80, 139
115.102 225.150 80, 137, 443
111.100 200.150 80, 443

如果这不是你要找的,请澄清。

于 2013-02-26T02:20:04.223 回答