1、在备份配置之前进行ping操作,所有IP地址放在HW_IP_List.txt中,ping通的地址放到HW_IP_True.txt中,ping不通的地址放到HW_IP_False.txt中。
脚本文件icmp_reply.py
#!/usr/bin/python
# -*- coding:gb2312 -*-
#import tab
import time,os
start_time = int (time.time())
def hw_ping_test():
ips = open('HW_IP_List.txt','r')
ip_True = open('HW_IP_True.txt','w')
ip_False = open('HW_IP_False.txt','w')
count_True,count_False=0,0
for ip in ips.readlines():
ip = ip.replace('\n','')
return1= os.system('ping -n 1 -w 1 %s'%ip)
if return1 :
print 'ping %s is fail'%ip
ip_False.write(ip+'\n')
count_False += 1
else:
print 'ping %s is ok'%ip
ip_True.write(ip+'\n')
count_True += 1
ip_True.close()
ip_False.close()
ips.close()
end_Time = int(time.time())
print "time(sencond):",end_Time - start_time,"s"
print "ping OK IP:",count_True," ping False IP:",count_False
hw_ping_test()
2、编辑核心脚本,调用icmp_reply.py,程序执行时会先自动运行icmp_reply.py,调用生成的HW_IP_True.txt文件,先要选择设备类型,然后选择执行的动作,输入TFTP服务器地址,程序就开始执行选择的相应的动作。
#!/usr/bin/python
#coding=utf-8
import telnetlib
import time
import re
import icmp_reply
LogTime = time.strftime('%Y-%m-%d_%H-%M-%S')
Device = raw_input('''Please Select Device
1:HuaWei;
2:HillStone(E1700/M3108);
3:H3C-3620;
Put Device ID:''') #选择设备类型,华为,山石和H3C-3620
if Device == '1': #华为相关
action = raw_input('''Please Select Action :
1:Config & Backup;
2:Backup;
Put Your Choose:''') #选择要做的动作,备份or 配置+备份
tftp = raw_input('Please Enter TFTP Sever IP:')
for line in open("HW_IP_True.txt"):
Host = line.replace('\n','')
UserName = 'admin'
PassWord = 'passw0rd'
save = 'save'
display = 'display cur'
try:
tn = telnetlib.Telnet(Host)
tn.read_until('Username:')
tn.write(UserName+'\n')
tn.read_until('Password:')
tn.write(PassWord+'\n')
if action == '1' :
config = open("hw_script.txt",'r')
for conf in config.readlines(): #配置脚本
tn.write(conf+'\n')
tn.write(b'\n')
telreply = tn.expect([],timeout=1)[2].encode("utf-8") #获取Telnet交互信息
DeviceName = (re.findall(str(".*<(.*)>.*"),telreply))[0] #生成的设备名称是个list。后面调用列表里面的索引0
tn.write(save+' '+DeviceName+'-'+LogTime+'.cfg'+'\n') #保存当前配置
tn.read_until('N]')
tn.write('y'+'\n')
tn.read_until('successfully.')
tn.write('tftp'+' '+tftp+' '+'put'+' '+'flash:/'+DeviceName+'-'+LogTime+'.cfg'+'\n' ) #使用tftp导出系统配置
time.sleep(2)
tn.write('quit'+'\n')
tn.close()
elif action == '2':
tn.write(b'\n')
telreply = tn.expect([],timeout=1)[2].encode("utf-8") #获取Telnet交互信息
DeviceName = (re.findall(str(".*<(.*)>.*"),telreply))[0] #生成的设备名称是个list。后面调用列表里面的索引0
tn.write(save+' '+DeviceName+'-'+LogTime+'.cfg'+'\n')
tn.read_until('N]')
tn.write('y'+'\n')
tn.read_until('successfully.')
tn.write('tftp'+' '+tftp+' '+'put'+' '+'flash:/'+DeviceName+'-'+LogTime+'.cfg'+'\n' )#使用tftp导出系统配置
time.sleep(2)
tn.write('quit'+'\n')
tn.close()
print Host,'Backup Success !!'
except :
print Host,'Backup Failed !!'