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!")
基于Paramiko实现对设备文件的定时备份、老文件的删除(数据库存设备名、设备管理IP)
最新推荐文章于 2024-05-16 11:09:42 发布