Search code examples
pythonpython-3.xurllib

'bytes' object has no attribute 'items'


While doing a CTF challenge, we are asked to enter MD5 hash of a certain 'key' within few milliseconds, so I'm trying to automate the task like this in Python3:

import re
import urllib.request
import urllib.parse
import hashlib

url = 'http://random.page'

page = urllib.request.urlopen(url)
header = {}
header['Set-Cookie'] = page.info()['Set-Cookie']
html = page.read().decode('utf-8')
key = re.search("<h3 align='center'>+.*</h3>", html).group(0)[19:-5]
md5 = hashlib.md5(key.encode()).hexdigest()

data = {'hash':md5}
post_data = urllib.parse.urlencode(data).encode('ascii')
post_header = urllib.parse.urlencode(header).encode('ascii')
request = urllib.request.Request(url, data=post_data, headers=post_header)
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

I want the same session as the 'key' gets changed at every request, so I'm trying to use the same cookie. But this error arises:

Traceback (most recent call last):
  File "MD5.py", line 18, in <module>
    request = urllib.request.Request(url, data=post_data, headers=post_header)
  File "/usr/lib/python3.7/urllib/request.py", line 334, in __init__
    for key, value in headers.items():
AttributeError: 'bytes' object has no attribute 'items'

Solution

  • Do not urlencode headers. urllib.request.Request expects it to be a dictionary.

    Simply pass the headers as is and it will fix your problem.