centos7 用shell对系统用户登录进行监控预警

1.监听用户登录的shell代码

有时候由于系统运维的需要,当有人登录服务器的时候,需要立马提醒运维的相关人员,并且给登录人员一个预警信息,让他知道他的登录行为是被监视的。
下面是样例代码scanLogin.sh

#!/bin/sh

function listlogin(){
var=`env LC_ALL=en_US.en date +"%b %e"` && last | grep "${var}" | grep "still logged in" > /tmp/new.log
loginUserNum=`diff -y  /tmp/new.log /tmp/old.log | egrep "<" -c`
loginOutNum=`diff -y  /tmp/new.log /tmp/old.log | egrep ">" -c`
now_date_str=`date +"%Y%m%d%H%M%S"`
message_file="/tmp/login"$now_date_str".txt"
wx_sender="yuanxuan"
server_ip=`ifconfig | egrep "^em|^ens|^eno|^enp|^br[0-9]" -A2 | grep "inet " | awk '{print $2}' | tr "\n" "|"`

if [ $loginUserNum -gt "0" ] ; then
  echo $wx_sender > $message_file
  echo "Server "$server_ip" now login " >> $message_file
  diff -y  /tmp/new.log /tmp/old.log | egrep "<" >> $message_file
  send_user=`diff -y  /tmp/new.log /tmp/old.log | grep "<" | awk '{print $1" "$2}'` && echo "Hello, your login has been monitored and the administrator will contact you promptly" | write ${send_user}
fi

if [ $loginOutNum -gt "0" ] ; then
   echo $wx_sender > $message_file
   echo "Server "$server_ip" now logout " >> $message_file
   diff -y  /tmp/new.log /tmp/old.log | egrep ">" >> $message_file
fi
/usr/bin/cp -f /tmp/new.log /tmp/old.log
curl -u "test:test123" -vT $message_file http://10.10.55.135:88/wxmessage/
rm -f $message_file
}

while true ; do listlogin ; sleep 3 ; done

其中http://10.10.55.135:88/wxmessage/地址是一个webdav地址,当有人登录时,把该用户的信息生成一个文本,发往webdav目录保存,这个消息文本随后会被企业微信发送程序发到相关运维管理人员。
当有人登录,登录者本人会收到这样一条信息
在这里插入图片描述
但是运维管理人员会收到这样一条企业微信

2.作为系统常驻服务运行

把上面的监听代码作为一个常驻服务放入系统scanLogin.service

[Unit]
# 描述,随你怎么写
Description=Scan User Login Status
After=network.target

# 这里是关键
[Service]
# 后台运行模式,服务类型,具体可以自行百度,设置成自己想要的
#Type=simple
# 所属用户
User=root
# 所属组
Group=root
# 重启
#Restart=always
TimeoutSec=0
# 配置重新启动服务之前的睡眠时间,重启频率,比如某次异常后,等待5(s)再进行启动,默认值0.1(s)
RestartSec=1
# 这是服务运行的具体执行命令,可执行执行脚本的绝对路径,即对应的service start/stop/reload
ExecStart=/etc/init.d/scanLogin.sh 1>/dev/null 2>&1 &
ExecStop=ps -ef | grep "scanLogin.sh" | grep "grep" -v | awk '{print $2}' | xargs kill -9 && exit 0
[Install]
WantedBy=multi-user.target

然后把文件拷贝到相应目录

chmod 755 scanLogin.service
chmod 755 scanLogin.sh
/usr/bin/mv scanLogin.sh /etc/init.d/
/usr/bin/mv scanLogin.service /etc/systemd/system/
systemctl daemon-reload
systemctl start scanLogin.service
systemctl status scanLogin.service
systemctl enable scanLogin.service

这样整个服务就运行起来了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

机核动力

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值