Automatic e-mail notification to administrators when users log in to Linux via Python scripts
System Environment CentOS 7
#!/usr/bin/env python
#coding: Utf-8
#导入需要的库, if you do not install it yourself
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 $} '). Read () #获取最后一行的第一列
TTY = Os.popen ("W | awk ' END {print $} '). Read ()
LOGIN_IP = Os.popen ("W | awk ' END {print $} '). 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= "$" border= "1" cellspacing= "0" cellpadding= "5" text-align= "Center" >
<tr>
<td> Login Users </td>
<td> Login Ip</td>
<td> Logon Hours </td>
<td> signed-in shell environment </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 = ' User%s logged in from%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 ("Login Successful")
Except Smtplib. Smtpexception:
Pring ("Error: Login Failed")
After the script is written, the user automatically executes the statement when logged in, which is achieved by changing the configuration file BASHRC
VI ~./BASHRC
! []
The effect of the implementation is as follows
Get login information for Linux system users via Python