Python监控系统信息、巡检数据库将结果写入到html,并定时发送邮件到邮箱

1、编写jinja2模板




    Oracle中查询数据
    



系统信息:

{ % for key,value in mInfo.items() %}{ % endfor %}
MemoryInfo
totalMem freeMem avaMem
{ { value }}
{ % for key in cpuInfo.keys() %}{ % endfor %}{ % for value in cpuInfo.values() %}{ % endfor %}
CPUInfo
{ { key }}
{ { value }}
{ % for key,value in dInfo.items() %}{ % endfor %}
DiskInfo
MountName Total Used Free Percent
{ { key }} { { value.total }} { { value.used }} { { value.free }} { { value.percent }}

Oracle数据库巡检:

{ % for etl in emp_title_list %}{ % endfor %}{ % for row in results %}{ % endfor %}
监控数据库表空间使用情况
{ { etl }}
{ { row[0] }} { { row[1] }} { { row[2] }} { { row[3] }} { { row[4] }} { { row[5] }} { { row[6] }}

2、创建Python脚本

import psutil
import os
from jinja2 import Environment,FileSystemLoader
import webbrowser
import cx_Oracle

"""Monitor Memory"""
def monMem():

    memInfo = psutil.virtual_memory()
    totalMem = str(round(memInfo.total/1024/1024,2)) + 'M'
    freeMem = str(round(memInfo.free/1024/1024,2)) + 'M'
    avaMem = str(round(memInfo.available/1024/1024,2)) + 'M'

    mInfo = {
     }
    mInfo['totalMem'] = totalMem
    mInfo['freeMem'] = freeMem
    mInfo['avaMem'] = avaMem

	"""这里区分下不同平台的情况"""
    if os.name == 'posix':
        bufMem = memInfo.buffers
        cachedMem = memInfo.cached

        mInfo['bufMem'] = bufMem
        mInfo['cachedMem'] = cachedMem

    return mInfo

"""Monitor CPU"""
def monCpu():
    physical_cpu_count = psutil.cpu_count(logical=False)
    logical_cpu_count = psutil.cpu_count()
    use_cpu_percent = psutil.cpu_percent(interval=1)

    cpuInfo = {
     }

    cpuInfo['physical_cpu_count'] = physical_cpu_count
    cpuInfo['logical_cpu_count'] = logical_cpu_count
    cpuInfo['use_cpu_percent'] = use_cpu_percent

    return cpuInfo


"""Monitor Disk"""
def monDisk():
    # select partiton of disk
    diskInfo = psutil.disk_partitions()

    mountPoint = []
    for disk in diskInfo:
        mountPoint.append(disk.mountpoint)
    # print(mountPoint)

    dInfo = {
     }
    for mp in mountPoint:
        print(mp + "'s usage info is: ")
        print("\t Total: \t" + str(psutil.disk_usage(mp).total))
        print("\t Used: \t\t" + str(psutil.disk_usage(mp).used))
        print("\t Free: \t\t" + str(psutil.disk_usage(mp).free))
        print("\t Percent: \t" + str(psutil.disk_usage(mp).percent) + "%")

        dInfo[mp] = {
     
            'total' : str(round(psutil.disk_usage(mp).total/1024/1024,2)) + 'M',
            'used' : str(round(psutil.disk_usage(mp).used/1024/1024,2)) + 'M',
            'free' : str(round(psutil.disk_usage(mp).free/1024/1024,2)) + 'M',
            'percent' : str(psutil.disk_usage(mp).percent) + '%'
        }

    return dInfo

"""select data from oracle"""
def getResults():
    conn = cx_Oracle.connect('scott/scott@TNS_LISSEN')
    cursor = conn.cursor()

    selectSql = """select  a.tablespace_name,
        a.file_id,
        round(a.free/1024/1024,2) || 'M' as "free_size",
        b.total/1024/1024 || 'M' as "total_size",
        round(b.maxbytes/1024/1024,2) || 'M' as "can_max_auto_allocated_size",
        round(((b.total-a.free)/total)*100,2) || '%' as "used_percent",
        round(((b.maxbytes-b.total)/b.maxbytes)*100,2) || '%' as "can_auto_allocated_percent"
from
(select tablespace_name,file_id,sum(bytes) as free
        from dba_free_space group by tablespace_name,file_id) a,
(select tablespace_name,file_id,sum(bytes) as total,maxbytes
        from dba_data_files
        group by tablespace_name,file_id,maxbytes) b
where a.file_id = b.file_id
order by file_id"""
    cursor.execute(selectSql)
    results = []
    emp_title_list = []

    for desc in cursor.description:
        emp_title_list.append(desc[0])
    results.append(emp_title_list)

    result = cursor.fetchall()
    results.append(result)

    cursor.close()
    conn.close()

    return results

