我正在为Linux编写一个简单的程序,该程序查看mac地址。我的程序应查看“ ifconfig
”,并使用正则表达式仅提取MAC地址。
import subprocess
import re
print('This program will only look at the mac address.')
print('Enter your interface.(for example: wlan0))')
interface = input(': ')
find_mac = subprocess.check_output(["ifconfig", interface], shell=True)
mac_clean = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w\:\w\w", find_mac)
print(mac_clean.group(0))`
我希望的输出为MY:MAC:ADDRESS
,但实际输出为
mac_clean = re.search(r“ \ w \ w:\ w \ w:\ w \ w:\ w \ w:\ w \ w:\ w \ w”,find_mac)
搜索中的文件“ /usr/lib/python3.7/re.py”,第183行
返回_compile(模式,标志).search(字符串)
TypeError:无法在字节上使用字符串模式-如对象
答案 0 :(得分:0)
subprocess.check_output的结果是字节,因此需要一个字符串才能工作
mac_clean = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w\:\w\w", find_mac.decode())
您可以使用bytes.decode
您还可以通过psutils
轻松地了解到这篇文章link
答案 1 :(得分:-1)
首先,将find_mac转换为字符串。
find_mac = subprocess.check_output(["ifconfig", interface], shell=True).decode()
然后,针对您在正则表达式中的模式。
mac_clean = re.search(r"^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$", find_mac)
有关正则表达式的一些教程和文档:
编辑:根据@Reznik注释纠正错误
Edit1:修复正则表达式