2016-10-13 41 views
0

我想這一點:如何查找過去24小時內連接到服務器的用戶?

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" 

回答

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" 
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]}' 
+0

謝謝穆斯塔法和fedorqui。我對此很新。 –

+0

但我不知道如何將這些信息提供給工作腳本。 heee –

+0

@Larsvontrierpung然後你必須自己做一些研究。我們不是在這裏爲你餵食,而是爲了幫助。試試看,回來後回答具體問題。 – fedorqui

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" 
+0

你知不知道你可以使用'date'+ ... ...「'有你想要的日期格式,而不是解析其默認輸出?看到我的答案。 – fedorqui

相關問題