基于Paramiko实现对设备文件的定时备份、老文件的删除(数据库存设备名、设备管理IP)

from paramiko import SSHClient, AutoAddPolicy, ssh_exception
from time import sleep, localtime, strftime, time
import pymysql
from datetime import datetime, timedelta
import re
from getpass import getpass
import socket

class ZSQ():
    def __init__(self, ip, usr, pwd):
        self.hostname = ip
        self.username = usr
        self.password = pwd
        self.client = self._get_connect()
        self.cli = self.client.invoke_shell()
        self.cli.send("screen-length 0 temporary\n")
        sleep(3)
        self.cli.recv(65535)

    def _get_connect(self):
        ssh_con = SSHClient()
        ssh_con.set_missing_host_key_policy(AutoAddPolicy)
        ssh_con.connect(hostname=self.hostname, username=self.username, password=self.password)
        return ssh_con

    def save_running(self):
        ssh_con = self._get_connect()
        cmd = 'save ' + strftime('%Y_%m_%d', localtime(time())) + '_' + name + '_vrpcfg.zip'
        self.cli.send("{}\n".format(cmd))
        self.cli.send('y\n')
        self.cli.send('y\n')
        sleep(3)
        dis_this = self.cli.recv(65535).decode()
        print(dis_this)
        ssh_con.close()

    def download_file(self):
        ssh_con = self._get_connect()
        sftp_con = ssh_con.open_sftp()
        l_path = strftime('%Y_%m_%d', localtime(time())) + '_' + name + '_vrpcfg.zip'
        r_path = '/' + strftime('%Y_%m_%d', localtime(time())) + '_' + name + '_vrpcfg.zip'
        sftp_con.get(localpath=l_path, remotepath=r_path)
        sleep(3)
        ssh_con.close()

    def deletefile(self):
        ssh_con = self._get_connect()
        sftp_con = ssh_con.open_sftp()
        seven_days_ago = datetime.now() - timedelta(days=3)
        files = sftp_con.listdir('flash:/')
        for file in files:
            match = re.search(r'\d{4}_\d{2}_\d{2}', file)
            if match:
                timestamp_str = match.group()
                timestamp = datetime.strptime(timestamp_str, '%Y_%m_%d')
                if timestamp < seven_days_ago:
                    if file[-10:] == "vrpcfg.zip":
                        sftp_con.remove('flash:/' + file)
                        print(f'Configuration file {file} deleted successfully.')
                        sleep(3)
        ssh_con.close()

    def close(self):
        self.client.close()

def backup(ip, usr, pwd):
    ba = ZSQ(ip, usr, pwd)
    ba.deletefile()
    ba.save_running()
    ba.download_file()

if __name__ == "__main__":
    try:
        ssh_usr = input('Username:')
        ssh_pwd = getpass('Password:')
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password='12345678',
            db='ys',
            charset='utf8',
        )
        cur = conn.cursor()
        sqli = "select * from test;"
        result = cur.execute(sqli)
        person_all = cur.fetchall()
        switch_with_authentication_issue = []
        switch_not_reachable = []
        last_time = time()
        while True:
            for p in person_all:
                try:
                    name = p[0]
                    ip = p[1]
                    now_time = time()
                    if now_time - last_time >= 86400:
                        backup(ip, ssh_usr, ssh_pwd)
                        last_time = time()
                    elif now_time - last_time < 300:
                        backup(ip, ssh_usr, ssh_pwd)
                    print('*'*50)
                    sleep(300)
                except ssh_exception.AuthenticationException:
                    print('User authentication failed for ' + ip + '.')
                    switch_with_authentication_issue.append(ip)
                except socket.error:
                    print(ip + 'is not reachable.')
                    switch_not_reachable.append(ip)
                print('\nUser authentication failed for below switches:')
                for i in switch_with_authentication_issue:
                    print(i)
                print('\nBelow switches are not reachable:')
                for i in switch_not_reachable:
                    print(i)
    except KeyboardInterrupt:
        print("monitoring has stopped!")





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值