当前位置:   article > 正文

python-华为路由器交换机批量处理ip与mac绑定_华为ar 61211e-s怎么批量导入mac ip绑定

华为ar 61211e-s怎么批量导入mac ip绑定

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169

运行后会产生日志文件

请添加图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/293313
推荐阅读
相关标签
  

闽ICP备14008679号