Python implements a digital device tftp backup configuration file Sample _python

Source: Internet
Author: User
Tags datetime

Environment: "Wind2003[open Tftp Server] + VIRTUALBOX:UBUNTN10 Server"
Tftp:open TFTP Server
Ubuntn
Python + pyexpect
Virtual machine Reason: Pyexpect does not support windows

Note: Originally intended to use SECRUECRT script, because the practice found no use under Linux pexpect easy-to-use, flexible, used to use expect, because TCL "grammar" without Python easy-to-use, easy to maintain

Write some procedural reasons:
Recently a more serious failure: Due to NetScreen device bugs, a node main standby equipment at the same time, the replacement of equipment, found that the backup configuration file garbled "Chinese", can not be used directly.
Consider equipment in the intranet, there are currently nearly 300 digital access equipment, so the original TFTP backup method
Due to a few backup devices: temporarily consider the function, program efficiency in the secondary

Release:
Basic implementation of Netscreen,cisco iOS, HW vrp,h3c f1000 Device Backup Program
Isolate device information Configuration 2. Increase the success of a backup test

Problem:
1 unresolved ping unreachable Main, feedback slow problem Resolution: IP One, do not support host name, add check address in Ipcheck function to solve
2. Login device deployment Expect code, no processing authentication failure, or timeout and other basic check problems

Copy Code code as follows:

#coding: Utf-8
#!/usr/bin/python
'''
program:run.py
'''
Import Pexpect
Import datetime
Import time
Import OS
Import re


#tftp服务器
Tftpserver= ' 192.168.1.115 '

#备份主机列表 "configuration format is as follows"
#ip backup script [System type] login account password Super password need to back up
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 up to
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

# Date of Creation
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.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

#思科ios系统交换机
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防火墙
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


#调用核心代码函数
def run ():
"" To check the configuration, verify that the device needs to be backed up, and then confirm that the device is up to the network, OK for 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__":
#执行备份
Run ()
#检查备份是否成功
Print ("-----------------------------------------)"
Backuppath= '/win_data/tftp_log ' #备份路径
Tftplist=[]
For I in Os.popen ("ls%s | grep \ "%s\" "% (Backuppath,gettoday ())). ReadLines (): #将备份到文件存放于列表中
Tftplist.append (I.split ("_") [0])
For i in Backuphosts: #检查需要备份设备, whether to back up to [tftp no files] No: prompt
If i[' check '] = = "Y":
If i[' IP '] not in tftplist:
Print ("%s backup error"% (i[' IP '))

'''
#测试
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
-----------------------------------------
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.