python-华为路由器交换机批量处理ip与mac绑定

python-华为路由器交换机批量处理ip与mac绑定,第1张

python-华为路由器交换机批量处理ip与mac绑定
    • 以下为代码
    • 运行后会产生日志文件

以下为代码
#-*- coding: utf-8 -*-
#!/usr/bin/python 
#仅供相互学习
#本次脚本测试环境为华为路由器
#

一、通过dis arp命令查看arp表 #

二、把一行ip与mac存为一个元组,再把元组存在列表里 #

三、因为192.168.0.0/16网段为管理接口网段不需要绑定所以过滤掉 #

四、mac地址有重复的元组会被过滤掉 #

五、ip-mac-bind.xls存放需要 *** 作的设备ip import paramiko import threading import time import os import xlrd import re #这里引入了第三方模块,cmd运行pip install 相关模块即可 #定义连接与 *** 作 def ssh2(ip,username,passwd,cmd): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,22,username,passwd,timeout=5) ssh_shell = ssh.invoke_shell() for m in cmd: res = ssh_shell.sendall(m) time.sleep(float(1)) print (ssh_shell.recv(1024)) ssh.close() except : print ('%s\tError\n'%(ip)) #定义读取excel函数 def read_excel_data(): filename = 'ip-mac-bind.xls' data = xlrd.open_workbook(filename) table = data.sheet_by_name('Sheet1') row_num = table.nrows # 行数 # col_num = table.ncols # 列数 datas=[] for i in range(row_num): datas.append(table.row_values(i)[0]) return datas def sshSwitch(ip,username,passwd): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,22,username,passwd,timeout=5) ssh_shell = ssh.invoke_shell() ssh_shell.send('user-interface vty 0 4 \n') ssh_shell.send('screen-length 0 \n') ssh_shell.send('dis arp \n') # time.sleep(float(5)) index=0 contentArr=[] while True: index+=1 stdout=ssh_shell.recv(9999) decon=str(stdout) contentArr.append(decon) #当屏幕输入Total时候停止 if 'Total' in decon: break; finalResult=''.join(contentArr) matchResult= re.findall('(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).+?([a-zA-Z\d]{4}-[a-zA-Z\d]{4}-[a-zA-Z\d]{4})',finalResult)#正则匹配ip 与 mac if matchResult: macCount=dict() # print(matchResult) for bind in matchResult: if bind[0][0:7] != '192.168':#过滤192.168.0.0/16网段 mac = bind[1] macCount[mac]=mac not in macCount# 简化下面4行代码,这里过滤重复的mac地址 # if mac in macCount: # macCount[mac]=False # else: # macCount[mac]=True for bind in matchResult: mac = bind[1] # print(bind) if bind[0][0:7] != '192.168' and macCount[mac]: #这里排除192.168.0.0/24地址的IP地址绑定 #这里匹配到IP mac并且拼接好了命令 docmd=(f' user-bind static ip-address {bind[0]} mac-address {bind[1]}') print(docmd) ssh_shell.send('end \n') ssh_shell.send('system-view \n') ################################################################################# #以下为执行 *** 作的代码,执行前先打印结果。


确认后再执行。


################################################################################ ssh_shell.send(f'{docmd} \n') # print(docmd) with open("ip-mac-bind-dolog.txt","a+") as f: f.write(f'连接{ip} *** 作命令{docmd} \n') time.sleep(float(0.5)) ssh_shell.send('end \n') ssh_shell.send('sys \n') ssh_shell.send('user-interface vty 0 4 \n') ssh_shell.send('undo screen-length \n') ssh_shell.send('end \n') ssh_shell.send('save \n') ssh_shell.send('y \n') with open("ip-mac-bind-dolog.txt","a+") as f: f.write('运行结束 结束时间:') f.write(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))+'\n') print ('%s执行完成'%(ip)) ssh.close() except Exception as e : print(e) with open("ip-mac-bindlog.txt","a+") as f: f.write(f'{ip} 连接异常'+'\n') print ('\n'+'%s连接异常'%(ip)) #设置交换机SSH用户名密码及线程 username = "cc" #用户名 passwd = "cc123" #密码 threads = 3 #多线程 if __name__=='__main__': print ("Begin......") swip =read_excel_data() thread_list=[] count1=0 count2=0 #print (swip[0]) while True: ip=swip[count2] a=threading.Thread(target=sshSwitch,args=(ip,username,passwd)) thread_list.append(a) a.start() print(ip+'执行') count2+=1 if count2%threads==0: print('线程超过'+str(threads)+',等待资源') while True: thread_list[count1].join() count1+=1 if count1==count2: print('资源释放完毕') break if count2>=len(swip): time.sleep(10) print(('执行结束')) with open("ip-mac-bindlog.txt","a+") as f: f.write('本次运行结束 结束时间:') f.write(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))+'\n') break

运行后会产生日志文件

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/568803.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存