我正在通过python编写一个非常简单的Web代理,现在我正在处理HTTPS CONNECT请求,因此我可以打开HTTPS网站。我正在尝试设置SSL隧道,但我的代码不太正确。我觉得我很接近,但是如果有人能看一眼就把我推向正确的方向,这将是很棒的。我目前对我应该做的事情的理解是
这是我的代码:
def ProxyThread(conn, client_addr):
request = conn.recv(MAX_BUFFER)
#print request
# Parsing
method, webserver, port = ParseReq(request)
print 'Request = ' + method + ' ' + webserver + ':' + str(port) + '\n'
try:
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.connect((webserver, port))
if method == 'CONNECT':
connect_req = 'HTTP/1.1 200 Connection established\r\n'
connect_req += 'Proxy-agent: localhost\r\n\r\n'
conn.send(connect_req.encode())
serverSocket.send(connect_req)
while 1:
data = serverSocket.recv(MAX_BUFFER)
# while there is data to receive from server
if len(data) > 0:
conn.send(data)
else:
break
serverSocket.close()
conn.close()
except socket.error, (message):
print message
if conn:
conn.close()
if serverSocket:
serverSocket.close()
return
编辑1:更新代码以在我获得HTTPS请求时启动线程
def ProxyThread(conn, client_addr):
request = conn.recv(MAX_BUFFER)
method, webserver, port = ParseReq(request)
#Handle index out of range exception - Throw out the request
if method is None or webserver is None or port is -1:
return
print 'Request = ' + method + ' ' + webserver + ':' + str(port) + ' START\n'
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
if method == 'CONNECT':
connect_req = 'HTTP/1.0 200 Connection established\r\n'
connect_req += 'Proxy-agent: ProxyServer/1.0\r\n'
connect_req += '\r\n'
print connect_req
conn.send(connect_req)
thread = threading.Thread(target=HTTPSProxyThread, args=(conn, serverSocket))
thread.start()
serverSocket.connect((webserver, port))
serverSocket.send(request)
while 1:
data = serverSocket.recv(MAX_BUFFER)
# while there is data to receive from server
if len(data) > 0:
conn.send(data)
else:
break
print 'Request = ' + method + ' ' + webserver + ':' + str(port) + ' FINISH\n'
serverSocket.close()
conn.close()
def HTTPSProxyThread(conn, serverSocket):
while 1:
request = conn.recv(MAX_BUFFER)
print request
method, webserver, port = ParseReq(request)
serverSocket.connect((webserver, port))
serverSocket.send(request)
while 1:
data = serverSocket.recv(MAX_BUFFER)
# while there is data to receive from server
if len(data) > 0:
conn.send(data)
else:
break
答案 0 :(得分:0)
很多人似乎在Python或Node.js中构建自己的Web代理。
作为过去22年来制作网络代理的人,我想知道人们为什么会这样做,特别是在所有主要平台上都有免费产品的地方,有人已经处理了这些问题,例如其中你将不得不处理)
虽然这是一种有趣的方式来暂时消磨时间,但是这些代理中存在的代理越多,如果将朴素的实现用于更一般的流量,则整体网络变得越多。如果您只是将此用于您自己的特定部署要求,请忽略此评论。
我想我想说的是,制作一个表现良好(更不用说高性能)的Web代理并非易事。