MMonteza
MMonteza

Reputation: 33

Print Date and Username from a secure log file

I'm trying to get the Username and Date 'y/m/d' from a /var/log/secure, however when I'm trying to use awk, it only provides the date.

Sample of a secure log file.

2022-11-23T02:03:24.594880+01:00 servername su: pam_unix(su:session): session opened for user john.doe by (uid=0)

What I'm expecting to print is: 2022-11-23 john.doe

Here's my code.

cat /var/log/secure | grep 'session opened' | awk -FT '{print $1 " " " User: " $9 }'

"The output is only: 2022-11-23 User:"

Upvotes: 3

Views: 299

Answers (4)

The fourth bird
The fourth bird

Reputation: 163577

You use the T char as the field separator.

That gives you 2 fields where field 1 is 2022-11-23 and after that you print User:


What you might do is use either 1 or more spaces or T as a field separator and then print field 1 and field 10:

 awk -F"[[:blank:]]+|T" '{print $1, $10 }' file

Another option could be splitting the first field on T instead of the whole line and then print the first part followed by field 9:

awk '{split($1,a,"T"); print a[1], $9}'

Or matching the date like pattern followed by a T and then print the match without the T followed by field 9:

awk 'match($0, /^[0-9]{4}(-[0-9]{2}){2}T/) {
  print substr($0,RSTART,RLENGTH-1), $9
}'

Output

2022-11-23 john.doe

Upvotes: 3

Ed Morton
Ed Morton

Reputation: 204478

No need for cat or grep:

$ awk '/session opened/{print substr($0,1,10), $9}' /var/log/secure
2022-11-23 john.doe

You never need grep when you're using awk. grep 'session opened' | awk '{foo}' = awk '/session opened/{foo}', and you never need cat just to open a file, see https://porkmail.org/era/unix/award.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133750

With your shown samples please try following awk code.

awk -F'T| user | by '  '{print $1,$3}' Input_file

Upvotes: 2

Jetchisel
Jetchisel

Reputation: 7831

With the assumption that the date always comes first and the username is in between the strings user and by A sed solution would be something like:

sed '/session opened/s/^\([^T]*\).* user \(.*\) by .*$/\1 \2/' /var/log/secure

Upvotes: 1

Related Questions