"""获取网页内容函数"""
def render(tplPath,**kwargs):
    path,fileName = os.path.split(tplPath)
    template = Environment(loader=FileSystemLoader(path)).get_template(fileName)
    content = template.render(**kwargs)

    return content

def getContent():
    emp_title_list = getResults()[0]
    emp = 'emp'
    results = getResults()[1]
    mInfo = monMem()
    cpuInfo = monCpu()
    dInfo = monDisk()

    return render('Test.html',**locals())

"""show web immediate"""
def showWeb():
    html = 'testJinja2.html'

    with open(html,'w') as fObj:
        fObj.write(getContent())
        fObj.close()

    webbrowser.open(html,new=1)

if __name__ == '__main__':
   # print(monMem())
   # print(monCpu())
   # print(monDisk())
	showWeb()

运行脚本查看web显示情况:
Python监控系统信息、巡检数据库将结果写入到html,并定时发送邮件到邮箱_第1张图片

这里的巡检脚本比较简单,只做示例…

3、添加发送邮件函数

import psutil
import os
from jinja2 import Environment,FileSystemLoader
import webbrowser
import cx_Oracle
import yagmail
import smtplib
from email.mime.text import MIMEText


"""Monitor Memory"""
def monMem():

    memInfo = psutil.virtual_memory()
    totalMem = str(round(memInfo.total/1024/1024,2)) + 'M'
    freeMem = str(round(memInfo.free/1024/1024,2)) + 'M'
    avaMem = str(round(memInfo.available/1024/1024,2)) + 'M'

    mInfo = {
     }
    mInfo['totalMem'] = totalMem
    mInfo['freeMem'] = freeMem
    mInfo['avaMem'] = avaMem

    if os.name == 'posix':
        bufMem = memInfo.buffers
        cachedMem = memInfo.cached

        mInfo['bufMem'] = bufMem
        mInfo['cachedMem'] = cachedMem

    return mInfo

# 监控CPU
def monCpu():
    physical_cpu_count = psutil.cpu_count(logical=False)
    logical_cpu_count = psutil.cpu_count()
    use_cpu_percent = psutil.cpu_percent(interval=1)

    cpuInfo = {
     }

    cpuInfo['physical_cpu_count'] = physical_cpu_count
    cpuInfo['logical_cpu_count'] = logical_cpu_count
    cpuInfo['use_cpu_percent'] = use_cpu_percent

    return cpuInfo


# 监控磁盘
def monDisk():
    # select partiton of disk
    diskInfo = psutil.disk_partitions()

    mountPoint = []
    for disk in diskInfo:
        mountPoint.append(disk.mountpoint)
    # print(mountPoint)

    dInfo = {
     }
    for mp in mountPoint:
        """
        print(mp + "'s usage info is: ")
        print("\t Total: \t" + str(psutil.disk_usage(mp).total))
        print("\t Used: \t\t" + str(psutil.disk_usage(mp).used))
        print("\t Free: \t\t" + str(psutil.disk_usage(mp).free))
        print("\t Percent: \t" + str(psutil.disk_usage(mp).percent) + "%")"""

        dInfo[mp] = {
     
            'total' : str(round(psutil.disk_usage(mp).total/1024/1024,2)) + 'M',
            'used' : str(round(psutil.disk_usage(mp).used/1024/1024,2)) + 'M',
            'free' : str(round(psutil.disk_usage(mp).free/1024/1024,2)) + 'M',
            'percent' : str(psutil.disk_usage(mp).percent) + '%'
        }

    return dInfo

