Python MAC地址修改器开发中使用re模块提取子串报错:无法在类字节对象上使用字符串模式
解决MAC地址修改器中的TypeError问题
你遇到的这个TypeError: cannot use a string pattern on a bytes-like object错误,本质原因很简单:subprocess.check_output()函数默认返回的是字节(bytes)类型的数据,而re.search()需要接收字符串类型的参数,两者类型不匹配就触发了这个错误。另外我还发现你的正则表达式和代码逻辑有几个小细节可以优化,下面一步步帮你解决:
1. 核心问题修复:将字节流解码为字符串
在获取ifconfig输出结果时,直接调用.decode('utf-8')把字节数据转换成字符串,Kali Linux系统下用utf-8编码完全没问题:
ifconfig_result = subprocess.check_output(["ifconfig", options.interface]).decode('utf-8')
2. 修正正则表达式(匹配完整MAC地址)
你当前的正则r"\w\w:\w\w:\w\w:\w\w:\w\w"只匹配了5组两位字符,但标准MAC地址是6组(比如00:11:22:33:44:55),所以要补充一组:
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
3. 增加空值判断(避免匹配失败时报错)
如果因为某些原因(比如接口名错误、MAC修改未生效)导致正则没匹配到MAC地址,直接调用group(0)会触发AttributeError,所以要先检查匹配结果是否存在:
if mac_address_search_result: print(f"[+] Current MAC address: {mac_address_search_result.group(0)}") else: print("[-] Failed to retrieve MAC address.")
修改后的完整代码
#!/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(f"[+] Changing MAC address for {interface} to {new_mac}") options = get_arguments() change_mac(options.interface, options.new_mac) # 修复1:解码字节流为字符串 ifconfig_result = subprocess.check_output(["ifconfig", options.interface]).decode('utf-8') # 修复2:修正正则表达式匹配完整MAC mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result) # 修复3:增加空值判断 if mac_address_search_result: print(f"[+] Successfully changed MAC to: {mac_address_search_result.group(0)}") else: print("[-] Could not verify MAC address change.")
额外小提示
在Kali Linux中,现在有些新版本已经用ip命令替代ifconfig了,如果后续遇到ifconfig不存在的问题,可以把相关命令换成ip link set dev <interface> down、ip link set dev <interface> address <new_mac>、ip link set dev <interface> up,功能是一样的。
内容的提问来源于stack exchange,提问作者Michael Baxter




