1、编写jinja2模板
<html>
<meta http-equiv="Content-Type" content="text/html" charset="GBK" />
<head>
<title>Oracle中查询数据</title>
<style type="text/css">
<!--
body{
background-color:#ebf5ff;
margin:0px;
padding:4px;
text-align:center;
}
.datalist{
color:#0046a6;
background-color:#d2e8ff;
font-family:Console;
border:1px solid #007eff;
border-collapse:collapse;
}
.datalist caption{
font-size:18px;
font-weight:bold;
margin : 10px;
text-align:left;
}
.datalist th{
color:#003e7e;
background-color:#7bb3ff;
padding:10px;
padding-top:5px;
padding-bottom:5px;
}
.datalist th,.datalist td{
border:1px solid #429fff;
text-align:center;
}
.datalist td{
padding-left:10px;
padding-right:10px;
}
p{
text-align:left;
font-family:Console;
font-size:25px;
color:red;
margin-top:10px;
margin-bottom:5px;
font-weight:bold;
}
.monlist caption{
text-align:left;
}
-->
</style>
</head>
<body>
<!-- 这里将查询到的结果使用table来显示 -->
<p>系统信息:</p>
<table class="datalist monlist">
<caption>MemoryInfo</caption>
<tr>
<th>totalMem</th>
<th>freeMem</th>
<th>avaMem</th>
</tr>
<tr>
{% for key,value in mInfo.items() %}
<td> {{ value }}</td>
{% endfor %}
</tr>
</table>
<table class="datalist monlist">
<caption>CPUInfo</caption>
<tr>
{% for key in cpuInfo.keys() %}
<th>{{ key }}</th>
{% endfor %}
</tr>
<tr>
{% for value in cpuInfo.values() %}
<td> {{ value }}</td>
{% endfor %}
</tr>
</table>
<table class="datalist monlist">
<caption>DiskInfo</caption>
<tr>
<th>MountName</th>
<th>Total</th>
<th>Used</th>
<th>Free</th>
<th>Percent</th>
</tr>
{% for key,value in dInfo.items() %}
<tr>
<th>{{ key }}</th>
<td>{{ value.total }}</td>
<td>{{ value.used }}</td>
<td>{{ value.free }}</td>
<td>{{ value.percent }}</td>
</tr>
{% endfor %}
</table>
<p>Oracle数据库巡检:</p>
<table summary="select data from oracle" class="datalist">
<caption>监控数据库表空间使用情况</caption>
<tr>
{% for etl in emp_title_list %}
<th>{{ etl }}</th>
{% endfor %}
</tr>
{% for row in results %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
<td>{{ row[2] }}</td>
<td>{{ row[3] }}</td>
<td>{{ row[4] }}</td>
<td>{{ row[5] }}</td>
<td>{{ row[6] }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
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显示情况:
这里的巡检脚本比较简单,只做示例…
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('370751572@qq.com','******','ganxin2020@163.com','Important',getContent())
查看结果:
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')
来源:CSDN
作者:Lissen_Gan
链接:https://blog.csdn.net/u011285708/article/details/104451094