Created
September 6, 2023 15:09
-
-
Save thuync/2e7c41468fb17bb9bd9deef2dc8c5d65 to your computer and use it in GitHub Desktop.
proxy-rotator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import http.server | |
| import socketserver | |
| import random | |
| # List of proxy servers to rotate through | |
| proxy_list = [ | |
| 'http://proxy1.example.com:8080', | |
| 'http://proxy2.example.com:8080', | |
| # Add more proxy servers as needed | |
| ] | |
| # Rotate through proxy servers in a circular manner | |
| def rotate_proxy(): | |
| return random.choice(proxy_list) | |
| # Define a custom request handler to forward requests through rotating proxies | |
| class ProxyHandler(http.server.SimpleHTTPRequestHandler): | |
| def do_GET(self): | |
| # Get a proxy from the rotation | |
| proxy = rotate_proxy() | |
| self.log_message("Using proxy: %s" % proxy) | |
| # Set up the proxy | |
| proxy_handler = {'http': proxy, 'https': proxy} | |
| self.requests = self.requests.replace(self.path.encode(), self.protocol.encode()) | |
| # Forward the request through the proxy | |
| try: | |
| response = requests.get(self.path, headers=self.headers, proxies=proxy_handler, verify=False) | |
| self.send_response(response.status_code) | |
| for key, value in response.headers.items(): | |
| self.send_header(key, value) | |
| self.end_headers() | |
| self.wfile.write(response.content) | |
| except Exception as e: | |
| self.send_error(500, f"Proxy Error: {str(e)}") | |
| if __name__ == "__main__": | |
| PORT = 8080 | |
| with socketserver.TCPServer(("", PORT), ProxyHandler) as httpd: | |
| print(f"Proxy server is listening on port {PORT}") | |
| httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment