I need to extract authorization data from the auth.log file. I also need to format this data so that it is easy to view. In my case, it is several columns: Date Time User Action IP.
I already have a part of the code, to be more precise, I can get the data for the last 3 hours, but I have problems with formatting.
I will be very grateful for your help!
#!/bin/bash
LOG_FILE="/var/log/auth.log"
OUTPUT_FILE="/home/phantaserrr/Script/auth_log_report.txt"
current_time=$(date +%s)
time_threshold=$((current_time - 3 * 3600))
time_threshold_formatted=$(date -d @$time_threshold +"%Y-%m-%dT%H:%M:%S")
awk -v threshold="$time_threshold_formatted" '
/polkitd|gdm-launch-environment/ {
split($1, date, "T");
split(date[1], ymd, "-");
split($2, time, "+");
user = $5;
action = $0;
if (match($0, /rhost=([0-9]+.[0-9]+.[0-9]+.[0-9]+)/, arr)) {
ip = arr[1];
} else {
ip = "unknown";
}
if (action ~ /session opened/ || action ~ /session closed/ || action ~ /logged out/) {
# Clean up action string
sub(/[.*] /, "", action);
print ymd[1] "-" ymd[2] "-" ymd[3], time[1], user, action, ip;
}
}
' "$LOG_FILE" > "$OUTPUT_FILE"
When I try to execute this script, I get the following errors
awk: line 11: syntax error at or near ,
awk: line 13: syntax error at or near else
awk: line 17: syntax error at or near if
awk: line 22: syntax error at or near }
Here is an example of a log file format
2024-08-03T16:31:12.232218+03:00 phantaserrr-VM gnome-keyring-daemon[2015]: The PKCS#11 component was already initialized
2024-08-03T16:31:12.233818+03:00 phantaserrr-VM gnome-keyring-daemon[2225]: discover_other_daemon: 1
2024-08-03T16:31:12.250473+03:00 phantaserrr-VM gnome-keyring-daemon[2227]: discover_other_daemon: 1
2024-08-03T16:31:12.250567+03:00 phantaserrr-VM gnome-keyring-daemon[2015]: The Secret Service was already initialized
2024-08-03T16:31:12.251861+03:00 phantaserrr-VM gnome-keyring-daemon[2230]: discover_other_daemon: 1
2024-08-03T16:31:16.130923+03:00 phantaserrr-VM polkitd[730]: Registered Authentication Agent for unix-session:2 (system bus name :1.79 [/usr/bin/gnome-shell], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale en_US.UTF-8)
2024-08-03T16:31:17.631108+03:00 phantaserrr-VM gdm-launch-environment]: pam_unix(gdm-launch-environment:session): session closed for user gdm
phantaserrr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.