python通過cx_Oracle模塊監控oracle業務

1、要想通過python監控Oracle,可以使用cx_Oracle模塊,還需配置環境變量,此處不做詳解
關於cx_Oracle的版本,一定要和linux機器上的oracle版本以及python版本符合;

此處我的oracle版本是11g,python是2.7,因此我的cx_Oracle版本是cx_Oracle-5.2.1-11g-py27-1.x86_64.rpm,否則會報libcublas.so.12.1 cannot open shared object file no such file or directory類似的錯誤;

下面附python3腳本

cat /u01/app/oracle/scripts/unionpay.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import cx_Oracle,sys,os

'''
腳本備註
'''


sql = {
    'unionpay_success': "sql1",
    'unionpay_failed': "sql2'"
}


def Get_Item(itemkey):
    conn = None
    result = None

    try:
        conn = cx_Oracle.connect(‘數據庫賬號/密碼@IP:端口/庫名')
        cursor = conn.cursor()
        cursor.execute(sql[itemkey])
        rows = cursor.fetchall()
        if len(rows) == 1:

            result = rows[0][0]
        else:
            result = None

        cursor.close()
        conn.close()

    except Exception as e:
        print(e)
    finally:

        if not conn:
            conn.close()

    return result

if __name__ == '__main__':
    a = Get_Item(sys.argv[1])
    if sys.argv[1] == 'unionpay_success':
        os.system('zabbix_sender -z zabbix_server_ip  -s zabbix_agent_ip -k unionpay_success -o %s'% a)
    else:
        os.system('zabbix_sender -z zabbix_server_ip -s zabbix_agent_ip -k unionpay_failed -o %s'% a)

以上腳本是通過zabbix採集器做監控的,這樣可以減輕服務端的io性能

2、在寫計劃任務是遇到一個大坑,手動執行正常,但配到crontab中無法運行

因爲需要生效你使用的用戶的bash信息,可以在前面加上“source ~/.bash_profile &&”,這個文件中應當配置的有oracle的環境變量,crontab如:

*/2 * * * * source /home/oracle/.bash_profile && /usr/bin/python2 /u01/app/oracle/scripts/unionpay.py > /yyy.log 2>&1  
此處我用的是oracle這個普通用戶
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章