现在有这样的需求:全网的监控骨干设备及VPN骨干设备都要新增SSH配置(开通SSH登录),涉及到的网络设备上百台,若一台台登录到设备上去配置,想想工作量都巨大。那么Python的应用来啦。只需要简单的100来行代码,就可以自动下发相应配置到设备上。
会点Python编程的网络工程师,工作效率嗖嗖嗖的提升!
# -*- coding: UTF-8 -*-
#! /usr/bin/python2.7
import telnetlib
import datetime
import time
from time import sleep
from multiprocessing import Process
import pymysql.cursors
def 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编程基础,习惯用自动化编程的思维去编程相关运维脚本,工作多年,希望把自己的经验分享给大家,觉得有用的,可以关注、点赞、转发,如有相同或者不同观点,欢迎评论,谢谢!】