问题
I need to determine my device's MAC (hardware) address, ie that for the wifi. I'm using Termux on an Android device, although maybe an answer will apply more generally.
I'm using python, but any bash would be okay too.
On some 2017 devices, the following used to work:
import subprocess
result = subprocess.run(['ip','link'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
rc,so, se = result.returncode, result.stdout, result.stderr
assert not rc
ipl = re.split('\n[^ ]+ ', so, re.MULTILINE)
wlanl = [L for L in ipl if L.startswith('wlan0')]
assert wlanl
HWadd = re.findall('link/ether (.*?) ',wlanl[0])[0].lower()
however, this is failing strangely (I cannot get re.split to work as I expect) on a new 2019 device.
Instead, I now have a nearly equally ungainly alternative that works:
import subprocess
result = subprocess.run(['ip','link'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
rc,so, se = result.returncode, result.stdout, result.stderr
assert not rc
ipl = re.findall('\n[0-9]+: wlan0:.*?\n +link/ether ([^\n]*?) .*?\n', so, re.MULTILINE+ re.DOTALL)
assert ipl
HWadd = ipl[0].lower()
Is there a more reliable way to extract this information from the OS somewhere?
By the way, using termux-wifi-connectioninfo
gives:
"mac_address": "02:00:00:00:00:00"
回答1:
I didn't try your Python example, but what you're doing works in bash:
~ $ ip link | grep -A1 wlan0
25: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DORMANT group default qlen 3000
link/ether aa:bb:cc:11:22:33 brd ff:ff:ff:ff:ff:ff
There is also a feature request to add moreutils which would be able to do this with ifdata -ph wlan0
if it's added.
来源:https://stackoverflow.com/questions/58463658/how-to-determine-wifi-hardware-address-in-termux