如何从日志文件中提取IP地址并将其附加到URL?

时间:2017-05-25 07:29:04

标签: bash curl grep

日志文件包含此行。

Nov 28 21:39:25 soft-server sshd[11946]: Accepted password for myusername from 10.0.2.2 port 13494 ssh2

我想仅在日志文件包含字符串“Accepted password for”并将IP地址附加到URL时才运行curl命令。

这样的事情:

if [ grep -q "Accepted password for" var/log/auth.log]
then
    curl 'www.examplestextmessage.com/send-a-message/text=$IP_address'
fi

此外,如何重写上述脚本,该脚本可以检查多个登录并为每个结果运行单独的curl命令?

例如:

11月28日21:35:25 localhost sshd [565]:服务器监听0.0.0.0端口22

11月28日21:39:25软件服务器sshd [11946]:myusername的接受密码 从10.0.2.2端口13494 ssh2

11月28日21:40:25 localhost sshd [565]:服务器监听0.0.0.0端口22

11月28日21:41:25 localhost sshd [565]:服务器监听0.0.0.0端口22

11月21日21:42:25 localhost sshd [565]:服务器监听0.0.0.0端口22

11月21日21:43:25软件服务器sshd [11946]:从10.0.1.1端口13494 ssh2接受myusername的密码

4 个答案:

答案 0 :(得分:0)

grep -oP 'Accepted password for \w+ from\s\K[^ ]+' log.file|while read line;
     do 
     curl "www.examplestextmessage.com/send-a-message/text=$line"
 done

说明:
首先grep将列出包含单词""的接受密码的行中的IP地址。然后将grep结果流送入while loop以将IP地址附加到curl并执行curl。

答案 1 :(得分:0)

带xargs的1行脚本:

grep -oP 'Accepted password for \w+ from\s\K[^ ]+' "/var/log/auth.log" | xargs -I{} -r curl -v -L "www.examplestextmessage.com/send-a-message/text={}"

xarg -r如果标准输入完全为空,请不要运行该命令。默认情况下,即使没有输入,该命令也会运行一次。

xarg -I{}选项更改了新命令行的构建方式。而不是一次添加尽可能多的参数,xargs将从其输入中一次获取一个名称,在此处查找给定的标记({})并将其替换为名称。

答案 2 :(得分:0)

说明:

  1. grep内容“接受的密码”
  2. 从结果集中使用awk / cut
  3. 查找IP地址
  4. 使用IP地址列表作为循环的输入
  5. 下面是代码示例

    for IP_address in  `cat auth.log | grep 'Accepted password for' | awk '{print $11}'`
    do
    curl "www.examplestextmessage.com/send-a-message/text=$IP_address"
    done
    

答案 3 :(得分:0)

完整性的另一个选择是使用-E来配合正则表达式:

sed  -En 's/(^.*Accepted password for )(.*)( from )(.*)( port.*$)/\4/p'

这会将文本分成五个单独的部分,用括号中的数据提取来表示。然后我们专注于第4次提取以获取IP地址