我有以下“ arp -a”命令输出列表,只要检测到网络中的设备,该输出就会连续。
['XX.1.60.XX ether XX:16:35:b2:c9:XX C wlan0', 'XXX.168.42.XXX ether XX:35:cd:e8:a5:XX C usb0', 'XX.1.62.XXX ether XX:9f:db:72:61:XX C wlan0', '']
我希望生成一个以IP地址为键,硬件地址为值的字典,即:
{ 'XX.1.60.XX': XX:16:35:b2:c9:XX, 'XXX.168.42.XXX': 'XX:35:cd:e8:a5:XX'}
答案 0 :(得分:0)
使用split()
将行切成单词
data = ['XX.1.60.XX ether XX:16:35:b2:c9:XX C wlan0', 'XXX.168.42.XXX ether XX:35:cd:e8:a5:XX C usb0', 'XX.1.62.XXX ether XX:9f:db:72:61:XX C wlan0', '']
result = {}
for line in data:
try:
ip, _, hardware, _, _ = line.split()
result[ip] = hardware
except ValueError:
# bad line format
pass
print(result)
# {'XX.1.60.XX': 'XX:16:35:b2:c9:XX', 'XXX.168.42.XXX': 'XX:35:cd:e8:a5:XX', 'XX.1.62.XXX': 'XX:9f:db:72:61:XX'}
答案 1 :(得分:0)
使用字典理解:
o = ['XX.1.60.XX ether XX:16:35:b2:c9:XX C wlan0', 'XXX.168.42.XXX ether XX:35:cd:e8:a5:XX C usb0', 'XX.1.62.XXX ether XX:9f:db:72:61:XX C wlan0', '']
o = {v[0]: v[2] for v in (v.split() for v in o) if len(v) >= 3}
print(o)
打印:
{'XX.1.60.XX': 'XX:16:35:b2:c9:XX', 'XXX.168.42.XXX': 'XX:35:cd:e8:a5:XX', 'XX.1.62.XXX': 'XX:9f:db:72:61:XX'}
答案 2 :(得分:0)
这可以做到:
out = {re.findall(r'X.*?(?= )',i)[0]: re.findall(r'X.*?(?= )',i)[1] for i in x if i!=''}
收益:
{'XX.1.60.XX': 'XX:16:35:b2:c9:XX', 'XXX.168.42.XXX': 'XX:35:cd:e8:a5:XX', 'XX.1.62.XXX': 'XX:9f:db:72:61:XX'}
答案 3 :(得分:0)
dict(re.findall(r'([\dX.]+)\s.*?([\dX:a-f]+)\s', line)[0] for line in data if line)
# {'XX.1.60.XX': 'XX:16:35:b2:c9:XX', 'XXX.168.42.XXX': 'XX:35:cd:e8:a5:XX', 'XX.1.62.XXX': 'XX:9f:db:72:61:XX'}