【问题标题】:in python using re.py to extract from a substring error在python中使用re.py从子字符串中提取错误
【发布时间】:2021-01-10 09:55:52
【问题描述】:

我正在参加一门 Python 课程,我正在学习“使用正则表达式提取子字符串”部分。例如,我们正在构建一个 MAC 地址转换器。

到目前为止,这是我的代码:

#!/usr/bin/env python
import subprocess
import optparse
import re


def get_arguments():
    parser = optparse.OptionParser()
    parser.add_option("-i", "--interface", dest="interface", help="interface to change its MAC address")
    parser.add_option("-m", "--mac", dest="new_mac", help="New MAC address")
    (options, arguments) = parser.parse_args()
    if not options.interface:
        parser.error("[-] please specify an interface, use --help for more info")
    elif not options.new_mac:
        parser.error("[-] please specify a MAC, use --help for more info")
    return options


def change_mac(interface, new_mac):
    subprocess.call(["sudo", "ifconfig", interface, "down"])
    subprocess.call(["sudo", "ifconfig", interface, "hw", "ether", new_mac])
    subprocess.call(["sudo", "ifconfig", interface, "up"])
    print("[+] Changing MAC address for " + interface + " to " + new_mac)


options = get_arguments()
change_mac(options.interface, options.new_mac)

ifconfig_result = subprocess.check_output(["ifconfig", options.interface])
print(ifconfig_result)
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
print(mac_address_search_result.group(0))

据我在教程中看到的,这是应该的,但我收到以下错误:

Traceback (most recent call last):
File “mac_changer.py”, line 32, in
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
File “/usr/lib/python3.8/re.py”, line 201, in search
return _compile(pattern, flags).search(string)
TypeError: cannot use a string pattern on a bytes-like object

我在 google 上查看了有关此错误的一些信息,但我没有找到任何适合 mac 转换器的信息。
澄清一下,我正在 Linux kali 下构建和运行它,它在终端中运行。

【问题讨论】:

    标签: python


    【解决方案1】:

    可能你得解码subprocess.check_output的输出:

    subprocess.check_output(["ifconfig", options.interface]).decode('utf-8')
    

    看看check_output的文档:

    默认情况下,此函数会将数据作为编码字节返回。输出数据的实际编码可能取决于被调用的命令,因此通常需要在应用程序级别处理对文本的解码。

    【讨论】:

    • 好吧,我会的,当我阅读您的答案时,如果这是我需要的答案,我会持保留态度,因为我已经在这里阅读了 simular 以获得不同的数据集并忽略了它就像那个错误的数据集一样,但是因为我已经将解码添加到子流程的行的编辑中,所以对我的怀疑表示感谢,现在看起来应该感谢一百万个任何合理建议的机会他们没有使用或需要使用解码的专业 TUT 视频仍然得到很好的结果?
    • 所以我现在实际上刚刚学会了一种不同的方法来处理这个问题所以事实证明,我被展示了如何为 python 2 制作我的代码,但它是作为 python3 执行的,所以得到了这些错误.decode 想法完美地工作,因为它的字符串和字节的不同是问题,所以不同的方式是在建议添加 .decode('utf-8') 行之后的下一行,该行如下所示: mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result) 只需简单地在末尾添加 str() 所以 str(ifconfig_result) )
    • 是的,这是另一种方式,即使我更愿意将ifconfig_result 作为字符串。
    猜你喜欢
    • 2016-06-01
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2021-05-01
    • 2017-04-01
    • 2015-05-10
    相关资源
    最近更新 更多