Reputation: 43
I want this:
sojjan pts/9 localhost Thu Oct 13 08:04:14 2016 - Thu Oct 13 08:04:15 2016 (00:00)
gurra pts/9 localhost Wed Oct 12 15:36:00 2016 - Wed Oct 12 15:36:02 2016 (00:00)
sojjan pts/8 :0 Wed Oct 12 10:13:34 2016 still logged in
sojjan pts/7 :0 Mon Oct 10 13:34:56 2016 still logged in
To become like this:
Last 24h SSH logins:
sojjan pts/9 localhost Thu Oct 13 08:04:14 2016 - Thu Oct 13 08:04:15 2016 (00:00)
gurra pts/9 localhost Wed Oct 12 15:36:00 2016 - Wed Oct 12 15:36:02 2016 (00:00)
Still logged in:
sojjan pts/8 :0 Wed Oct 12 10:13:34 2016 still logged in
sojjan pts/7 :0 Mon Oct 10 13:34:56 2016 still logged in
I tried as
#!/bin/bash
test0=$(last -F | grep still)
test1=$(date | awk {'print $2, $3'});
test2=$(date --date='-1 days' | awk {'print $2, $3'});
last -F | grep -v 'reboot' | grep -i "$test0\|$test1\|$test2"
Upvotes: 0
Views: 1156
Reputation: 289745
There is a handy parameter in the last
command:
-t YYYYMMDDHHMMSS
Display the state of logins as of the specified time. This is useful, e.g., to determine easily who was logged in at a particular time -- specify that time with -t and look for "still logged in".
With this, we can get last
command from 24 hours ago and compare it with now using process substitution:
diff <(last) <(last -t "$(date -d"1 day ago" "+%Y%m%d%H%M%S")")
Then, it is a matter of parsing this output, which you can do with awk
:
awk '/still logged in\s*$/ {logged[NR]=$0; next} # store logged
{finished[NR]=$0} # store finished
END {print "Last 24h SSH logins:"; # print header finished
for (i in finished) # print finished
print finished[i];
printf "\nStill logged in:\n"; # print header logged
for (i in logged) # print logged
print logged[i]}'
All together, and as a one-liner, you have something like:
diff <(last) <(last -t "$(date -d"1 day ago" "+%Y%m%d%H%M%S")") | awk '/still logged in\s*$/ {logged[NR]=$0; next} {finished[NR]=$0} END {print "Last 24h SSH logins:"; for (i in finished) print finished[i]; printf "\nStill logged in:\n"; for (i in logged) print logged[i]}'
Upvotes: 3
Reputation: 43
This works well now!
Thanks!
#!/bin/bash
lastday=$(date --date='-1 days' | awk '{ print $2, $3 }'|sed 's/ \([1-9]\)$/ \1/')
echo "lastday $lastday"
echo
echo -e "\nLast 24h SSH logins:"
last -F | grep -v 'reboot' | grep "$lastday" | grep -v "still logged in"
echo -e "\nStill logged in:"
last -F | grep -v 'reboot' | grep "still logged in"
Upvotes: 0
Reputation: 4112
try this;
#!/bin/bash
lastday=$(date --date='-1 days' | awk {'print $2, $3'});
echo -e "Last 24h SSH logins:\n"
last -F | grep -v 'reboot' | grep -i "$lastday"
echo -e "\nStill logged in:\n"
last -F | grep -v 'reboot' | grep -i "still"
Upvotes: 0