def getResults():
    conn = cx_Oracle.connect('scott/scott@TNS_LISSEN')
    cursor = conn.cursor()

	"""查看表空间使用信息sql"""
    selectSql = """select  a.tablespace_name,
        a.file_id,
        round(a.free/1024/1024,2) || 'M' as "free_size",
        b.total/1024/1024 || 'M' as "total_size",
        round(b.maxbytes/1024/1024,2) || 'M' as "can_max_auto_allocated_size",
        round(((b.total-a.free)/total)*100,2) || '%' as "used_percent",
        round(((b.maxbytes-b.total)/b.maxbytes)*100,2) || '%' as "can_auto_allocated_percent"
from
(select tablespace_name,file_id,sum(bytes) as free
        from dba_free_space group by tablespace_name,file_id) a,
(select tablespace_name,file_id,sum(bytes) as total,maxbytes
        from dba_data_files
        group by tablespace_name,file_id,maxbytes) b
where a.file_id = b.file_id
order by file_id"""
    cursor.execute(selectSql)
    results = []
    emp_title_list = []

    for desc in cursor.description:
        emp_title_list.append(desc[0])
    results.append(emp_title_list)

    result = cursor.fetchall()
    results.append(result)

    cursor.close()
    conn.close()

    return results

def render(tplPath,**kwargs):
    path,fileName = os.path.split(tplPath)
    template = Environment(loader=FileSystemLoader(path)).get_template(fileName)
    content = template.render(**kwargs)

    return content

def getContent():
    emp_title_list = getResults()[0]
    emp = 'emp'
    results = getResults()[1]
    mInfo = monMem()
    cpuInfo = monCpu()
    dInfo = monDisk()

    return render('Test.html',**locals())

"""添加的sendMail函数"""
def sendMail(user,pwd,to,subject,content):
    SMTP_SERVER = 'smtp.qq.com'
	SMTP_PORT = 25
#发送HTML邮件
    msg = MIMEText(content,_subtype='html')
    msg['From'] = user
    msg['To'] = to
    msg['Subject'] = subject

#创建发送邮箱服务器实例
    smtp_server = smtplib.SMTP(SMTP_SERVER,SMTP_PORT)
    print('Connecting To Mail Server.')
    try:
#和服务器打招呼
        smtp_server.ehlo()
	#设置会话加密
        print('Starting Encryped Session.')

        smtp_server.starttls()
        smtp_server.ehlo()
        print('Logging Into Mail Server.')

	#登录邮箱服务器
        smtp_server.login(user,pwd)
        print('Sending Mail.')
	#发送邮件user发送的邮件名,to发送目的地邮箱 msg.as_string()邮箱格式
        smtp_server.sendmail(user,to,msg.as_string())
    except Exception as err:
        print('Sending Mail Failed: {0}'.format(err))
    #不论是否出现异常都会输出finally
    finally:
#退出邮箱服务器
        smtp_server.quit()


def showWeb():
    html = 'testJinja2.html'

    with open(html,'w') as fObj:
        fObj.write(getContent())
        fObj.close()

    webbrowser.open(html,new=1)

if __name__ == '__main__':
    #print(monMem())
    #print(monCpu())
    #print(monDisk())
    #showWeb()
    #print(getContent())
   sendMail('[email protected]','******','[email protected]','Important',getContent())

查看结果:
Python监控系统信息、巡检数据库将结果写入到html,并定时发送邮件到邮箱_第2张图片
Python监控系统信息、巡检数据库将结果写入到html,并定时发送邮件到邮箱_第3张图片

4、添加定时任务

import sys,os
import random
import time
from datetime import datetime
from config import globaVar
from pages import studyPage
from apscheduler.schedulers.blocking import BlockingScheduler

def run ():
"""方法中执行脚本Test.py这里使用os.system方法,也可以使用psutil.subprocess.call方法"""
	os.system("python C:\Users\Administrator\Desktop\Test_Python\Test.py")

if name == ‘__main__’:
	scheduler = BlockingScheduler()
	"""每天8点30发送监控信息到email"""
	scheduler.add_job(run,'cron',hour=20,minute=30,id='sendMail')

你可能感兴趣的:(Python,python,oracle)