Skip to Main Content
 

Main Menu

 

Nagios/Op5 script using cx_Oracle in python returning codes

This plugin is used to find the status of the service.
I have created a table error_logs. Let's start with selecting from error_logs table.
We have total 9 rows


sql

import library cx_oracle
you can get cx_oracle by running below command
python -m pip install cx_Oracle --upgrade --user


sql

execute the code and see if you can connect to database and get required result
your out put should look like below


C:\Users\pc786\Desktop\blog\Nagios return codes>python cx_oracle.py
9

Now write rest of the code
set your variable threshold warning, critical, ok and return exit codes accordinly

sql

output below

sql

copy the below code


import cx_Oracle
import sys

unknown = ('Unknown') #try your connection
try:
 conn_str = u'hr/hr@192.168.174.131:1521/xe'
 conn = cx_Oracle.connect(conn_str)
 sql='select count(*) from error_logs'
 column_length=[5, 22, 6, 5]
 cursor = conn.cursor()
 for row in cursor.execute(sql):
   for i in range (len(row)):
     print(str(row[i]).ljust(column_length[i]), end='' )
   print()
#add if block if you like to
except cx_Oracle.DatabaseError as exc:
  err, = exc.args
  print("Oracle-Error-Code:", err.code)
  print("Oracle-Error-Message:", err.message)
  print(unknown)
  sys.exit(3)
finally:
  cursor.close()
  conn.close()

rows = int(row[i])

#Set threshold for warning and critical
critical = 9
warning = 7
ok = 0

class status(object):
    def getStatus(self):
        if int(rows) >= critical:
            print ('Critical %'+ str(int(rows) * critical / 100) + (' total error rows are ') +str(rows) )
            sys.exit(2)
        elif int(rows) >= warning:
            print ('Warning %'+ str(int(rows) * warning / 100) + (' total error rows are ') +str(rows))
            sys.exit(1)
        else:
            print ('OK %'+ str(int(rows) * ok / 100) + (' total error rows are ') +str(rows))
            sys.exit(0)

classObject = status()
classObject.getStatus()

 
 

Feedback