美文网首页
python练手--Infoblox WAPI实现DHCP服务备

python练手--Infoblox WAPI实现DHCP服务备

作者: 嵩山奶熊 | 来源:发表于2018-08-09 20:22 被阅读0次

    笔者所在的单位之前更换了DHCP服务,采用了商用的infoblox的DDI解决方案。基本所有操作均在图形化界面上进行设置。但存在一些问题,比如配置备份需要手动备份、多个账号配置修改不知道谁改了什么东西,另一方面单位地址池庞大,有170余个地址池,7万左右ip地址参与自动分配,数据资源非常丰富。

    为了改善这类问题,笔者查阅了一些资料,发现infoblox社区里提供了友善的Infoblox Perl API (PAPI) 、the REST Api (WAPI)、Data and Management API(DMAPI)等等接口。笔者筛选了一下,决定利用WAPI接口写了两段功能性代码完成自动化配置备份、地址信息备份,修改告警的功能。另一方面立足于笔者所在单位的实际情况将WAPI进行二次封装,提取园区内设备IP、MAC、Type、Name信息,为之后数据分析提供基础数据。

    参考网站:
    https://community.infoblox.com/t5/Network-Change-Configuration/Writing-a-rest-client-in-perl/td-p/1909https://pypi.org/project/pyinfoblox/
    https://pypi.org/project/pyinfoblox/

    直接贴上浓郁鲜橙多口味的py代码:

    readinfo.py

    #!/usr/bin/env python
    #encoding=utf-8
    
    from __future__ import print_function
    from pyinfoblox import InfobloxWAPI
    import telnetlib,os,time,sys
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    import email.mime.multipart
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email import Encoders
    
    reload(sys)  
    sys.setdefaultencoding('utf8')  
    
    infoblox = InfobloxWAPI(
        username = '***',
        password = '******',
        wapi = 'https://******/wapi/vx.x/'
    )
    
    #登陆 DHCP服务器
    
    networks = infoblox.network.get()
    
    #读取地址池配置文件
    
    os.system('mv /var/python/beifen/DHCP/beifen/DHCP_networks.txt /var/python/beifen/DHCP/old/DHCP_networks.txt')
    os.system('mv /var/python/beifen/DHCP/beifen/ip_networks.txt /var/python/beifen/DHCP/old/ip_networks.txt')
    
    #将上次备份的全量配置文件转移至old文件夹以便配置恢复
    
    file1 = open('/var/python/beifen/DHCP/beifen/DHCP_networks.txt','wb')
    file = open('/var/python/beifen/DHCP/beifen/ip_networks.txt','wb')
    
    #新建两个文件,一个为地址池配置文件。一个为逻辑筛选的地址池
    
    for i in networks:
        file1.write(str(i))
        try:
            file.write(i['comment'])
            file.write('\n')
        except KeyError:
            file.write('no comment')
            file.write('\n')
        file.write(i['network'])
        file.write('\n')
        file.write('\n')
    
    #筛选地址池comment字段。笔者DHCP是由其他DHCP配置文件导入的,由于编码方式乱码或无备注的问题,进行筛选
    
        if not i['network'].startswith('172'):
    #笔者172开通的网段为无线网段,其中不涉及地址绑定类业务,无需进行修改
            ipv4address = infoblox.ipv4address.get(network = i['network'])
            num = i['network']
            num = num.replace('/','_')
    #读取地址池字段,修改格式
            filename = '/var/python/beifen/DHCP/beifen/' + num + '.txt'
            oldfile = '/var/python/beifen/DHCP/old/' + num + '.txt'
            move = 'mv ' + filename + ' ' + oldfile
            os.system(move)
    #将每个地址池中的配置进行备份,将上次备份的文件保存至old文件夹
            file2 = open(filename,'wb')
            for j in ipv4address:
                if 'fixed' in ''.join(j['objects']):
                    file2.write(j['ip_address'])
                    file2.write('\n')
                    file2.write(j['mac_address'])
                    file2.write('\n')
                    file2.write(str(j['names']))
                    file2.write('\n')
                    file2.write('\n')
            file2.close()
    #将每个地址池中绑定IP进行备份,筛选ip、mac、names字段。保存至该地址池所在文件
    file.close()
    file1.close()
    

    compare.py

    #!/usr/bin/env python
    #encoding=utf-8
    
    import telnetlib,os,time
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    import email.mime.multipart
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email import Encoders
    
    def checknoin(new,old):
        line3 = ''
        send = ''
    
        g = open(old)
        data = g.read()
    
        with open(new) as f:
            line = f.readline()
            while line:
                for j in range(0,4):
                    line3 += line
                    line = f.readline()
                while (not line3 in data):
                    send += line3
                    break;
                line3 = ''
        f.close()
        return send
    
    #对比两个文件配置,返回new中新增的配置信息。由于之前筛选了ip、mac、names字段并用一个换行符区分一段绑定地址。截取4行配置文件对比
    
    def serchfile(dirpath):
        path = '/var/python/beifen/DHCP/beifen/'
        for root,dirs,files in os.walk(dirpath):
            list = files[2:]
        return list
    
    #备份路径下筛选所有配置文件,除去前两个文件。前两个文件分别为DHCP_networks.txt的全量配置文件及ip_networks.txt筛选过后的network配置信息
    
    def sendmail(addmessage,removemessage,datapath,name):
        sender = '**@***.***.edu.cn'
        username = '**@***.***.edu.cn'
        passwd = '******'
        receiver = ['**@***.***.edu.cn','**@***.***.edu.cn']
        smtpserver = '**.***.edu.cn'
    
    #配置邮箱用户名、密码,配置发件人、收件人、smtpserver。可直接改成163或qq邮箱
    
        subject = 'DHCP fixed address change'
    
    #邮件主题
    
        #msg = MIMEText(content)
        msg = MIMEMultipart()
    
        msg['Subject'] = Header(subject,'utf-8')
        msg['From'] = sender
        msg['To'] = ';'.join(receiver)
    #配置文件参数写入
        if os.path.exists(datapath + name):
            content = 'this network has been modified.<br><br><br>fixed address has been added:<br>' + addmessage.replace('\n','<br>') + '<br><br>fixed address has been removed:<br>' + removemessage.replace('\n','<br>')
            body = MIMEText(content, _subtype='html', _charset='gb2312')
            msg.attach(body)
            part = MIMEBase('application','octet-stream')
            part.set_payload(open(datapath + name ,'rb').read())
            Encoders.encode_base64(part)
    #写邮件内容
            part.add_header('Content-Disposition','attachment', filename = name )
            msg.attach(part)
    #将地址池的配置文件添加至邮件附件
        else:
            content = 'Error! no backup file found'
            body = MIMEText(content, _subtype='html', _charset='gb2312')
            msg.attach(body)
    #配置错误信息
        smtp = smtplib.SMTP(smtpserver)
        smtp.login(username,passwd)
    
        smtp.sendmail(sender, receiver, msg.as_string())
    #送件
        #except s.SMTPException,e:
        #    print '发送失败'
    
        smtp.quit()
        #print ('send email successful')
    
    
    if __name__ == '__main__':
    
        newpath = '/var/python/beifen/DHCP/beifen/'
        oldpath = '/var/python/beifen/DHCP/old/'
        namelist = serchfile(newpath)
        for i in namelist:
            filename = newpath + i
            oldfile = oldpath + i
            add = checknoin(filename,oldfile)
            rem = checknoin(oldfile,filename)
    #对每一个地址池的配置文件进行检查,是否有增删改
            if ( bool(add) or bool(rem) ):
                sendmail(add,rem,newpath,i)
    #如有修改,发送告警邮件
    

    效果截图:

    部分文件备份:


    beifen.png

    全备文件:


    quanbei.png
    配置变动告警:
    change.png

    数据分析

    笔者随便找了一个地址池为例,来一起看一下Infoblox IPAM 中对于地址状态的定义,如下图:


    type.png

    看到一些常用状态:unused、used、fixed、lease等。笔者来对比一下获取到的原始日志。
    获取代码:

    ipv4address = infoblox.ipv4address.get(network='***.***.**.0/25')
    print(ipv4address)
    

    以broadcast地址为例,查看unused状态地址:

    {u'status': u'USED', u'network': u'***.***.**.0/25', u'network_view': u'default', u'usage': [], u'objects': [], u'names': [], u'mac_address': u'', u'types': [u'BROADCAST'], u'_ref': u'ipv4address/Li5pcHY0X2FkZHJlc3MkMjAyLjEyMC45NS4xMjcvMA:***.***.**.***', u'ip_address': u'***.***.**.***', u'is_conflict': False}
    

    查看fixed状态地址:

    {u'status': u'USED', u'network': u'***.***.**.0/25', u'network_view': u'default', u'lease_state': u'FREE', u'usage': [u'DHCP'], u'objects': [u'fixedaddress/ZG5zLmZpeGVkX2FkZHJlc3MkMjAyLjEyMC45NS4xMTkuMC4u:***.***.**.***/default'], u'names': [u'baihao-server'], u'mac_address': u'68:b5:99:70:**:**', u'types': [u'FA', u'DHCP_RANGE'], u'_ref': u'ipv4address/Li5pcHY0X2FkZHJlc3MkMjAyLjEyMC45NS4xMTkvMA:***.***.**.***', u'ip_address': u'***.***.**.***', u'is_conflict': False}
    

    查看active-lease状态地址:

    {u'status': u'USED', u'network': u'***.***.**.0/25', u'network_view': u'default', u'lease_state': u'ACTIVE', u'usage': [u'DHCP'], u'objects': [u'lease/ZG5zLmxlYXNlJDAvMjAyLjEyMC45NS4xMjMvMC8:***.***.**.***/default'], u'names': [u'TL-WR720N'], u'mac_address': u'14:cf:92:62:**:**', u'types': [u'LEASE', u'DHCP_RANGE'], u'_ref': u'ipv4address/Li5pcHY0X2FkZHJlc3MkMjAyLjEyMC45NS4xMjMvMA:***.***.**.***', u'ip_address': u'***.***.**.***', u'is_conflict': False, u'dhcp_client_identifier': u'"\\001\\024\\317\\222b>\\345"'}
    

    查看unused状态地址:

    {u'status': u'USED', u'network': u'***.***.**.0/25', u'network_view': u'default', u'lease_state': u'FREE', u'usage': [u'DHCP'], u'objects': [u'lease/ZG5zLmxlYXNlJDAvMjAyLjEyMC45NS4xMTcvMC8:***.***.**.***/default'], u'names': [], u'mac_address': u'c8:14:51:23:**:**', u'types': [u'LEASE', u'DHCP_RANGE'], u'_ref': u'ipv4address/Li5pcHY0X2FkZHJlc3MkMjAyLjEyMC45NS4xMTcvMA:***.***.**.***', u'ip_address': u'***.***.**.***', u'is_conflict': False}
    

    笔者溜了一遍单位地址,基本这四类地址占了99%。很清楚,unused地址'usage'字段为空,active-lease地址'lease_state'字段为active,fixed地址'objects'字段中包含'fixedaddress',unused地址'lease_state'字段为'FREE'且'objects'字段中包含'lease'。

    筛选有效数据对于任意一门程序语言都很轻松,基本把每个network的有效字段筛出来个dictionary或者matrix就各位随意了。

    由于mac地址是无法在三层网络直接传输的,因此只能通过IP来找到网关定位一台主机。而对于笔者单位的园区网而言基本很难通过mac地址直接锁定一台电脑。但是对于DHCP而言,mac-ip-name-type是实时关联的,这就为在园区随时定位任意一台主机提供了方案。

    设备查询API接口封装和园区内任意设备的大数据分析方案下一节再来探讨吧~

    相关文章

      网友评论

          本文标题:python练手--Infoblox WAPI实现DHCP服务备

          本文链接:https://www.haomeiwen.com/subject/qmihvftx.html