自动获取交换机ARP信息(IP/MAC),多次执行程序可实现最新ARP信息(IP/MAC)与上次执行ARP信息(IP/MAC)对比,自动比对变化情况,输出变化的ARP信息(IP/MAC)
import telnetlib, re, os, time
username = "user"#交换机管理账户
password = "password"#交换机管理密码
ip = "192.168.1.1"#交换机管理IP地址
def get_arp():
tn = telnetlib.Telnet(ip)
tn.read_until(b'Username', timeout=8)
tn.write(username.encode('ascii') + b"\n")
tn.read_until(b'Password', timeout=8)
tn.write(password.encode('ascii') + b"\n")
time.sleep(1)
tn.write("dis arp interface Vlanif 144".encode('ascii') + b"\n")
time.sleep(1)
result = tn.read_very_eager().decode('ascii')
i = 1
while True:
if "More" in result:
result = result.strip("---- More ----")
i += 1
tn.write(b" ")
time.sleep(1)
result += tn.read_very_eager().decode('ascii')
else:
break
return result
def save_arp():
arp = get_arp()
if not os.path.exists("ARP表"):
os.mkdir("ARP表")
with open("ARP表/arp.txt", "w+") as f:
f.write(arp)
with open('ARP表/arp.txt') as f, open('ARP表/arp.bak', 'w', encoding='utf-8') as f1:
for line in f:
# line=re.match(
# "(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d).{19}",
# line)
line = re.match(
"(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\s*(\w{4}-\w{4}-\w{4})",
line)
if line is not None:
line = ','.join(line.group().split())
arp_list = line.split(",")
arp_dict = {}
arp_dict["ip"] = arp_list[0]
arp_dict["mac"] = arp_list[1]
# arp_dict[arp_list[0]]=arp_list[1]
# print(arp_dict)
f1.write(str(arp_dict) + "\n")
os.remove('ARP表/arp.txt')
filename = ip + "_" + time.strftime("%Y%m%d_%H-%M-%S") + '.txt'
os.rename('ARP表/arp.bak', "ARP表/" + filename)
with open("fileDirectory.txt", "a+") as f:
f.write(filename + "\n")
return filename
def check_arp():
new_arp_filename = save_arp()
if not os.path.exists("Check表"):
os.mkdir("Check表")
with open("fileDirectory.txt", ) as fileDirectory:
old_arp_filename = fileDirectory.readlines()
old_count = len(open("ARP表/" + old_arp_filename[-2].strip()).readlines())
with open("ARP表/" + new_arp_filename) as f:
for new in f:
new = eval(new)
old_flag = 0
with open("ARP表/" + old_arp_filename[-2].strip()) as f1:
for old in f1:
old = eval(old)
old_flag += 1
if new["ip"] == old["ip"] and new["mac"] == old["mac"]:
break
else:
if old_flag == old_count:
checkARP = "checkARP" + ip + time.strftime("%Y%m%d_%H-%M-%S") + '.txt'
with open("Check表/" + checkARP, "a+") as checkARP:
checkARP.write(str(new)+"\n")
print(new)
break
else:
continue
if __name__ == '__main__':
check_arp()