我有一个shell脚本,它搜索身份验证失败。例如,如果给定文件包含以下行:

Mar 19 15:54:18 precise3 sshd[16516]: Failed password for lotte from 127.0.0.1 port 47384 ssh2

shell脚本将找到它并将结果写入一个单独的文件中,如下所示:
date: date    username: username    client IP: ip-address

现在我有了发现身份验证失败的脚本,但是如何将失败中的数据写入文件?脚本本身是:
#!/bin/bash
if egrep "sshd\[[0-9]+\]: Failed password for \w+ from [0-9.]+ port [0-9]+ ssh2$" /var/log/auth.log
then
    echo "date: date    username: username    client IP: ip-address" > /root/failedauth
else
    echo "No failed authentications found."
fi

最佳答案

使用awk:

awk '/Failed password/ {print "Date: "$1" "$2" "$3"\tUsername: "$9"\t\tClient IP: "$11 }' /var/log/auth.log >> /root/failedauth

上面只需找到所有失败的身份验证尝试并将其登录到/root/failed auth-如果希望在没有结果的情况下回显一行,可以执行以下操作:
failures=$(awk '/Failed password/ {print "Date: "$1" "$2" "$3"\tUsername: "$9"\t\tClient IP: "$11 }' /var/log/auth.log)
test -n "$failures" && echo "$failures" >> /root/failedauth || echo "No failed auths found"

关于linux - 在Shell脚本中执行grep搜索得到的回显结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22298623/

10-11 19:37
查看更多