Perl - 如何从安全日志中提取进程ID

时间:2014-05-08 01:11:59

标签: perl pid

我需要为开放/关闭会话提取进程ID(27001)和(28612)来计算登录时间。我无法提取进程ID,我正在使用伪

if (the input line has "session" and "opened")
    $processID = <get process ID>;
    $openTime{$processID} = set epoch

我的日志文件:

[user test]$ cat /var/log | grep session
May  7 17:37:55 test sshd[27001]: pam_unix(sshd:session): session opened for user user by (uid=0)
May  7 18:19:07 test sshd[27001]: pam_unix(sshd:session): session closed for user user
May  7 18:26:56 test sshd[28466]: pam_unix(sshd:session): session opened for user user by (uid=0)
May  7 18:28:11 test sshd[28612]: pam_unix(sshd:session): session opened for user user by (uid=0)

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码来提取这些流程ID:

if (m/\[(\d+)\] .* session .* opened/x) {
    say "$1";
}

这是一个完整的测试程序:

#!/usr/bin/perl

use strict;
use warnings;

use feature qw(switch say);

use Data::Dumper;

while (<DATA>) {
    chomp;
    if (m/\[(\d+)\] .* session .* opened/x) {
        say "$1";
    }
}

__DATA__
May  7 17:37:55 test sshd[27001]: pam_unix(sshd:session): session opened for user user by (uid=0)
May  7 18:19:07 test sshd[27001]: pam_unix(sshd:session): session closed for user user
May  7 18:26:56 test sshd[28466]: pam_unix(sshd:session): session opened for user user by (uid=0)
May  7 18:28:11 test sshd[28612]: pam_unix(sshd:session): session opened for user user by (uid=0)

输出:

$ perl t.pl
27001
28466
28612

答案 1 :(得分:1)

您需要此代码

if ( /session opened/ ) {
   my ( $processID ) = /sshd\[(\d+)\]/;
   ( $openTime{ $processID } ) = /^(.*?\d+:\d+:\d+)/;
}

输入数据将

   '28612' => 'May  7 18:28:11',
   '27001' => 'May  7 17:37:55',
   '28466' => 'May  7 18:26:56'