Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect a request to a different url in python

Tags:

I have been looking for the syntax to redirect a special url to a remote server to do some XSS testing. Any ideas?

import SimpleHTTPServer import SocketServer  class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):     def do_GET(self):         print self.path          if self.path == '/analog': -------------------->return "http://12b.dk/analog"???         return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)  theport = 1234 Handler = myHandler pywebserver = SocketServer.TCPServer(("", theport), Handler)  print "Python based web server. Serving at port", theport pywebserver.serve_forever() 
like image 591
tax Avatar asked Mar 24 '10 10:03

tax


People also ask

How do I redirect a URL in Python?

Use Python urllib Library To Get Redirection URL. request module. Define a web page URL, suppose this URL will be redirected when you send a request to it. Get the response object. Get the webserver returned response status code, if the code is 301 then it means the URL has been redirected permanently.


2 Answers

For a redirect, you have to return a code 301, plus a Location header. Probably you can try something like:

class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):    def do_GET(self):        self.send_response(301)        self.send_header('Location','http://www.example.com')        self.end_headers() 
like image 69
Dan Andreatta Avatar answered Oct 21 '22 08:10

Dan Andreatta


Python 3

In python3 it is done very similar to other answers, but different enough to justify demonstration.

This is a script that does nothing but listen on the port passed as argument 1 and send a 302 ("Found" aka Temporary) redirect to the URL passed as argument 2. (And it has a usage message.)

#!/usr/bin/env python3  import sys from http.server import HTTPServer, BaseHTTPRequestHandler  if len(sys.argv)-1 != 2:     print(""" Usage: {} <port_number> <url>     """.format(sys.argv[0]))     sys.exit()  class Redirect(BaseHTTPRequestHandler):    def do_GET(self):        self.send_response(302)        self.send_header('Location', sys.argv[2])        self.end_headers()  HTTPServer(("", int(sys.argv[1])), Redirect).serve_forever() 

You call it like:

sudo ./redirect.py 80 http://jenkins.example.com:8080/ 

That example ought to give you enough to write what ever kind of function you need.

like image 36
Bruno Bronosky Avatar answered Oct 21 '22 06:10

Bruno Bronosky