Python implements the TFTP backup configuration file example for a digital device

  • 2020-04-02 13:34:28
  • OfStack

 

Environment: [wind2003[open Tftp server] + virtualbox: ubuntu 10 server]
TFTP: Open TFTP Server    
ubuntn  
Python + pyexpect
Why virtual machines: pyexpect does not support Windows  

Note: the original intention is to use secrueCrt script, because the practice found no use of Linux under pexpect easy to use, flexible   , used to use expect because TCL [syntax] is not as easy to use and easy to maintain as python

Reasons to write some programs:
Recently, there has been a serious failure: due to the bug of netscreen device, the main and standby devices of one node failed at the same time. After replacing the device, it was found that the backup configuration file appeared garbled [Chinese] and could not be used directly.
Considering that the device is in the Intranet, there are nearly 300 digital devices, so the original TFTP backup method is adopted
Because the backup equipment is not much: only consider the function, the efficiency of the program on the secondary

Release:
Basically implement netscreen,cisco ios, hw VRP, h3c f1000 device backup program
Isolate the device information configuration   2. Whether the backup is successfully detected

Question:
1. Unsolved ping can not reach the main problem of slow feedback   Solution: IP one item, does not support the host name, in the ipCheck function to add the check address to solve
2. The logon device deploys expect code that does not handle authentication failures or timeouts


#coding:utf-8
#!/usr/bin/python
'''
program: run.py
'''
import pexpect
import datetime
import time
import os
import re

#tftp The server 
tftpServer='192.168.1.115'
# Backup host list [configuration format as follows] 
#ip   Backup script [ System type ]  Login account    password   super password   Do you need a backup 
backupHosts=[
 {"ip":"192.168.1.27","script":"vrp","login":"test","passwd":"*****","su_passwd":"*****","check":"Y"},
 {"ip":"192.168.1.28","script":"vrp","login":"test","passwd":"*****","su_passwd":"*****","check":"Y"},
 {"ip":"192.10.100.100","script":"vrp","login":"test","passwd":"*****","su_passwd":"*****","check":"Y"},
 {"ip":"192.10.100.101","script":"vrp","login":"test","passwd":"*****","su_passwd":"*****","check":"Y"},
 {"ip":"192.10.98.167","script":"juniper","login":"netscreen","passwd":"*****","su_passwd":"*****","check":"Y"},
 {"ip":"192.10.98.168","script":"juniper","login":"netscreen","passwd":"*****","su_passwd":"*****","check":"Y"},
 {"ip":"192.168.1.124","script":"h3c_firewall","login":"test","passwd":"*****","su_passwd":"*****","check":"Y"},
 {"ip":"192.168.1.125","script":"h3c_firewall","login":"test","passwd":"*****","su_passwd":"*****","check":"Y"},
 {"ip":"192.10.98.233","script":"ios","login":"test","passwd":"*****","su_passwd":"*****","check":"Y"},
 {"ip":"192.10.98sd","script":"ios","login":"test","passwd":"*****","su_passwd":"*****","check":"Y"},
]

#  Check if the host is reachable 
def ipCheck(ip):
 if re.match(r"d{1,3}.d{1,3}.d{1,3}.d{1,3}",ip):
  if os.uname()[0] == "Linux":
   output=os.popen("/bin/ping -c 1 -W 2 %s" % (ip)).read().split("n")
   if "1 packets transmitted, 1 received, 0% packet loss, time 0ms" in output:
    return True
   else:
    return False
 else:
  return False
#  Produce date 
def getToday():
 return datetime.date.today()
''' The core code '''
def telnet_hw3552(ip,login,passwd,su_passwd):
 try:
  foo = pexpect.spawn('/usr/bin/telnet %s' % (ip))
  index = foo.expect(['sername:', 'assword:'])
  if index == 0:
   foo.sendline(login)
   foo.expect("assword:")
   foo.sendline(passwd)
  elif index == 1:
   foo.sendline(passwd)
  foo.expect(">")
  foo.sendline("super")
  foo.expect("assword:")
  foo.sendline(su_passwd)
  foo.expect(">")
  foo.sendline("tftp %s put %s %s " % (tftpServer,"vrpcfg.cfg",ip+"_hw_"+str(getToday())+".cfg"))
  index=foo.expect(["successfully","Error"])
  if index == 1:
   foo.sendline(" ")
   foo.expect(">")
   foo.sendline("tftp %s put %s %s " % (tftpServer,"vrpcfg.zip",ip+"_hw_"+str(getToday())+".zip"))
  foo.sendline("quit")
 except pexpect.EOF:
  foo.close()
 else:
  foo.close  
