【发布时间】:2021-10-31 01:51:25
【问题描述】:
我需要在 bash 脚本中使用 ipset 命令提取并阻止日志文件中的某个 IP 地址(仅限 IPv4)。日志文件结构如下所示:
[Line 1] random text
[Line 2] random text
...
[Line 26] random text
Aug 31 13:40:14 [logs ] con_accept: [759] connection from 127.0.0.1:56860 is successfull on 0.0.0.0:25000
[Line 28] random text
...
[Line 38] random text
Aug 31 13:40:57 [logs ] _authrequest: [759] random text client connected and the sky is blue today more random text
[Line 40] random text
- 忘记添加每行
[Line 1] ... [Line X以时间戳Aug 31 13:40:14 [logs ] con_accept: [759] connection from 127.0.0.1:56860 is successful on 0.0.0.0:25000开头 - 需要提取和阻止的 IP 地址将显示在与模式匹配的行之前的最后 15 行内。在这种情况下,可以在
Line 27找到。 - 脚本首先搜索
sky is blue字符串 - 找到字符串后,它会在匹配的字符串行之前打印最后一个
15 lines,并提取与[759]匹配的IP地址,即clientID - 为避免误报和错误块,
[ID]必须匹配,在这种情况下,[759]匹配Line 39 and Line 27。clientID不是预定义的数字,所以它会改变。只能是数字。 - IPv4 地址
127.0.0.1将被提取,然后使用ipset add blacklist $IP阻止
到目前为止,我要么使用grep,要么使用awk。在找到模式后检查最后 15 行很容易,但是,我正在尝试进行额外检查并在 string is found 和 clientID 匹配后提取正确的 IP 地址。
awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=15 s="sky is blue" logfile
grep -B 15 'sky is blue' logfile
【问题讨论】: