看我怎么通过Python脚本给100台网络设备一键化下发相同的配置

提出需求现在有这样的需求:全网的监控骨干设备及VPN骨干设备都要新增SSH配置(开通SSH登录),涉及到的网络设备上百台,若一台台登录到设备上去配置,想想工作量都巨大 。那么Python的应用来啦 。只需要简单的100来行代码,就可以自动下发相应配置到设备上 。
会点Python编程的网络工程师,工作效率嗖嗖嗖的提升!
需要应用到的Python模块:

  • 1、telnetlib 远程telnet到网络设备(socket连上后想干嘛干嘛)
  • 2、time、datetime模块(需要表述时间),time模块的sleep()常常被用到,休眠、停顿的意思 。
  • 3、multiproccessing 多进程,使用多进程可以节省时间(多进程占用更多的CPU,区别于多线程-threading模块)
  • 4、pyMySQL模块,用它来连接数据库,操作数据库 。
直接上脚本:(Python2编写,linux环境下实测运行正常)# -*- coding: UTF-8 -*-#! /usr/bin/python2.7import telnetlibimport datetimeimport timefrom time import sleepfrom multiprocessing import Processimport pymysql.cursorsdef GO(H, ip,device_type_id):username = 'username'password = 'password'if device_type_id == 20:tn = telnetlib.Telnet(ip)tn.read_until('login:', timeout=3)tn.write(username + 'n')tn.read_until('Password:', timeout=3)tn.write(password + 'n')time.sleep(4)tn.write('su' + 'n')tn.read_until('Password:', timeout=3)tn.write('hzcnc_enable' + 'n')time.sleep(3)tn.read_until('>', timeout=3)tn.write('sys n ssh server enable n ssh server acl 2001n quitn')time.sleep(2)tn.close()print "H3C-%s is OK! Now time is %s" % (H, datetime.date.today())#interface_config.close()if device_type_id == 21 or device_type_id == 22 or device_type_id == 24 or device_type_id == 19:tn = telnetlib.Telnet(ip)tn.read_until('Username:', timeout=3)tn.write(username + 'n')tn.read_until('Password:', timeout=3)tn.write(password + 'n')time.sleep(4)tn.write('su' + 'n')tn.read_until('Password:', timeout=3)tn.write('hzcnc_enable' + 'n')time.sleep(3)tn.read_until('>', timeout=3)tn.write('sys n ssh server enable n ssh server acl 2001n quitn')time.sleep(2)tn.close()print "H3C-%s is OK! Now time is %s" % (H, datetime.date.today())if device_type_id == 23 or device_type_id == 16:tn = telnetlib.Telnet(ip)tn.read_until('login:', timeout=3)tn.write(username + 'n')tn.read_until('Password:', timeout=3)tn.write(password + 'n')time.sleep(3)tn.write('su' + 'n')tn.read_until('Password:', timeout=3)tn.write('hzcnc_enable' + 'n')time.sleep(3)tn.read_until('>', timeout=3)tn.write('sys n ssh server enable n ssh server acl 2001n quitn')time.sleep(2)tn.close()print "H3C-%s is OK! Now time is %s" % (H, datetime.date.today())if __name__ == '__main__':connection = pymysql.connect(host='localhost',user='username',password='passwd',db='db_name',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)try:with connection.cursor() as cursor:sql = "SELECT name, manage_ip, device_type_id FROM devices WHERE device_role_id=6"# sql = "SELECT name, manage_ip, device_type_id FROM dcim_device WHERE manage_ip ='device_ip'"cursor.execute(sql)result = cursor.fetchall()finally:connection.close()for x in result:p = Process(target=GO, args=(str(x['name']),str(x['manage_ip']),int(x['device_type_id']),))p.start()sleep(2)配置结果:
看我怎么通过Python脚本给100台网络设备一键化下发相同的配置

文章插图
完美配置完毕
【笔者为网络工程师,懂点Python编程基础,习惯用自动化编程的思维去编程相关运维脚本,工作多年,希望把自己的经验分享给大家,觉得有用的,可以关注、点赞、转发,如有相同或者不同观点,欢迎评论,谢谢!】

【看我怎么通过Python脚本给100台网络设备一键化下发相同的配置】


    推荐阅读