最近學習到linux系統日誌和計劃任務,下班回家的地鐵上有了靈感,嘗試編寫了本身的第一個腳本,監測若是有惡意登陸服務器的話,發郵件通知管理員。暫時還沒學習到如何發郵件給管理員,目前只是命令行的提醒和日誌記錄;腳本的內容也比較簡單,都是學習過的基本知識,活學活用。linux
一、首先編寫一個腳本:bash
定義一個變量LT,變量的值爲lastb命令列出的行數(即無效登陸的次數,若有惡意登陸的話行數會變多);服務器
執行一個if判斷語句,若是定義的值大於15次的話,判斷爲惡意登陸,通知管理員。ssh
腳本內容以下:ide
[root@localhost ~]# cat lt.sh #! /bin/bash #定義變量LT,記錄無效登陸的次數; LT=`lastb |wc -l |cut -d ' ' -f 1` if [ $LT -gt "15" ] #判斷無效登陸的次數若是大於15的話,執行下面的操做; then echo "somebody try to login please check log" #打印有人嘗試登陸系統請檢查日誌 fi
二、編寫一個計劃任務學習
每隔一分鐘自動執行上面的腳本ui
[root@localhost ~]# crontab -l */1 * * * * /bin/sh /root/lt.sh
三、查看效果url
超過15次登陸在當前命令行模式會提示,有一封新郵件在/var/spool/mail/root下;spa
[root@localhost ~]# You have new mail in /var/spool/mail/root
查看新郵件,會發現腳本里面的內容,證實有人在嘗試登陸主機;命令行
[root@localhost ~]# tail -2 /var/spool/mail/root somebody try to login please check log
執行lastb命令查看發現不少登陸失敗的記錄
[root@localhost ~]# lastb |head user1 ssh:notty 192.168.22.1 Tue Apr 21 22:04 - 22:04 (00:00) user1 ssh:notty 192.168.22.1 Tue Apr 21 22:04 - 22:04 (00:00) user1 ssh:notty 192.168.22.1 Tue Apr 21 22:03 - 22:03 (00:00) user1 ssh:notty 192.168.22.1 Tue Apr 21 22:03 - 22:03 (00:00) user1 ssh:notty 192.168.22.1 Tue Apr 21 22:03 - 22:03 (00:00) user1 ssh:notty 192.168.22.1 Tue Apr 21 22:03 - 22:03 (00:00) user1 ssh:notty 192.168.22.1 Tue Apr 21 22:03 - 22:03 (00:00) user1 ssh:notty 192.168.22.1 Tue Apr 21 21:29 - 21:29 (00:00) user1 ssh:notty 192.168.22.1 Tue Apr 21 21:29 - 21:29 (00:00) user1 ssh:notty 192.168.22.1 Tue Apr 21 21:29 - 21:29 (00:00)
查看/var/log/secure 日誌也會發現有屢次登陸失敗的記錄
Apr 21 22:03:35 localhost unix_chkpwd[1501]: password check failed for user (user1) Apr 21 22:03:35 localhost sshd[1499]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=192.168.22.1 user=user1 Apr 21 22:03:36 localhost sshd[1499]: Failed password for user1 from 192.168.22.1 port 50591 ssh2 Apr 21 22:03:39 localhost unix_chkpwd[1502]: password check failed for user (user1) Apr 21 22:03:41 localhost sshd[1499]: Failed password for user1 from 192.168.22.1 port 50591 ssh2 Apr 21 22:03:44 localhost unix_chkpwd[1503]: password check failed for user (user1) Apr 21 22:03:46 localhost sshd[1499]: Failed password for user1 from 192.168.22.1 port 50591 ssh2 Apr 21 22:03:49 localhost unix_chkpwd[1504]: password check failed for user (user1) Apr 21 22:03:51 localhost sshd[1499]: Failed password for user1 from 192.168.22.1 port 50591 ssh2 Apr 21 22:03:52 localhost sshd[1499]: Failed password for user1 from 192.168.22.1 port 50591 ssh2 Apr 21 22:03:54 localhost sshd[1500]: Received disconnect from 192.168.22.1: 0:
根據訪問日誌的來源IP,咱們能夠對來源設置iptables規則,禁止訪問服務器的22端口,或者封閉ip地址;
暫時只有這麼多,小小的驕傲一下,給本身增長點自信心,相信以後的學習中會更加深刻了解linux;
和你們分享一下,共勉之。