#!/usr/bin/python

# mssqlcmd - Run remote system commands on hosts running Microsoft SQL Server
# Copyright (C) 2007-2011  Sertan Kolat (warex) - sertan@olympos.org

# version 0.3
# last update: Feb 28, 2011

# pymssql library is required
# download from http://pymssql.sourceforge.net

import getopt,sys
import getpass
from os import name as ostype

try:
	import _mssql
except ImportError:
	print "pymssql library is required to run this program.\nplease download it from http://pymssql.sourceforge.net"
	sys.exit(2)

def usage():
	print "mssqlcmd - Run remote system commands using MSSQL"
	print "\nUsage: mssqlcmd.py [options] 'System command (default: ipconfig)'"
	print "\nOptions:"
	print "-h, --help	Show this help message and exit"
	print "-s SERVER	Remote server hostname or IP address."
	print "		On Windows you can use sqlhost\instancename"
	print "		to connect to a non-default(named) instance.\n"
	print "-p PORT		Server port (default 1433)"
	print "-u USERNAME	SQL server username (default 'sa')."
	print "		Will ask for a password if -u option is given.\n"
#	print "-d DATABASE	Database name to run SQL queries on (default: master).\n\t\tUseful when using -q option.\n"
#	print "-q SQL_QUERY	Run SQL query instead of remote system command"

def main():
	# Set up options and parse arguments
	if len(sys.argv) == 1:
		usage()
		sys.exit(2)

	try:
		opts, args = getopt.getopt(sys.argv[1:], "hs:u:p:", ["help"])
	except getopt.GetoptError:
		#print help information and exit
		usage()
		sys.exit(2)
	
	if len(args)>0:
		dbcommand = ' '.join(args)
	else:
		dbcommand = 'ipconfig'
	#dbhost='localhost'
	dbhost=''
	dbport=1433
	dbuser='sa'
	dbpass=''
	for o, a in opts:
		if o in ("-h", "--help"):
			usage()
			sys.exit()
		if o in "-u":
			dbuser = a
			try:
				dbpass = getpass.getpass('Enter password for %s: ' % a)
			except KeyboardInterrupt:
				sys.exit()
		if o in "-p":
			dbport = a
		if o in "-s":
			dbhost = a
	
	if not dbhost:
		print 'You must provide a server to connect! (-h for help)'
		sys.exit(2)
	
	print ('Running "%s" on %s:%s...' % (dbcommand, dbhost, dbport))
	if dbport != 1433:
		if ostype in ["nt", "ce"]:
			dbhost = dbhost + ',' + dbport
		else:
			dbhost = dbhost + ':' + dbport
		
	try:
		conn=_mssql.connect(dbhost, dbuser, dbpass)
	except:
		print 'Error connecting to MSSQL server!'
		sys.exit(2)

	try:
		# Solutions to common xp_cmdshell problems
		#
		# 1) xp_cmdshell removed? try adding it!
		#   EXEC sp_addextendedproc "xp_cmdshell", "xpsql70.dll"
		#
		#conn.execute_query('EXEC sp_addextendedproc "xp_cmdshell", "xpsql70.dll"')
		#
		# 2) Use SQL query below to enable xp_cmdshell on MSSQL 2005 or 2008
		#   sp_configure 'xp_cmdshell', '1'
		#
		#conn.execute_query("EXEC sp_configure 'show advanced options', 1")
		#conn.execute_query("RECONFIGURE WITH OVERRIDE")
		#conn.execute_query("sp_configure 'xp_cmdshell', '1'")
		#conn.execute_query("RECONFIGURE WITH OVERRIDE")
		#conn.execute_query("EXEC sp_configure 'show advanced options', 0")
		#
		
		ret=conn.execute_query('exec master..xp_cmdshell "%s"' % dbcommand)
	except _mssql.MssqlDatabaseException,e:
		print e.message
	else:
		for row in conn:
			if row['output'] != None:
				print row['output']


if __name__ == '__main__':
	main()

