我是Python初学者,希望您能帮我解决这个问题。
我有一个写在文件中的 mac 地址列表。我需要获取网络上的 mac 地址列表,将它们与文件中的地址进行比较,然后在 stdout 中打印文件中未在网络地址列表中找到的地址。
最后用这些地址更新文件。
现在我设法读取了一个我作为参数提供的文件:
import sys
with open(sys.argv[1], 'r') as my_file:
lines = my_file.read()
my_list = lines.splitlines()
我正在尝试通过从 python 运行进程 arp 来读取 mac 地址:
import subprocess
addresses = subprocess.check_output(['arp', '-a'])
但是通过这段代码我得到了这个:
Internet Address Physical Address Type
156.178.1.1 5h-c9-6f-78-g9-91 dynamic
156.178.1.255 ff-ff-ff-ff-ff-ff static
167.0.0.11 05-00-9b-00-00-10 static
167.0.0.123 05-00-9b-00-00-ad static
.....
我如何在此处进行过滤以便仅获取 mac 地址列表?
或者我可以像这样检查两个列表以查看文件中的 mac 地址是否在网络上,如果不在则将其打印出来?
最佳答案
从你拥有的开始:
networkAdds = addresses.splitlines()[1:]
networkAdds = set(add.split(None,2)[1] for add in networkAdds if add.strip())
with open(sys.argv[1]) as infile: knownAdds = set(line.strip() for line in infile)
print("These addresses were in the file, but not on the network")
for add in knownAdds - networkAdds:
print(add)
关于Python获取mac地址列表并将它们与文件列表进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33765539/