前提工作

python中默认没有安装SSH模块,SSH功能依靠paramiko 模块实现,需要自己独立安装,具体安装步骤自行百度。

主要脚本,和之前一样,通过TFTP备份配置

#!/usr/bin/python

#-*- coding: utf-8 -*-

import re

import paramiko          #引入ssh模块,该模块需要单独安装。

import time

LogTime = time.strftime('%Y-%m-%d_%H-%M-%S')

tftp = raw_input('Please Enter TFTP Sever IP:')           

temp = open('config.txt','w')

hostname = '192.168.202.254'

port = 22

username = 'admin'

password = 'passw0rd'

client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect(hostname, port, username, password, timeout=5)

remote_conn = client.invoke_shell()

remote_conn.send('display version\n')

time.sleep(1)

remote_conn.send('\n')

out = remote_conn.recv(temp)

DeviceName = (re.findall(str(".*<(.*)>.*"),out))[0]

save = "save %s-%s.cfg " %(DeviceName,LogTime)

remote_conn.send(save+'\n')

time.sleep(1)

remote_conn.send('y'+'\n')

time.sleep(2)

tftp_cli = "tftp %s put %s-%s.cfg" %(tftp,DeviceName,LogTime)

remote_conn.send(tftp_cli+'\n')

time.sleep(2)

print  hostname,'Backup Success !!'