PyProxy/PyProxy.py

41 lines
1.4 KiB
Python
Raw Permalink Normal View History

2024-11-29 16:31:32 +08:00
# 基础示范例子,后续加入轮转代理
import socket
import socks
import threading
from socketserver import ThreadingMixIn, TCPServer, StreamRequestHandler
class ThreadingTCPServer(ThreadingMixIn, TCPServer):
pass
class SocksProxyHandler(StreamRequestHandler):
def handle(self):
# 获取客户端请求的地址和端口
remote_address = self.rfile.readline().strip().decode('utf-8').split(':')
remote_host = remote_address[0]
remote_port = int(remote_address[1])
# 设置SOCKS代理
socks.set_default_proxy(socks.SOCKS5, 'localhost', 1080)
socket.socket = socks.socksocket
# 连接到远程主机
try:
with socket.create_connection((remote_host, remote_port)) as remote_socket:
# 将客户端数据转发到远程主机
while True:
data = self.request.recv(4096)
if not data:
break
remote_socket.sendall(data)
response = remote_socket.recv(4096)
self.request.sendall(response)
except Exception as e:
print(f"Error: {e}")
def start_proxy_server(host='0.0.0.0', port=8888):
server = ThreadingTCPServer((host, port), SocksProxyHandler)
print(f"Starting proxy server on {host}:{port}")
server.serve_forever()
if __name__ == '__main__':
start_proxy_server()