歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux 利用wtmp 日志記錄並分析用戶登陸統計

Linux 利用wtmp 日志記錄並分析用戶登陸統計

日期:2017/3/1 9:48:02   编辑:Linux編程

1.在linux /var/log/wtmp 日志中以二進制的形式記錄了用戶登陸的時間和登陸IP,用who 命令可以查看
who /var/log/wtmp

mtpt pts/0 2014-02-07 08:43 (192.168.0.5)
yunji pts/0 2014-02-08 09:29 (192.168.0.8)
langshi pts/1 2014-02-08 10:54 (192.168.0.7)
fanghui pts/0 2014-02-10 09:07 (192.168.0.11)
2.通過shell腳本可以分析出用戶名,登陸時間,次數以及登陸ip
以html 格式輸出,代碼如下
#!/bin/bash
dt=$( date -dlast-day +%Y-%m-%d )
mkdir -p /usr/local/src/shellcode
u=('echo"$@"')
t=('echo"$@"')
i=('echo"$@"')
ur=('echo"$@"')
ti=('echo"$@"')
ip=('echo"$@"')
ci=('echo"$@"')
s=0
df=$(who /var/log/wtmp |grep "$dt"|awk ' { print $1 } '|sort |uniq|wc -l) #不同用戶的個數
touch /usr/local/src/shellcode/ti.txt
touch /usr/local/src/shellcode/ip.txt
getUsermessage()
{
who /var/log/wtmp |grep "$dt" > /usr/local/src/shellcode/userlist
m=0
while read line
do
u[$m]=$( echo $line |awk ' { print $1 } ' )
t[$m]=$( echo $line |awk ' { print $4 } ' )
i[$m]=$( echo $line |awk '{ print $5 } '| sed -n "s/(//p"|sed -n "s/)//p" )
m=$[ $m + 1 ]
done < /usr/local/src/shellcode/userlist
}


getusername()
{
who /var/log/wtmp |grep "$dt"|awk ' { print $1 } ' |sort|uniq >/usr/local/src/shellcode/users
cat>/usr/local/src/shellcode/report.html<<eof
<table border="1">
<tr>
<th>序號</th>
<th>時間</th>
<th>用戶</th>
<th>登陸次數</th>
<th>登陸時間</th>
<th>登陸地址</th>
</tr>
eof
while read line
do
num=0
tm=0
pi=0
cat /dev/null > /usr/local/src/shellcode/ti.txt
cat /dev/null > /usr/local/src/shellcode/ip.txt
for (( n=0;n<${#u[@]}; n++ ))
do
usr=${u[$n]}
if [ "$line" = "$usr" ]
then
let num++
echo ${t[$n]}>> /usr/local/src/shellcode/ti.txt
echo ${i[$n]}>> /usr/local/src/shellcode/ip.txt
fi
done
ci[$s]=$num
ur[$s]=$line
echo ${ur[$s]}
echo ${ci[$s]}
while read line


do


tm+=$line+


done</usr/local/src/shellcode/ti.txt


ti[$s]=$tm
echo "hello ${ti[$s]}"
cat /dev/null >/usr/local/src/shellcode/ti.txt
while read line
do
pi+=$line+
done < /usr/local/src/shellcode/ip.txt
ip[$s]=$pi
echo "hello ${ip[$s]}"
cat >>/usr/local/src/shellcode/report.html<<eof
<tr>
<td>$s</td>
<td>$dt</td>
<td>${ur[$s]}</td>
<td>${ci[$s]}</td>
<td>${ti[$s]}</td>
<td>${ip[$s]}</td>


</tr>
eof
let s++


done < /usr/local/src/shellcode/users
cat >>/usr/local/src/shellcode/report.html <<here
</table>
here


}


report()
{
i=0
cat>/usr/local/src/shellcode/report.html<<eof
<table border="1">
<tr>
<th>序號</th>
<th>時間</th>
<th>用戶</th>
<th>登陸次數</th>
<th>登陸時間</th>
<th>登陸地址</th>
</tr>"
eof


for (( ;i<$df; i++ ))
do
echo $i
echo ${ur[$i]}
cat >>/usr/local/src/shellcode/report.html<<eof
<tr>
<td>$i</td>


<td>2013-11-27</td>


<td>${ur[$i]}</td>


<td>${ci[$i]}</td>
<td>${ti[$i]}</td>
<td>${ip[$i]}</td>


</tr>
eof


done
cat >>/usr/local/src/shellcode/report.html <<here
</table>
here


}


getUsermessage


getusername


sed -i "s/+/;/g" /usr/local/src/shellcode/report.html

Copyright © Linux教程網 All Rights Reserved