#! /usr/bin/python """ wcall.py This application provides basic facilities to send HTTP requests to a server. License ------- Copyright (C) 2006. Jason R Briggs This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Meta-Data --------- Author: Jason R Briggs License: http://www.gnu.org/licenses/gpl.txt Version: $Revision: 0.2 $ Start Date: 2006/08/06 Last Revision Date: $Date: 2006/08/06 17:46 $ """ import httplib from optparse import OptionParser import re import sys parser = OptionParser(usage="usage: %prog [options] method url") parser.add_option("-f", "--file", dest="filename", help="send file [filename]", metavar="FILE") parser.add_option("-s", "--headers", dest="headers", help="http headers (format header1=val1&header2=val2", metavar="HEADERS") uri_re = re.compile(r'([^:]*)://([^/]*)(.*)') def wcall(options, args): protocol = None url = None server = None method = args[0] mat = uri_re.match(args[1]) if mat: protocol = mat.group(1) server = mat.group(2) url = mat.group(3) if not protocol or not server: raise RuntimeError, 'invalid uri' headers = {} if options.headers: for p in options.headers.split('&'): sp = p.split('=') if len(sp) != 2: continue headers[sp[0]] = sp[1] if method in ['PUT', 'POST'] and (not headers.has_key('Content-Type') or headers['Content-Type'] != 'application/x-www-form-urlencoded'): headers['Content-Type'] = 'application/x-www-form-urlencoded' if method not in ['GET', 'DELETE', 'HEAD']: if options.filename: content = file(options['filename']).read() else: content = sys.stdin.read() headers['Content-Length'] = str(len(content)) else: content = '' if protocol == 'https': conn = httplib.HTTPSConnection(server) else: conn = httplib.HTTPConnection(server) conn.request(method, url, content, headers) resp = conn.getresponse() print 'status %s , reason %s' % (resp.status, resp.reason) print str(resp.msg) print resp.read() if __name__ == '__main__': (options, args) = parser.parse_args() if len(args) < 2: parser.print_help() sys.exit(1) wcall(options, args)