在开始编写Python脚本之前,我们需要准备以下环境:
1 |
pip install paramiko |
备份华为交换机配置文件的基本步骤如下:
接下来,我们将详细编写一个Python脚本来实现上述步骤。
首先,我们需要导入必要的Python库:
1 2 3 |
import paramiko import os from datetime import datetime |
我们需要配置SSH连接的信息,包括交换机的IP地址、用户名和密码等:
1 2 3 4 |
hostname = '交换机的IP地址' username = '用户名' password = '密码' port = 22 # 默认SSH端口 |
使用Paramiko库创建SSH连接:
1 2 3 4 5 |
def create_ssh_client(hostname, port, username, password): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname, port, username, password) return client |
连接成功后,我们需要执行交换机的命令来获取配置文件。华为交换机常用的命令是display current-configuration。
1 2 3 |
def get_switch_configuration(client): stdin, stdout, stderr = client.exec_command('display current-configuration') return stdout.read().decode('utf-8') |
我们需要将获取到的配置文件保存到本地。为了便于管理,通常会按照日期命名备份文件。
1 2 3 4 5 6 7 |
def save_configuration(config, backup_dir): if not os.path.exists(backup_dir): os.makedirs(backup_dir) filename = os.path.join(backup_dir, f'config_backup_{datetime.now().strftime("%Y%m%d%H%M%S")}.txt') with open(filename, 'w') as file: file.write(config) print(f'Configuration saved to {filename}') |
将上述步骤整合成一个完整的Python脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import paramiko import os from datetime import datetime
# 配置信息 hostname = '交换机的IP地址' username = '用户名' password = '密码' port = 22 # 默认SSH端口 backup_dir = '备份文件存储目录'
# 创建SSH连接 def create_ssh_client(hostname, port, username, password): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname, port, username, password) return client
# 获取交换机配置 def get_switch_configuration(client): stdin, stdout, stderr = client.exec_command('display current-configuration') return stdout.read().decode('utf-8')
# 保存配置文件 def save_configuration(config, backup_dir): if not os.path.exists(backup_dir): os.makedirs(backup_dir) filename = os.path.join(backup_dir, f'config_backup_{datetime.now().strftime("%Y%m%d%H%M%S")}.txt') with open(filename, 'w') as file: file.write(config) print(f'Configuration saved to {filename}')
# 主函数 def main(): try: client = create_ssh_client(hostname, port, username, password) config = get_switch_configuration(client) save_configuration(config, backup_dir) except Exception as e: print(f'An error occurred: {e}') finally: client.close()
if __name__ == "__main__": main() |
1 |
python backup_huawei_switch.py |
1 2 3 4 5 6 7 8 9 10 11 12 |
import logging
logging.basicConfig(filename='backup.log', level=logging.INFO, format='%(asctime)s - %(message)s')
def save_configuration(config, backup_dir): if not os.path.exists(backup_dir): os.makedirs(backup_dir) filename = os.path.join(backup_dir, f'config_backup_{datetime.now().strftime("%Y%m%d%H%M%S")}.txt') with open(filename, 'w') as file: file.write(config) logging.info(f'Configuration saved to {filename}') print(f'Configuration saved to {filename}') |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def main(): try: client = create_ssh_client(hostname, port, username, password) config = get_switch_configuration(client) save_configuration(config, backup_dir) except paramiko.AuthenticationException: print('Authentication failed, please verify your credentials') except paramiko.SSHException as sshException: print(f'Unable to establish SSH connection: {sshException}') except Exception as e: print(f'An error occurred: {e}') finally: client.close() |
1 |
crontab -e |
添加如下任务,每天凌晨2点执行备份:
1 |
0 2 * * * /usr/bin/python3 /path/to/backup_huawei_switch.py |
在Windows上,可以使用任务计划程序(Task Scheduler)。