多程序--利用堡壘機備份網路裝置配置
阿新 • • 發佈:2019-01-10
想利用Threading實現併發,但是失敗了。懷疑在多個執行緒下 con.expect( ) 為同一id,需要額外對con.expect 或 send 實現執行緒安全,因為總是報timeout,匹配不到字串。
為了防止多程序在讀取裝置列表時重複複製相同資料,又捨近求遠用multiprocessing.Manager()折騰很久失敗,沒明白Manager().Queue()為什麼會不成功。
#!/usr/bin/env python
#coding=utf-8"""
Collecting configuration with a jumpserver.
Yong Peng 2017-09-05
"""
import time
import pexpect
import os
import sys
import multiprocessing
#import getpass
__version__ = '3.0'
#time = time.strftime('%y.%m.%d-%H:%M:%S')
Dir_name = time.strftime('%Y%m%d')
if not os.path.lexists('/config_bak/{}'.format(Dir_name)):
os.system('mkdir /config_bak/{}'.format(Dir_name))
#登入堡壘機的帳號
#Password = getpass.getpass('Pls input password: ')
Username = 'usernameXX'
Pwd = 'passXX'
#登入裝置的帳號
Login_user = 'usernameYY'
Login_pwd = 'passYY'
Enable_pwd = 'enableYY'
command_set1 = ['show run\n', 'show vlan\n', 'show interface status\n']
command_set2 = ['show run\n', 'show ap-config summ\n', 'show ap-config run\n']
command_set3 = ['dis curr \n', 'dis interface brief\n']
#堡壘機登入
def Login(IP):
global con
con = pexpect.spawn('/usr/bin/ssh {}@8.8.8.8 -p 8822'.format(Username),maxread=2000000, logfile=None,encoding=None)
Counter1 = 0
while True:
#防止因認證錯誤,堡壘機登入無限迴圈嘗試
result = con.expect(['.*Password: ', '.*Select group: ', '.*Select page: ', '.*Select server: '])
if result == 0:
con.send(Pwd + '\n')
Counter1 += 1
if Counter1 <3:
continue
else:
print "Jumpserver authentication failure"
sys.exit(1)
#已登入堡壘機,在堡壘機提示選擇組時.輸入選擇0,否則無法根據IP跳轉資源
elif result == 1:
con.send('0\n')
continue
#跳轉到可根據IP跳轉資源的介面
elif result == 2 or 3:
break
#網路裝置登入
Counter2 = 0
while True:
#開始跳轉到要進行配置備份的裝置
con.send(IP + '\n')
time.sleep(1)
result = con.expect(['.*Select group: $', '.*Select page: $', '.*Select server: $', '.*Input account: $'])
if result == 3:
con.send(Login_user + '\n')
time.sleep(1)
con.expect('.*password: ')
time.sleep(1)
con.send(Login_pwd + '\n')
time.sleep(1)
break
else:
Counter2 += 1
if Counter2 < 3:
continue
else:
print 'There is no such a device'
# sys.exit(11)
break
#銳捷交換機
def Device_type1(bak_file):
con.expect('.*>$')
con.send('enable\n')
time.sleep(1)
con.expect('Password:')
time.sleep(1)
con.send(Enable_pwd + '\n')
time.sleep(1)
con.expect('.*#$')
con.send('\n')
time.sleep(1)
con.expect('.*#$')
#定義寫入檔案
con.logfile = bak_file
#進行備份配置
for i in command_set1:
con.send(i)
while True:
result = con.expect([' --More-- $', '.*#$'])
if result == 0:
time.sleep(0.3)
con.send(' ')
continue
else:
con.send('\n')
con.expect('.*#$')
break
bak_file.close()
con.close()
#銳捷AC(與Device_type1一模一樣,除了command_set以外)
def Device_type2(bak_file):
con.expect('.*>$')
con.send('enable\n')
con.expect('Password:')
con.send(Enable_pwd + '\n')
con.expect('.*#$')
con.send('\n')
con.expect('.*#$')
#定義寫入檔案
con.logfile = bak_file
#進行備份配置
for i in command_set2:
con.send(i)
while True:
result = con.expect(['.*--More-- $', '.*#$'])
if result == 0:
time.sleep(0.1)
con.send(' ')
continue
else:
con.send('\n')
con.expect('.*#$')
break
bak_file.close()
con.close()
#H3C防火牆
def Device_type3(bak_file):
con.expect('.*>')
con.send('\n')
con.expect('.*>')
#定義寫入檔案
con.logfile = bak_file
#進行備份配置
for i in command_set3:
con.send(i)
while True:
result = con.expect(['---- More ----', '.*>'])
if result == 0:
time.sleep(0.3)
con.send(' ')
continue
else:
con.send('\n')
con.expect('.*]')
break
bak_file.close()
con.close()
#定義執行緒執行的函式
def bak():
while not q.empty():
i3 = q.get()
IP = i3.split(',')[0]
Device_name = i3.split(',')[1]
bak_file = open('/config_bak/{}/{}.txt'.format(Dir_name, Device_name), 'w')
# try:
Login(IP)
if i3.split(',')[2].strip() == 'switch' :
Device_type1(bak_file)
elif i3.split(',')[2].strip() == 'AC' :
Device_type2(bak_file)
elif i3.split(',')[2].strip() == 'H3C' :
Device_type3(bak_file)
# except Exception:
# print 'Script Error'
q = multiprocessing.Queue()
with open('/config_bak/device_list.txt','r') as List:
for i in List.readlines():
q.put(i)
for i in range(5):
r = multiprocessing.Process(target=bak)
r.start()