#! /usr/bin/env python """ This script formats a simple command into XML for delivery to the RSW server, and reports the XML response. rsw_remote.py [opts] command [param=value] [param=value] ... Options: -s server-address Specifies the server web address; the default is http://rswgame.com . -v If present, verbose output is printed, which shows the URL posted to and the XML string actually posted. Otherwise, only the server response is printed. """ import getopt import sys import urllib2 def usage(code, msg = ''): print >> sys.stderr, __doc__ print >> sys.stderr, msg sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], 's:vh') except getopt.error, msg: usage(1, msg) serverAddress = 'http://rswgame.com' verbose = False for opt, arg in opts: if opt == '-s': serverAddress = arg elif opt == '-v': verbose = True elif opt == '-h': usage(0) # The first argument should be a command, not a parameter, which means # it should not contain an equals sign. if len(args) < 1 or '=' in args[0]: usage(0) # First, find the actual address for sending XML requests. We do this # by following the redirect from "http://rswgame.com/xml". This # should be an https address, if the RSW server is responding and # configured correctly. url = serverAddress + '/xml' try: file = urllib2.urlopen(url) except IOError: print >> sys.stderr, "Could not contact RSW server at %s" % (url) sys.exit(1) serverPostAddress = file.geturl() if verbose: print '\nPost to: %s\n' % (serverPostAddress) # Now, format the command into an XML request. request = '\n' request += '\n' % (args[0]) # Add in all of the parameters. for param in args[1:]: # If an equal sign is present on the command line, it splits the # parameter into parameter and value. Otherwise, the value is # empty. if '=' in param: param, value = param.split('=', 1) request += ' \n' % (param, value) else: request += ' \n' % (param) request += '\n' if verbose: print request # Now use urllib2 to post the request. try: file = urllib2.urlopen(serverPostAddress, request) except urllib2.HTTPError: # The server returned an HTTP error, e.g. 400, which indicates it # didn't like something about the command. print >> sys.stderr, "Incorrect XML formatting or other internal error." sys.exit(1) except IOError: # Some bigger error contacting the server. print >> sys.stderr, "Failure posting request to RSW server at %s" % (serverPostAddress) sys.exit(1) response = file.read() print response