ELK --- Grok正则过滤Linux系统登录日志

说明:

Linux系统登录日志为/var/log/secure,一次登录会输出打印一下信息:

登录成功:

Jan  6 17:11:47 localhost sshd[3324]: Received disconnect from 172.16.0.13: 11: disconnected by user
Jan  6 17:11:47 localhost sshd[3324]: pam_unix(sshd:session): session closed for user root
Jan  6 17:11:48 localhost sshd[3358]: Address 172.16.0.13 maps to localhost, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!
Jan  6 17:11:51 localhost sshd[3358]: Accepted password for root from 172.16.0.13 port 38604 ssh2
Jan  6 17:11:51 localhost sshd[3358]: pam_unix(sshd:session): session opened for user root by (uid=0)

登录失败:

Jan  6 17:13:10 localhost sshd[3380]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=172.16.0.39  user=root
Jan  6 17:13:12 localhost sshd[3380]: Failed password for root from 172.16.0.39 port 58481 ssh2

以上信息中我们只用通过一下两条判断登录成功或失败

Jan  6 17:11:51 localhost sshd[3358]: Accepted password for root from 172.16.0.13 port 38604 ssh2
或者
Jan  6 17:13:12 localhost sshd[3380]: Failed password for root from 172.16.0.39 port 58481 ssh2

logstash配置

input {
    file {
        path => "/var/log/secure"
    }
}

filter {
    grok {
        match => {
            "message" => ".* sshd\[\d+\]: (?\S+) .* (?(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?) .*"
        }
        overwrite => ["message"]
    }
}

output {
    if [ClientIP] =~ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ and ([status] == "Accepted" or [status] == "Failed") {
        elasticsearch {
            hosts => "172.16.11.199"
            index => "logstash-%{+YYYY.MM.dd}"
        }
    }
}

配置解释:

  • input插件使用file读取日志文件
  • filter插件使用grok来匹配相应的日志行
    1. message中定义了两个Fields,分别匹配登录来源IP,和登录状态
    2. overwrite表示重写message行
  • output插件指定将过滤出来的信息输出到哪个地方,这里输出到elasticsearch
    1. 一个条件判断,判断filter中定义的两个fields是否匹配,如果匹配则输出到elasticsearch中,如果不匹配则不操作

正则解释

Jan  6 17:11:51 localhost sshd[3358]: Accepted password for root from 172.16.0.13 port 38604 ssh2

ClinentIP:

  • .* 匹配 Jan 6 17:11:51 localhost

  • sshd\[\d+\]:sshd[3358]: 段,\d+匹配多个数字

  • (?\S+):

    1. (?正则表达式):定义一个xxx字段匹配后面正则表达式,类似{xxx:匹配的结果},在上面output中的条件判断即可使用该字段来使用匹配到的结果
    2. \S+表示多个字符串,也就是匹配Accepted或Failed
  • (?(?:\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})?)

    1. 先定义一个ClientIP字段
    2. (?:...)? 表示匹配一个ip但不保存供以后引用,如果(...)则以后可以使用$1来调用匹配到的值,最后一个?表示非贪婪匹配,尽可能少的匹配

kibana配置用户登录成功失败条形图

ELK --- Grok正则过滤Linux系统登录日志_第1张图片

ELK --- Grok正则过滤Linux系统登录日志_第2张图片

ELK --- Grok正则过滤Linux系统登录日志_第3张图片

你可能感兴趣的:(ELK --- Grok正则过滤Linux系统登录日志)