python代码

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import subprocess
import sys
import re def run_cmd(cmd, cwd=None, runas=None):
if not sys.platform.startswith('win') and runas and runas != 'root':
cmd = 'su - {} -c "{}"'.format(runas, cmd)
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True,
cwd=cwd)
return proc def get_os_oracle_user():
cmd = ''' ps -ef | grep ora_ | grep -v grep | awk '{ print $1 }' | uniq '''
code, res = run_cmd(cmd)
if code == 0:
os_oracle_user = res
return os_oracle_user
else:
print "获取运行database的操作系统用户失败...", res
sys.exit(1) def get_grid_user():
cmd = '''ps -ef | grep asm_pmon | grep -v grep |uniq'''
return_code, result = run_cmd(cmd)
if return_code == 0 and result:
os_oracle_user = result.split('\n')[0].split()[0].strip()
return os_oracle_user
else:
print "获取运行database的操作系统用户失败...", result
sys.exit(1) class Oracle_init():
"""所有监控oracle的基类"""
def __init__(self, user='monitoruser', password='123456'):
try:
if user == 'sysdba':
self.user = '/ as sysdba'
elif user and password:
self.user = '{0}/{1}'.format(user, password)
else:
self.user = None
self.os_oracle_user=get_os_oracle_user()
except Exception as err:
print err
sys.exit(1) def run_cmd(self,sid,cmd):
cmd = r'''su - {} -c "export ORACLE_SID={}
sqlplus -S /nolog <<EOF
conn /as sysdba;
{}
exit;
EOF"'''.format(self.os_oracle_user, sid,cmd)
code, res = run_cmd(cmd)
error=self.check_error(res)
if error:
print error
sys.exit(1)
else:
return res def check_error(self,res):
if re.search(r'ORA-01017', res):
error = '账号或密码错误'
elif re.search(r'ORA-01034', res):
error = '数据库不可用'
elif re.search('ORA-\d+:[\s\S]*', res):
error = re.search('ORA-\d+:[\s\S]*', res).group()
else:
error = None
return error # 获取所有实例名
def get_sids():
sids = ''
cmd = "ps -ef|grep -v grep |grep ora_pmon|awk '{print $NF}'|sed 's/ora\_pmon\_//'|uniq"
code, res = run_cmd(cmd)
if not code and res:
sids = res.replace('\n', ' ')
return sids ########判断ohasd状态##############
def get_oracleOhasdStatus():
try:
cmd = "ps -ef | grep ohasd.bin|grep -v grep"
code,res=run_cmd(cmd)
if code:
return False
else:
return True
except Exception as err:
sys.stderr.write(err.__str__() + '\n')
return False ################监听日志大小##############
def get_oracle_listenerLog(sid):
try:
global is_cluster
if is_cluster:
user=get_grid_user()
else:
user= get_os_oracle_user()
cmd = 'su - {} -c "export ORACLE_SID={};' \
'du -sm $ORACLE_BASE/diag/tnslsnr/`hostname`/listener/trace/listener.log"'.format(user,sid)
code,res=run_cmd(sid, cmd)
if not res:
print '未获得数据'
sys.exit(1)
else:
return res.split()[0]
except Exception as err:
sys.stderr.write(err.__str__() + '\n')
return -1 ################监听trace文件# ##############
def get_oracleTrace(sid):
try:
global is_cluster
if is_cluster:
user = get_grid_user()
cmd = 'su - {} -c "export ORACLE_SID={};cat $ORACLE_BASE/diag/asm/+asm/$ORACLE_SID/trace/alert_+ASM1.log |egrep \'ORA-|ERROR\'"'.format(
user, sid)
else:
user = get_os_oracle_user()
cmd='su - {} -c "export ORACLE_SID={};cat $ORACLE_BASE/diag/rdbms/$DB_UNIQUENAME/$ORACLE_SID/trace |egrep \'ORA-|ERROR\'"'.format(
user, sid) code, res = run_cmd(sid, cmd)
if not res:
print '未获得数据'
sys.exit(1)
else:
return res.split()[0]
except Exception as err:
sys.stderr.write(err.__str__() + '\n')
return -1 if __name__=='__main__':
output = "metric=%s|value=%d|type=%s|tags=%s"
print output % ("system.file.number", get_oracleOhasdStatus(), 'gauge', '') obj = Oracle_init(user='monitoruser', password='123456') sql_cmd = "select value from v\\\$parameter where name='cluster_database';"
sids=get_sids()
res=obj.run_cmd(sids[0],sql_cmd)
res=res.split('\n')
length=len(res)
is_cluster=None
for i in range(-1,-1-length,-1):
if not i :
continue
if i.strip()=='False':
is_cluster=False
break
if i.strip()=='True':
is_cluster=True
break
if is_cluster is None:
print '无法判断是否是集群'
sys.exit(1) for sid in sids:
print output % ("system.file.number", get_oracle_listenerLog(sid), 'gauge', '')
print output % ("system.file.number", get_oracleTrace(sid), 'gauge', '')

  

