user3614385
user3614385

Reputation: 11

Perl - How Do I Pull the Process ID From Security Log

I need to pull the Process ID's (27001) and (28612) for open/closed sessions to compute login time. I am having trouble pulling the Process ID's, the pseudo I am working with

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

My log file:

[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)

Upvotes: 1

Views: 51

Answers (2)

Dim_K
Dim_K

Reputation: 571

You need this code

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

On your input data will be

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

Upvotes: 1

Lee Duhem
Lee Duhem

Reputation: 15121

You could use the following code to extract those process ids:

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

Here is a full testing program:

#!/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)

And output:

$ perl t.pl
27001
28466
28612

Upvotes: 1

Related Questions