0
import subprocess
import re

interface = input(" interface : ")
new_mac = input("new MAC : ")

print("Changing " + interface + " to " + new_mac)

subprocess.call(["ifconfig", interface, "down"])
subprocess.call(["ifconfig", interface, "hw", "ether", new_mac])
subprocess.call(["ifconfig", interface, "up"])
subprocess.call(["ifconfig"])

ifconfig_result = subprocess.check_output(["ifconfig", "eth0",])
print(ifconfig_result)

mac_addr_searchresult = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
print(mac_addr_searchresult.group(0))

I want the output to be just the mac address but it keeps returning me TypeError: cannot use a string pattern on a bytes-like object

1 Answers1

0

As tripleee pointed in comment another simple fix for Python 3.7+ would be to just to pass text=True parameter in check_output

ifconfig_result = subprocess.check_output(["ifconfig", "eth0",], text=True)

According to Python3 doc:

By default, check_output will return the data as encoded bytes

Since the data is encoded bytes you need to convert it to string, for that you can use bytes.decode (by default the encoding is utf-8 for bytes.decode)

ifconfig_result = subprocess.check_output(["ifconfig", "eth0",])
ifconfig_result = ifconfig_result.decode()

Or you can bytes.decode it while passing to re.search

mac_addr_searchresult = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result.decode())

If you want the output directly as string you can use subprocess.getoutput

Chandan
  • 11,465
  • 1
  • 6
  • 25
  • 1
    Actually the simplest fix by far in Python 3.7+ is to add `text=True` to the keyword arguments. (The same flag was called `universal_newlines=True` in 3.5+) – tripleee May 16 '22 at 09:24