# cisco ios System switch 
def telnet_ciscoios(ip,login,passwd,su_passwd):
 try:
  foo = pexpect.spawn('/usr/bin/telnet %s' % (ip))
  index = foo.expect(['sername:', 'assword:']) 
  if index == 0:
   foo.sendline(login)
   foo.expect("assword:")
   foo.sendline(passwd)
  elif index == 1:
   foo.sendline(passwd)
  foo.expect(">")
  foo.sendline("en")
  foo.expect("assword:")
  foo.sendline(su_passwd)
  foo.expect("#")
  foo.sendline("copy running-config tftp")
  foo.expect(".*remote.*")
  foo.sendline("%s" % (tftpServer))
  foo.expect(".*filename.*")
  foo.sendline("%s" % (ip+"_ciscoIos_"+str(getToday())+"_runningconfig.cfg"))
  foo.expect("#")
  foo.sendline("exit")
 except pexpect.EOF:
  foo.close()
 else:
  foo.close

#h3c A firewall 
def telnet_h3cfirewallf1000(ip,login,passwd,su_passwd):
 try:
  foo = pexpect.spawn('/usr/bin/telnet %s' % (ip))
  index = foo.expect(['sername:', 'assword:']) 
  if index == 0:
   foo.sendline(login)
   foo.expect("assword:")
   foo.sendline(passwd)

  elif index == 1:
   foo.sendline(passwd)
  foo.expect(">")
  foo.sendline("tftp %s put %s %s " % (tftpServer,"startup.cfg",ip+"_h3cf1000_"+str(getToday())+"_startup.cfg"))
  foo.expect(">")
  foo.sendline("tftp %s put %s %s " % (tftpServer,"system.xml",ip+"_h3cf1000_"+str(getToday())+"_system.xml"))
  foo.expect(">")
  foo.sendline("quit")
 except pexpect.EOF:
  foo.close()
 else:
  foo.close  

#netscreen firewall
def telnet_netscren(ip,login,passwd,su_passwd):
 try:
  foo = pexpect.spawn('/usr/bin/telnet %s' % (ip))
  index = foo.expect(['login:', 'assword:']) 
  if index == 0:
   foo.sendline(login)
   foo.expect("assword:")
   foo.sendline(passwd)
  elif index == 1:
   foo.sendline(passwd)

  foo.expect(">")
  foo.sendline(su_passwd)
  foo.expect(">")
  foo.sendline("save config to tftp %s %s" % (tftpServer,ip+"_netscreen_"+str(getToday())+".cfg"))
  foo.expect("Succeeded")
  foo.expect(">")
  foo.sendline("exit")
  foo.expect(".*save.*")
  foo.sendline("Y")  
 except pexpect.EOF:
  foo.close()
 else:
  foo.close  

# Call the core code function 
def run():
 ''' Check the configuration first to see if the device needs to be backed up,   Confirm whether the device is accessible to the network, ok Do a backup operation '''
 for i in backupHosts:
  if i['check'] == "Y":
   if ipCheck(i['ip']):
    print(" --->>> backup %s  ......" % (i['ip']))
    if i['script'] == "vrp":
     telnet_hw3552(i['ip'],i['login'],i['passwd'],i['su_passwd']) #cfg
    elif i['script'] == "ios":
     telnet_ciscoios(i['ip'],i['login'],i['passwd'],i['su_passwd']) #cisco
    elif i['script'] == "juniper":
     telnet_netscren(i['ip'],i['login'],i['passwd'],i['su_passwd']) #juniper netscreen
    elif i['script'] == "h3c_firewall":
     telnet_h3cfirewallf1000(i['ip'],i['login'],i['passwd'],i['su_passwd']) #  h3c firewall
    else:
     print("%s [%s] nonsupoort this type system host" % (i['ip'],i['script']))
   else:
    print("unknown host %s or hosts ip config error" % (i['ip']))

#+++++++++++++++++++++main+++++++++++++++++++=
if __name__ == "__main__":
# Perform a backup  
 run()
# Verify that the backup was successful 
 print("----------------------- report ------------------")
 backupPath='/win_data/tftp_log'  # The backup path 
 tftpList=[]
 for i in os.popen("ls %s | grep "%s"" % (backupPath,getToday())).readlines():    # Backup to a file in a list 
  tftpList.append(i.split("_")[0])
 for i in backupHosts:    # Check whether the device is backed up or not [tftp Is there any file on it? ]    No: a hint 
  if i['check'] == "Y":
   if i['ip'] not in tftpList:
    print("%s backup error" % (i['ip']))

'''
# test 
testistrator@python:/win_data$ python run.py 
 --->>> backup 192.168.1.27  ......
 --->>> backup 192.168.1.28  ......
 --->>> backup 192.10.100.100  ......
 --->>> backup 192.10.100.101  ......
 --->>> backup 192.10.98.167  ......
 --->>> backup 192.10.98.168  ......
 --->>> backup 192.168.1.124  ......
 --->>> backup 192.168.1.125  ......
 --->>> backup 192.10.98.233  ......
unknown host 192.10.98sd or hosts ip config error
----------------------- report ------------------
192.10.98sd backup error
'''


Related articles: