search
HomeBackend DevelopmentPython Tutorialpython实现数通设备tftp备份配置文件示例

 

环境:【wind2003[open Tftp server] + virtualbox:ubuntn10 server】
tftp : Open TFTP Server  
ubuntn 
python + pyexpect
采用虚拟机原因: pyexpect 不支持windows 

注:原打算采用secrueCrt 脚本编写,因实践中发现没有使用linux下pexpect易用,灵活  ,之前习惯使用expect,因tcl【语法】没有python易用、易维护

编写些程序原因:
最近出了比较严重故障:因netscreen设备bug,一个节点主备设备同时出故障,更换设备后,发现备份配置文件出现乱码【中文】,不能直接使用。
考虑设备在内网,目前有近300台数通设备,因此采用原始tftp备份方式
因备份设备不多:暂只考虑功能,程序效率放在次要

发布:
基本实现netscreen,cisco ios, hw vrp,h3c f1000设备 备份程序
分离出设备信息配置  2.增加备份是否成功检测

问题:
1 未解决ping 不可达主要,反馈慢问题  解决办法:ip 一项,不支持主机名,在 ipCheck函数中添加检查地址进行解决
2.登录设备部署expect代码,没有处理认证失败情况,或者超时等基本检查问题

复制代码 代码如下:

#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'

#备份主机列表【配置格式如下】
#ip  备份脚本[系统类型] 登录帐号  密码  super密码 是否需要备份
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"},
]


# 检查主机是否可达
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

# 产生日期
def getToday():
 return datetime.date.today()

'''核心代码'''

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():
 '''先查看配置,确认设备是否需要备份, 再确认设备是否网络可达,ok才进行备份操作'''
 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("----------------------- report ------------------")
 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:    #检查需要备份设备,是否备份到[tftp上有没有文件]   没:则提示
  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
----------------------- report ------------------
192.10.98sd backup error
'''

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.