1. 程式人生 > >通過Python 獲取Linux系統用戶的登錄信息

通過Python 獲取Linux系統用戶的登錄信息

linux CentOS Python

通過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系統用戶的登錄信息