Linux 利用wtmp 日志记录并分析用户登陆统计
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