python urllib2 支持 自定义cookie

时间:2023-03-09 09:21:12
python urllib2 支持 自定义cookie

首先需要2个软件来抓包。

fiddler : http 代理软件可以分析,抓包,重放。

wireshark : 全能抓包分析软件。

RFC 提供了非常好的设计描述。

https://tools.ietf.org/html/rfc7230

https://tools.ietf.org/html/rfc7231

安装好
Fiddler2
Tools ->Fiddler Options…-> Connections
Allow remotecomputers toconnect
需要重启 Fiddler2 后生效

Wireshark
设置好抓包规则
tcp.port == 8888

全部设置好后,使用另外一台电脑,配置好浏览器,打开下面的测试地址:
https://www.baidu.com/img/bd_logo1.png

最好是,在2台电脑上进行,有IP 地址比较好分辩(没有2台电脑的用VM 也行)。

python urllib2 支持 自定义cookie

本机为 192.168.1.127 , Fiddler 为 192.168.1.121。

可以看到,本地在发送了一个 请求头后,直接和 192.168.1.121 进行了 TLS 协商。

可见 HTTPS 代理也是非常容易实现。

TCP 流:

python urllib2 支持 自定义cookie

或者使用 curl 进行测试,firefox 自带了很多垃圾请求,不太好分辨包。

python urllib2 支持 自定义cookie

可见 百度用的是 apache 的服务器。

建立一个 连接到目标站点的 https socket。

回复 HTTP/1.1 200 Connection Established

浏览器发过来 client hello ,转发给 https socket

普通的 HTTP 是 请求 响应模式。
而 HTTPS 是有可能 HTTPS 也会主动发送 tcp 数据包过来,如 server hello 。
所以实现上,还需要用到 select 来实现 fd 的检查工作。

 #!/usr/bin/env python
#coding:utf-8
import socket
import sys
import re
import os
import time
import select
import threading HEADER_SIZE = 4096 host = '0.0.0.0'
port = 8000 #子进程进行socket 网络请求
def http_socket(client, addr):
#创建 select 检测 fd 列表
inputs = [client]
outputs = []
remote_socket = 0
print("client connent:{0}:{1}".format(addr[0], addr[1]))
while True:
readable, writable, exceptional = select.select(inputs, outputs, inputs)
try:
for s in readable:
if s is client:
#读取 http 请求头信息
data = s.recv(HEADER_SIZE)
if remote_socket is 0:
#拆分头信息
host_url = data.split("\r\n")[0].split(" ")
method, host_addr, protocol = map(lambda x: x.strip(), host_url)
#如果 CONNECT 代理方式
if method == "CONNECT":
host, port = host_addr.split(":")
else:
host_addr = data.split("\r\n")[1].split(":")
#如果未指定端口则为默认 80
if 2 == len(host_addr):
host_addr.append("")
name, host, port = map(lambda x: x.strip(), host_addr)
#建立 socket tcp 连接
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, int(port)))
remote_socket = sock
inputs.append(sock)
if method == "CONNECT":
start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
s.sendall("HTTP/1.1 200 Connection Established\r\nFiddlerGateway: Direct\r\nStartTime: {0}\r\nConnection: close\r\n\r\n".format(start_time))
continue
#发送原始请求头
remote_socket.sendall(data)
else:
#接收数据并发送给浏览器
resp = s.recv(HEADER_SIZE)
if resp:
client.sendall(resp)
except Exception as e:
print("http socket error {0}".format(e)) #创建socket对象
http_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
http_server.bind((host, port))
except Exception as e:
sys.exit("python proxy bind error {0}".format(e)) print("python proxy start") http_server.listen(1024) while True:
client, addr = http_server.accept()
http_thread = threading.Thread(target=http_socket, args=(client, addr))
http_thread.start()
time.sleep(1) #关闭所有连接
http_server.close()
print("python proxy close")