提出需求
現在有這樣的需求:全網的監(jiān)控骨干設備及VPN骨干設備都要新增SSH配置(開通SSH登錄),涉及到的網絡設備上百臺,若一臺臺登錄到設備上去配置,想想工作量都巨大。那么Python的應用來啦。只需要簡單的100來行代碼,就可以自動下發(fā)相應配置到設備上。
會點Python編程的網絡工程師,工作效率嗖嗖嗖的提升!
需要應用到的Python模塊:
- 1、telnetlib 遠程telnet到網絡設備(socket連上后想干嘛干嘛)
- 2、time、datetime模塊(需要表述時間),time模塊的sleep()常常被用到,休眠、停頓的意思。
- 3、multiproccessing 多進程,使用多進程可以節(jié)省時間(多進程占用更多的CPU,區(qū)別于多線程-threading模塊)
- 4、pyMySQL模塊,用它來連接數據庫,操作數據庫。
直接上腳本:(Python2編寫,linux環(huán)境下實測運行正常)
# -*- 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編程基礎,習慣用自動化編程的思維去編程相關運維腳本,工作多年,希望把自己的經驗分享給大家,覺得有用的,可以關注、點贊、轉發(fā),如有相同或者不同觀點,歡迎評論,謝謝!】