天天看點

python擷取本地IP位址發送郵件

#!/usr/bin/env python

#_*_coding:utf-8 _*_

import time

import socket

import fcntl

import struct

import smtplib

from email.mime.text import MIMEText

def get_ip_add(ifname):

        s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

        return socket.inet_ntoa(fcntl.ioctl(

                s.fileno(),

                0x8915,

                struct.pack('256s',ifname[:15])

        )[20:24])

def sendmail(subject,msg,fromemail,emailpasswd,toemail):

        user=fromemail

        pwd=emailpasswd

        to=toemail

        nowtime=time.strftime('%Y-%m-%d %H:%M:%S')

        msg=MIMEText(msg)

        msg["Subject"]=subject

        msg["From"]=user

        msg["To"]=to

        try:

                #s=smtplib.SMTP_SSL('smtp.qq.com',465)

                s=smtplib.SMTP('smtp.126.com',25)#連接配接126服務端

                s.login(user,pwd)

                s.sendmail(user,to,msg.as_string())

                s.quit()

                print "[%s]INFO:Email send Success!"% nowtime

        except smtplib.SMTPException,e:

                print "[%s]ERROR:Email send Faild,%s"%(nowtime,e)

if __name__=='__main__':

        local_id=get_ip_add('em1')

        print local_id

        subject='伺服器[%s]日志報警了!'%local_id#可以根據實際定義

        fromemail='[email protected]'

        emailpasswd='xxxxx'##這裡的密碼是用戶端的授權碼,不是126的登入密碼

        toemail='[email protected]'#發給誰

        name_1="This is tesing"

        sendmail(subject,name_1,fromemail,emailpasswd,toemail)#name_1可以根據實際的需求寫對應的内容

本文轉自 DBAspace 51CTO部落格,原文連結:http://blog.51cto.com/dbaspace/1877807