如何查找过去24小时内连接到服务器的用户?

时间:2016-10-13 08:07:49

标签: bash unix awk sed grep

我想要这个:

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  

变成这样:

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  

我试过

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

3 个答案:

答案 0 :(得分:3)

last命令中有一个方便的参数:

  

-t YYYYMMDDHHMMSS

     

显示指定时间内的登录状态。这很有用,例如,可以轻松确定在特定时间登录的用户 - 使用-t指定该时间并查找“仍然登录”。

有了这个,我们可以从24小时前获得last命令并使用process substitution与现在进行比较:

diff <(last) <(last -t "$(date -d"1 day ago" "+%Y%m%d%H%M%S")")

然后,这是解析此输出的问题,您可以使用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]}' 

所有这些,作为一个单行,你有类似的东西:

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]}'

答案 1 :(得分:0)

试试这个;

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

答案 2 :(得分:0)

现在效果很好!

谢谢!

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