Example of a configuration file for tftp backup of a digital device using python

Source: Internet
Author: User
Tags time 0
This article mainly introduces the example of a tftp backup configuration file for a digital device using python. For more information, see the following environment: [wind2003 [open Tftp server] + virtualbox: javastn10 server]
Tftp: Open TFTP Server
Ubuntn
Python + pyequalct
Reason for using virtual machine: pybench Ct does not support windows

Note: I originally intended to use secrueCrt scripts. because in practice, I found that pexpect is not easy to use and flexible in linux, and I used to use it. because tcl [Syntax] is not easy to use and easy to maintain in python

Write some program reasons:
Recently, a serious fault occurred: due to a netscreen device bug, the master and backup devices of a node failed at the same time. after the device was changed, it was found that the backup configuration file was garbled [Chinese] and could not be used directly.
Considering that the device is on the intranet, there are currently nearly 300 digital-connect devices, so the original tftp backup method is used.
Because there are not many backup devices: Currently, only functions are considered, and program efficiency is secondary.

Release:
Basic implementation of netscreen, cisco ios, hw vrp, h3c f1000 device backup program
Separate device information configuration 2. check whether the backup is successful

Problem:
1. unsolved ping failures. slow feedback. Solution: ip address. host name is not supported. add the check address in the ipCheck function to solve the problem.
2. log on to the device and deploy the verification Ct code. the verification fails, or basic check problems such as timeout are not handled.

The code is as follows:


# Coding: UTF-8
#! /Usr/bin/python
'''
Program: run. py
'''
Import pexpect
Import datetime
Import time
Import OS
Import re


# Tftp server
TftpServer = '192. 168.1.115'

# Backup host list [the configuration format is as follows]
# Backup ip backup script [system type] logon account password super Password required or not
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 whether 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 0 ms" in output:
Return True
Else:
Return False
Else:
Return False

# Date of generation
Def getToday ():
Return datetime. date. today ()

'''Core code '''

Def telnet_hw3552 (ip, login, passwd, su_passwd ):
Try:
Foo = pexpect. spawn ('/usr/bin/telnet % s' % (ip ))
Index = foo. CT (['sername: ', 'assword:'])
If index = 0:
Foo. sendline (login)
Foo. CT ("assword :")
Foo. sendline (passwd)
Elif index = 1:
Foo. sendline (passwd)
Foo. CT ("> ")
Foo. sendline ("super ")
Foo. CT ("assword :")
Foo. sendline (su_passwd)
Foo. CT ("> ")
Foo. sendline ("tftp % s put % s" % (tftpServer, "vrpcfg. cfg ", ip +" _ hw _ "+ str (getToday () + ". cfg "))
Index = foo. exact CT (["successfully", "Error"])
If index = 1:
Foo. sendline ("")
Foo. CT ("> ")
Foo. sendline ("tftp % s put % s" % (tftpServer, "vrpcfg.zip", ip + "_ hw _" + str (getToday () + ". zip "))
Foo. sendline ("quit ")
Failed T 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. CT (['sername: ', 'assword:'])
If index = 0:
Foo. sendline (login)
Foo. CT ("assword :")
Foo. sendline (passwd)
Elif index = 1:
Foo. sendline (passwd)
Foo. CT ("> ")
Foo. sendline ("en ")
Foo. CT ("assword :")
Foo. sendline (su_passwd)
Foo. CT ("#")
Foo. sendline ("copy running-config tftp ")
Foo. CT (". * remote .*")
Foo. sendline ("% s" % (tftpServer ))
Foo. CT (". * filename .*")
Foo. sendline ("% s" % (ip + "_ ciscoIos _" + str (getToday () + "_ runningconfig. cfg "))
Foo. CT ("#")
Foo. sendline ("exit ")
Failed T pexpect. EOF:
Foo. close ()
Else:
Foo. close

# H3c firewall
Def telnet_h3cfirewallf1000 (ip, login, passwd, su_passwd ):
Try:
Foo = pexpect. spawn ('/usr/bin/telnet % s' % (ip ))
Index = foo. CT (['sername: ', 'assword:'])
If index = 0:
Foo. sendline (login)
Foo. CT ("assword :")
Foo. sendline (passwd)

Elif index = 1:
Foo. sendline (passwd)
Foo. CT ("> ")
Foo. sendline ("tftp % s put % s" % (tftpServer, "startup. cfg ", ip +" _ h3cf1000 _ "+ str (getToday () +" _ startup. cfg "))
Foo. CT ("> ")
Foo. sendline ("tftp % s put % s" % (tftpServer, "system. xml ", ip +" _ h3cf1000 _ "+ str (getToday () +" _ system. xml "))
Foo. CT ("> ")
Foo. sendline ("quit ")
Failed T 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. CT (['login: ', 'assword:'])
If index = 0:
Foo. sendline (login)
Foo. CT ("assword :")
Foo. sendline (passwd)
Elif index = 1:
Foo. sendline (passwd)

Foo. CT ("> ")
Foo. sendline (su_passwd)
Foo. CT ("> ")
Foo. sendline ("save config to tftp % s" % (tftpServer, ip + "_ netscreen _" + str (getToday () + ". cfg "))
Foo. CT ("Succeeded ")
Foo. CT ("> ")
Foo. sendline ("exit ")
Foo. CT (". * save .*")
Foo. sendline ("Y ")
Failed T pexpect. EOF:
Foo. close ()
Else:
Foo. close


# Calling core code functions
Def run ():
'''First check the configuration, confirm whether the device needs to be backed up, and then confirm whether the network of the device is reachable before performing the 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 __":
# Backup
Run ()
# Check whether the backup is successful
Print ("----------------------- report ------------------")
BackupPath = '/win_data/tftp_log' # backup path
TftpList = []
For I in OS. popen ("ls % s | grep \" % s \ "" % (backupPath, getToday ())). readlines (): # store the backup files in the list.
TftpList. append (I. split ("_") [0])
For I in backupHosts: # check whether the device needs to be backed up to [whether there are any files on tftp] No: the system prompts
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
'''

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.