利用Python監控Oracle當前跑的TOP SESSION

利用linux top命令抓出Oracle當前正在跑的進程,記錄進程消耗的%CPU,%MEM,RES

根據PID查詢當前跑的SQL,以及當前等待事件,監控程序每3秒執行一次

import cx_Oracle
import os
import time
os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.UTF8'
command="top -bi -n 1 | grep oracle | grep -v top | grep -v _orcl | awk '"+'{print $1 "," $9 "," $7"," $10}'+"'"
#你需要將_orcl換成_sid
con=cx_Oracle.connect('scott', 'tiger', "192.168.56.10/orcl:pooled", cclass="PYTHON",
                            purity=cx_Oracle.ATTR_PURITY_SELF, encoding="UTF-8")
cur=con.cursor()
cur.arraysize = 100
sql='select decode(sql_id,null,a.program,sql_id),a.event from v$session a, v$process b where a.paddr=b.addr and b.spid='
while True:
 date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
 with os.popen(command, "r") as p:
   process = p.read()
 if process=='':
     print(str(date)+' System is idle')
 elif process!='':
  line=process.splitlines()
  for rows in line:
     row=rows.split(",")
     cur.execute(sql+row[0])
     for x in cur:
       sql_id=str(x[0])
       event=str(x[1])
       print(str(date)+','+row[0]+','+row[1]+'%CPU,'+ row[3]+'%MEM,'+str(round(int((row[2]))/1024))+'MB,'+sql_id+','+event)
 time.sleep(3)
cur.close()
con.close()

代碼運行示例:

[oracle@server ~]$ python3 monitor.py
2020-05-18 13:41:07 System is idle
2020-05-18 13:41:11 System is idle
2020-05-18 13:41:14,3023,75.0%CPU,23.0%MEM,439MB,34149m3vuwxuh,direct path write temp
2020-05-18 13:41:17,3023,68.8%CPU,23.2%MEM,443MB,34149m3vuwxuh,db file scattered read
2020-05-18 13:41:20,3023,58.8%CPU,23.2%MEM,444MB,34149m3vuwxuh,db file scattered read
2020-05-18 13:41:24,3023,62.5%CPU,23.2%MEM,444MB,34149m3vuwxuh,direct path write temp

第一列是當前時間,第二列是PID,第三列是CPU使用率,第四列是內存使用率,

第五列是當前耗費內存,第六列SQL_ID,第七列等待事件

可以將上面python代碼稍作改動,將查詢的信息保存到CSV文件中,早上再導入數據庫分析

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章