oracle监控的更多相关文章

  1. oracle 监控执行的sql语句

    oracle 监控执行的sql语句 select * from v$sqlarea a where module='PL/SQL Developer' order by a.FIRST_LOAD_TI ...

  2. oracle监控参数

    Sar –u 检查CPU的繁忙程度列说明Usr用户模式下cpu运行所占的百分比Sys系统模式下cpu运行所占的百分比Wio因为有进程等待块I/O而使cpu处于闲置状态所占百分比IdleCpu为闲置状态 ...

  3. oracle监控脚本

    简单命令 1.显示服务器上的可用实例:ps -ef | grep smon2.显示服务器上的可用监听器:ps -ef | grep -i listener | grep -v grep3.查看Orac ...

  4. Oracle监控代理安装ITM(IBM Tivoli Monitoring)

    1 监控代理安装 2 1.1 安装 2 1.1.1 解压安装包 2 1.1.2 安装 2 1.2 配置 5 1.2.1 给Agent授权 5 1.2.2 配置Oracle Agent 10 目录 1  ...

  5. zabbix oracle监控插件orabbix部署安装

    1,下载orabbix插件包(插件包同时满足在大部分POSIX-linux及unix和大部分版本的windows下运行,玩转类似但不等同于Tomcat) wget http://www.smartma ...

  6. Oracle 监控索引使用

    Oracle提供一个监控索引的方法,来确定索引是否被使用.如果索引没有被使用,就可以删除它们以减少不必要的语句的开销.因为表上的大量不必要的索引可能会降低DML语句的性能,给数据库性能产生压力.所以生 ...

  7. oracle监控脚本【转】

    1. 监控事例的等待 select event,sum(decode(wait_Time,0,0,1)) "Prev", sum(decode(wait_Time,0,1,0)) ...

  8. Oracle监控的关键指标

    1.监控事例的等待 select event, , , )) "Prev", , , )) "Curr", count(*) "Tot" f ...

  9. 转 oracle 监控执行计划突然变化

    ########sample 执行计划突然变化 问题: 接受到一条信息,执行计划突然变化了. SELECT /*+ db120190621 no_expand */ INTERNAL_KEY FROM ...

随机推荐

  1. Kafka技术内幕 读书笔记之(六) 存储层——日志的读写

    -Kafka是一个分布式的( distributed ).分区的( partitioned ).复制的( replicated )提交日志( commitlog )服务 . “分布式”是所有分布式系统 ...

  2. Redis之路

    前言:数据库是一切数据的源头,因此我们没有逃避的理由 (一) 什么是redis? redis是nosql(not noly sql)产品中最为出色的一种非关系型的数据库,主要包括以下几种存储结构:St ...

  3. JS盒模型

    JS盒模型 ***** 1.width | height parseInt(getComputedStyle(ele, null).getPropertyValue('width')) parseIn ...

  4. http.lua里的装饰器

    摘自:http.lua local co_yield = coroutine.yield local co_create = coroutine.create local co_status = co ...

  5. jsp实现文件上传下载

    文件上传: upload.jsp <form action="uploadServlet" method="post" enctype="mul ...

  6. MySQL的一些基本命令笔记(2)

    1.逻辑运算符的补充 between 的用法:(在....之间) select column1,column2,......columnN from 表名 where columnX between ...

  7. 七、文件IO——I/O处理方式和文件锁

    7.1 I/O 处理方式 7.1.1 I/O处理的五种模型 阻塞I/O模型 若所调用的 I/O 函数没有完成相关的功能就会使进程挂起,直到相关数据到达才会返回.如 终端.网络设备的访问. 非阻塞模型 ...

  8. luogu 2014 选课 树上背包

    树上背包 #include<bits/stdc++.h> using namespace std; ; const int inf=0x3f3f3f3f; vector<int> ...

  9. Debian Security Advisory(Debian安全报告) DSA-4406-1 waagent

    Package        : waagentCVE ID         : CVE-2019-0804 Francis McBratney发现Windows Azure Linux代理创建了具有 ...

  10. VM4061 layui.js:2 Layui hint: form is not a valid module

    报错:VM4061 layui.js:2 Layui hint: form is not a valid module 解决办法:当你遇到类似这样报错,说某某某不是一个有效的模块时,不防在layui. ...