【问题标题】:TypeError: cannot use a string pattern on a bytes-like object using re.findall()类型错误:不能使用 re.findall() 在类似字节的对象上使用字符串模式
【发布时间】:2021-02-17 14:50:07
【问题描述】:

当我遇到自动化数学计算以获取标志的挑战时,我开始使用 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" 也无济于事!

【问题讨论】:

  • re.findall 可能不会返回您想要的对象。
  • 在这种情况下还有其他选择吗?

标签: python html regex python-requests re


【解决方案1】:

response.text 会给你一个str,不是bytes,而是response.content 会给你bytes。

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

如果正则表达式也是bytes,re 将处理字节。

【讨论】:

    猜你喜欢
    • 2015-09-10
    • 2020-08-26
    • 2014-03-31
    • 2014-02-21
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    相关资源
    最近更新 更多