#!/usr/bin/env python #coding:utf-8 import paramiko import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication sender='wei.wan@XXX.cn' smtpserver='smtp.XXX.com' username='wei.wan@XXX.cn' passwd='1234@Abc' msgRoot=MIMEMultipart() subject="MEM INFO" client=paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect('192.168.137.10',22,username='root',password='redhat',timeout=4) stdin,stdout,stderr=client.exec_command('free') content=stdout.read() used=client.exec_command("free|awk 'NR==2{print $0}'|awk '{print $3}'") total=client.exec_command("free|awk 'NR==2{print $0}'|awk '{print $2}'") content2=float(used[1].read())/float(total[1].read()) content2=str(round(content2,4) * 100)+'%' client.close() content=content+'\n'+"Memory usage: "+content2 attachment="E:\\work\\PAD.txt" def sendmail(receiver,subject,content): msgRoot['Subject']=subject msgRoot['From']=sender msgRoot['To']=receiver #添加正文 text=MIMEText(content) msgRoot.attach(text) #添加附件 att=MIMEApplication(open(attachment,'rb').read()) att.add_header('Content-Disposition', 'attachment', filename="foo.txt") msgRoot.attach(att) try: smtp=smtplib.SMTP() smtp.connect('smtp.XXX.com') smtp.login(username,passwd) smtp.sendmail(sender,receiver,msgRoot.as_string()) smtp.quit() return True except Exception,e: print str(e) return False if __name__ == '__main__': if sendmail('wei.wan@XXX.cn',subject,content): print "send successfully" else: print "send failed"