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
这样整个服务就运行起来了。