Skip to content

Instantly share code, notes, and snippets.

@cluther
Created July 8, 2009 15:37
Show Gist options
  • Save cluther/142922 to your computer and use it in GitHub Desktop.
Save cluther/142922 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import os
from optparse import OptionParser
zenhome = os.environ['ZENHOME']
oldpath = os.environ.get('LD_LIBRARY_PATH', None)
libpath = os.path.join(zenhome, 'ZenPacks',
'ZenPacks.zenoss.ZenSQLTx-2.0.0-py2.4-linux-i686.egg',
'ZenPacks', 'zenoss', 'ZenSQLTx', 'lib')
# Augment PYTHONPATH
sys.path.append(libpath)
# Augment LD_LIBRARY_PATH
if oldpath:
os.environ['LD_LIBRARY_PATH'] += ':%s' % libpath
else:
os.environ['LD_LIBRARY_PATH'] = libpath
import pymssql
def raiseNagiosStyleError(e):
if hasattr(e, 'args'):
e = e.args[-1]
s = e.__str__().replace('\n',' ').replace('\r',' ')
print(s)
sys.exit(2)
class ZenossMSSQLQuery:
def __init__(self, host, user, passwd, db):
params = dict(host="%s:1433" % (host,), user=user, database=db)
if passwd: params['password'] = passwd
try:
self.conn = pymssql.connect(**params)
self.cursor = self.conn.cursor()
except Exception:
print "Error connecting to database."
sys.exit(2)
def runQuery(self, query):
self.cursor.execute(query)
data = self.cursor.fetchall()
try:
result = data[0][0]
print "OK|result=%s" % (str(result))
sys.exit(0)
except IndexError, e:
print "No result returned for query."
sys.exit(2)
if __name__ == "__main__":
parser = OptionParser()
parser.add_option('-H', '--host', dest='host',
help='Database server hostname or IP')
parser.add_option('-u', '--user', dest='user',
help='Username when connecting to the database')
parser.add_option('-p', '--password', dest='password',
help='Password when connecting to the database')
parser.add_option('-d', '--database', dest='database',
help='Database to connect to')
options, args = parser.parse_args()
if not options.host:
print "You must specify the host."
sys.exit(2)
elif not options.user:
print "You must specify the user."
sys.exit(2)
elif not options.database:
print "You must specify the database."
sys.exit(2)
elif not args:
print "You must specify a SQL query to run."
sys.exit(2)
zmq = ZenossMSSQLQuery(options.host, options.user, options.password,
options.database)
zmq.runQuery(args[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment