第一种是使用arping工具:
1 #!/usr/bin/env python 2 import subprocess 3 import sys 4 import re 5 6 def arping(ipaddress = "192.168.1.1"): 7 p = subprocess.Popen("/usr/sbin/arping -c 2 %s" % ipaddress, shell = True, 8 stdout = subprocess.PIPE) 9 out = p.stdout.read() 10 result = out.split() 11 for item in result: 12 if ":" in item: 13 print item 14 15 if __name__ == "__main__": 16 if len(sys.argv) > 1: 17 for ip in sys.argv[1:]: 18 print "arping", ip 19 arping(ip) 20 else: 21 arping()
这种方法依赖于特定平台的工具,整体就是使用了一个系统调用。
第二种是使用scapy,这种方法可以实现平台无关化
1 #!/usr/bin/env python 2 from scapy import srp,Ether,ARP,conf 3 import sys 4 5 def arping(iprange="192.168.1.1/24"): 6 conf.verb = 0 7 ans,unans = srp(Enter(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=iprange), 8 timeout=2) 9 collection = [] 10 for snd, rcv in ans: 11 result = rcv.sprintf(r"%ARP.psrc% %Ether.src%").split() 12 collection.append(result) 13 return collection 14 15 if __name__ == "__main__": 16 if len(sys.argv) > 1: 17 for ip in sys.argv[1:]: 18 print "arping", ip 19 print arping(ip) 20 else: 21 print arping()