环境:【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
'''

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

Python和C 在内存管理和控制方面的差异显著。1.Python使用自动内存管理,基于引用计数和垃圾回收,简化了程序员的工作。2.C 则要求手动管理内存,提供更多控制权但增加了复杂性和出错风险。选择哪种语言应基于项目需求和团队技术栈。

Python在科學計算中的應用包括數據分析、機器學習、數值模擬和可視化。 1.Numpy提供高效的多維數組和數學函數。 2.SciPy擴展Numpy功能,提供優化和線性代數工具。 3.Pandas用於數據處理和分析。 4.Matplotlib用於生成各種圖表和可視化結果。

選擇Python還是C 取決於項目需求:1)Python適合快速開發、數據科學和腳本編寫,因其簡潔語法和豐富庫;2)C 適用於需要高性能和底層控制的場景,如係統編程和遊戲開發,因其編譯型和手動內存管理。

Python在數據科學和機器學習中的應用廣泛,主要依賴於其簡潔性和強大的庫生態系統。 1)Pandas用於數據處理和分析,2)Numpy提供高效的數值計算,3)Scikit-learn用於機器學習模型構建和優化,這些庫讓Python成為數據科學和機器學習的理想工具。

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。

Python在Web開發中的關鍵應用包括使用Django和Flask框架、API開發、數據分析與可視化、機器學習與AI、以及性能優化。 1.Django和Flask框架:Django適合快速開發複雜應用,Flask適用於小型或高度自定義項目。 2.API開發:使用Flask或DjangoRESTFramework構建RESTfulAPI。 3.數據分析與可視化:利用Python處理數據並通過Web界面展示。 4.機器學習與AI:Python用於構建智能Web應用。 5.性能優化:通過異步編程、緩存和代碼優

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

Dreamweaver Mac版
視覺化網頁開發工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。