运维实现自动化数据提取邮件发送

运维做了一段时间了,发现很多事情都是重复的,可以写成脚本代替每天重复无聊没意义的事情,这样就有时间研究更有意义的东西了

使用的ptyhon3.6

代码很简单,分两部分,

一部分是数据库查询结果生成exel

一部分是邮件发送

可以在本地跑,没问题放到服务器定时任务天天跑

# encoding=utf-8
import xlwt
import pymysql


class MYSQL:
    def __init__(self):
        pass

    def __del__(self):
        self._cursor.close()
        self._connect.close()

    def connectDB(self):
        """
        连接数据库
        :return:
        """
        try:
            self._connect = pymysql.Connect(
                host='*****',
                port=*******,
                user='******',
                passwd='*******',
                db='*******',
                charset='utf8'
            )

            return 0
        except:
            return -1

    def export(self, output_path):
        self._cursor = self._connect.cursor()
        # 查询数据库要查询的数据
        count = self._cursor.execute("select * from test")

        print(count)
        # 重置游标的位置
        self._cursor.scroll(0, mode='absolute')
        # 搜取所有结果
        results = self._cursor.fetchall()

        # 获取MYSQL里面的数据字段名称
        fields = self._cursor.description
        workbook = xlwt.Workbook()

        sheet = workbook.add_sheet('table', cell_overwrite_ok=True)

        # 写上字段信息
        for field in range(0, len(fields)):
            sheet.write(0, field, fields[field][0])

        # 获取并写入数据段信息
        row = 1
        col = 0
        for row in range(1, len(results)+1):
            for col in range(0, len(fields)):
                sheet.write(row, col, u'%s' % results[row-1][col])
        workbook.save(output_path)


if __name__ == '__main__':
    mysql = MYSQL()
    flag = mysql.connectDB()
    if flag == -1:
        print('数据库连接失败')
    else:
        print('数据库连接成功')
        mysql.export('D:\\Python\\exel\\houtaitousu.xls')






import yagmail

username = '*******@qq.com'#邮箱账号
passwd = '*********'#授权码,不是邮箱密码
mail = yagmail.SMTP(user=username,
                    password=passwd,
                    host='smtp.qq.com',#其他服务器就smtp.qq.com  smtp.126.com
                    # smtp_ssl=True
                    ) #如果用的是qq邮箱或者你们公司的邮箱使用是安全协议的话,必须写上 smtp_ssl=True
# mail.send(
#     to=['*****@qq.com','*****@qq.com'], #如果多个收件人的话,写成list就行了,如果只是一个账号,就直接写字符串就行to='[email protected]'
#     cc='******@qq.com',#抄送
#     subject='邮件标题',#邮件标题
#     contents='邮件正文',#邮件正文
#     attachments=[r'C:\a.txt',
#                  r'C:\b.txt'])#附件如果只有一个的话,用字符串就行

mail.send(
    to=['****@qq.com'], 
    cc=['****@qq.com','***@chinaunicom.cn','***@chinaunicom.cn'], 
    subject='后台投诉',
    contents='''
    您好
        后台投诉,详见附件
        



    ------------------
    username:***

    phone_number:*****
    email: ********@qq.com
    ''',#邮件正文
    attachments=['D:\\Python\\exel\\houtaitousu.xls']
)

print('邮件发送成功')

猜你喜欢

转载自www.cnblogs.com/yuhudashen/p/10612958.html