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

该脚本主要用于华为路由器,通过disarp命令获取ARP表,过滤并处理192.168.0.0/16网段,避免重复绑定,然后使用paramiko库进行SSH连接,执行IP-MAC静态绑定操作。脚本读取Excel文件获取设备IP,并使用多线程执行,最后将操作记录写入日志文件。
摘要由CSDN通过智能技术生成

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-z\d]{4}-[a-z\d]{4}-[a-zd]{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

运行后会产生日志文件

请添加图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值