看了阿里云挺多监控开通都需要费用,博主就在服务器简单加个SSH登陆提醒。

创建SSH登陆监测文件’sshrc’

vim /etc/ssh/sshrc

贴入以下内容,记得将邮件发送路径对应起来

#!/bin/bash

#获取登录者的用户名

user=$USER

#获取登录者的IP地址

ip=${SSH_CLIENT%% *}

#获取登录的时间

time=$(date +%F%t%k:%M)

#服务器的IP地址

hostname=$(hostname)

echo "content=$time,$user,$ip,$hostname" > sshmonitor.log

python3 /home/lubaogui/main.py "$time" "$user" "$ip" "$hostname"

创建邮件发送执行文件’main.py’

vim /home/lubaogui/main.py

贴入以下内容,把email账号密码补全

# -*- coding: utf-8 -*-

# @Time : 19-4-9 上午10:10
# @Author : Lu Baogui
# @Email : 15766972573@qq.com
# @File : main.py
# @Software: PyCharm Community Edition


import logging
import sys

from smtplib import SMTP_SSL
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr


mail_info = {
"from": "********@qq.com",
"to": "********@qq.com",
"hostname": "smtp.qq.com",
"username": "********@qq.com",
"password": "*************",
"mail_subject": "test",
"mail_text": "hello, this is a test email, sended by py",
"mail_encoding": "utf-8"
}


def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))


def email_send(dtime,duser,dip,dhostname):
title_text = '服务器SSH登陆通知'
text = '您的机器:',dhostname,',于:',dtime,',被IP:',dip,'以账号',duser,'进行登录,请确认是否为本人操作。'
smtp = SMTP_SSL(mail_info["hostname"])
smtp.set_debuglevel(1)
smtp.ehlo(mail_info["hostname"])
smtp.login(mail_info["username"], mail_info["password"])

from_addr = mail_info["from"]
to_addr = mail_info["to"]

msg = MIMEText(''.join(text), 'plain', 'utf-8')
msg['From'] = _format_addr('告警提示: <%s>' % from_addr)
msg['To'] = _format_addr('主人 <%s>' % to_addr)
msg['Subject'] = Header(title_text, 'utf-8').encode()

smtp.sendmail(from_addr, [to_addr], msg.as_string())
smtp.quit()


if __name__ == "__main__":
email_send(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])