通过Python 获取Linux系统用户的登录信息

通过Python脚本实现用户登入Linux的时候自动发邮件通知管理员
系统环境CentOS 7

#!/usr/bin/env python
#coding:utf-8

#导入需要的库,如果没有自行安装
import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header

#获取需要的内容
reslut = os.popen("w").read()
Login_User = os.popen("w | awk 'END {print $1}'").read() #获取最后一行的第一列
TTY = os.popen("w | awk 'END {print $2}'").read()
Login_Ip = os.popen("w | awk 'END {print $3}'").read()
Login_Time = os.popen("w | awk 'END {print $4}'").read()
Login_Shell = os.popen("w | awk 'END {print $8}'").read()

#邮箱认证信息

mail_host='smtp.brightunity.com'

mail_user='[email protected]'

mail_pass='XXXXXX'

#发送和接受者
sender = '[email protected]'
receivers = ['[email protected]']

#邮件信息
message = MIMEText("""
<table color="CCCC33" width="800" border="1" cellspacing="0" cellpadding="5" text-align="center">
<tr>
<td>登录用户</td>
<td>登录IP</td>
<td>登录时间</td>
<td>登录的shell环境</td>
</tr>
<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>
</table>""" % (Login_User,Login_Ip,Login_Time,Login_Shell),'HTML','utf-8')
message['from'] = Header('CentOS','utf-8') #发送者显示名称
message['To'] = Header('bin_mail','utf-8') #接收者显示名称

subject = '用户%s从%s登录'%(Login_User,Login_Ip) #邮件主题
message['Subject'] = Header(subject,'utf-8') #定义编码

#发送邮件
try:
smtpObj = smtplib.SMTP('')
smtpObj.connect(mail_host,25)
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender,receivers,message.as_string())
print ("登录成功")
except smtplib.SMTPException:
pring ("Error: 登录失败")

写好脚本之后,用户登录的时候自动执行语句,这里通过更改配置文件 bashrc实现
vi ~./bashrc
通过Python 获取Linux系统用户的登录信息![]

实现的效果如下
通过Python 获取Linux系统用户的登录信息

猜你喜欢

转载自blog.51cto.com/binxing/2126486