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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过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系统用户的登录信息的主要内容,如果未能解决你的问题,请参考以下文章

Linux通过什么命令可以查看有多少个用户登录?

Python获取Linux或Windows系统的基本信息

linux系统:查看当前登录用户的信息,本文介绍3种方法

Linux下用于查看系统当前登录用户信息的4种方法

Linux下用于查看系统当前登录用户信息的4种方法

如何设置用户登录后的欢迎信息?