TypeError: cannot use a string pattern on a bytes-like object using re.findall()

TypeError: cannot use a string pattern on a bytes-like object using re.findall()

我开始解决 Python 中的 CTF 编程问题,当时我遇到了自动化数学计算以获得标志的挑战。

欢迎页面的源代码如下所示:

<html>

<head>

    <meta charset="utf-8">
    <title>FastMath</title>

</head>
<body>

<div id="content" style="text-align: center;">

Can you solve the level 1?<br/><h3><div id='calc'>1 + 1</div></h3><br/>
<form action="play.php" method="post">
 <input type="text" name="res" />
 <input type="submit" value="OK">
</form>
</div>
</body>

我写了我的 Python 代码来自动化它,以便获得如下标志

#!/usr/bin/env python
import requests
import re
encoding = 'utf-8'
url = '0.0.0.0:8091'
session = requests.Session()

response = session.get(url)
content = response.text

while True:
    try:
        #solves = re.findall('Can you solve the level (.*) ?', content)[0]
        number =  re.findall('(?:[0-9 ()]+[*+/-])+[0-9 ()]+', content)[0]

        post_url = url + '/play.php'
        solution = eval(number)
        post_data = { "res" : solution }

        response = session.post(post_url, data = post_data)
        content = response.content

        #debug
        print(content)
        #print('number of solves: ' + solves)
    except:
        flag = re.findall('FLAG{(.*)}', content)[0]
        print(flag)
        break

它设法进行了第一次计算,因为我得到了你能解决第 2 级吗?并按照我从输出中看到的那样提交,但随后出现错误:

b'<html>\n\n<head>\n\n\t<meta charset="utf-8">\n\t<title>FastMath</title>\n\n</head>\n<body>\n\n\t<div id="content" style="text-align: center;">\n\t\tCan you solve the level 2?<br/><h3><div id=\'calc\'>1 - 5</div></h3><br/>\t\t<form action="#" method="post">\n\t\t\t<input type="text" name="res" /></p>\n\t\t\t<p><input type="submit" value="OK"></p>\n\t\t</form>\n\t</div>\n</body>\n\n'
Traceback (most recent call last):
  File "mmm.py", line 14, in <module>
    number =  re.findall('(?:[0-9 ()]+[*+/-])+[0-9 ()]+', content)[0]
  File "/usr/lib/python3.6/re.py", line 222, in findall
    return _compile(pattern, flags).findall(string)
TypeError: cannot use a string pattern on a bytes-like object

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "mmm.py", line 27, in <module>
    flag = re.findall('LMFRCTF{(.*)}', content)[0]
  File "/usr/lib/python3.6/re.py", line 222, in findall
    return _compile(pattern, flags).findall(string)
TypeError: cannot use a string pattern on a bytes-like object

我尝试将其全部转换为字符串,但它没有用,即使使用 r"something"b"something" 也没有多大帮助!

response.text 会给你 str,而不是 byte,但 response.content 会给你 byte

选择您要使用的类型并始终如一地使用它。

如果正则表达式也是 byte

re 将处理字节。