Get login information for Linux system users via Python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.