2024/12/02
作者:博睿小谷 | 【Python培训班】
Python在网络工程运维中扮演着至关重要的角色。它不仅能够提高运维效率,还能简化繁琐的操作流程,是网络工程师必备的技能之一。
1. 使用Paramiko批量配置网络设备:
import paramiko# 定义网络设备信息{'host': '192.168.1.1', 'username': 'admin', 'password': 'password1'},devices = [{'host': '192.168.1.2', 'username': 'admin', 'password': 'password2'}] # 配置命令config_commands = ['interface GigabitEthernet0/0', 'ip address 10.0.0.1 255.255.255.0']# 连接并配置设备 def configure_device(device): try: # 创建SSH对象ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh = paramiko.SSHClient()ssh.connect(device['host'], username=device['username'], password=device['password'], timeout=8)# 执行配置命令 for command in config_commands: stdin, stdout, stderr = ssh.exec_command(command)print(f"Error connecting to {device['host']}: {str(e)}")print(stdout.read().decode('utf-8')) # 关闭连接 ssh.close() except Exception as e: # 遍历设备并配置 for device in devices:configure_device(device)
import osimport shutilfrom datetime import datetimedef backup_files(source_dir, backup_dir):# 创建备份目录timestamp = datetime.now().strftime("%Y%m%d%H%M%S")backup_path = f"{backup_dir}/{timestamp}"for item in os.listdir(source_dir):os.makedirs(backup_path, exist_ok=True) # 复制文件if os.path.isdir(s):s = os.path.join(source_dir, item) d = os.path.join(backup_path, item)# 定义源目录和备份目录shutil.copytree(s, d, dirs_exist_ok=True) else: shutil.copy2(s, d) source_directory = '/path/to/source'backup_files(source_directory, backup_directory)backup_directory = '/path/to/backup'# 执行备份
from fabric import Connection# 定义远程服务器信息host = "192.168.1.10" # 远程服务器IPuser = "your_username" # SSH用户名password = "your_password" # SSH密码(可选,建议使用SSH密钥)# 创建连接# 执行远程命令conn = Connection(host=host, user=user, connect_kwargs={"password": password})print(f"Command: {command}")def execute_remote_command(command): result = conn.run(command, hide=True)execute_remote_command("sudo apt update")print(f"Output: {result.stdout.strip()}") print(f"Error: {result.stderr.strip()}") # 示例:更新系统和安装软件包conn.close()execute_remote_command("sudo apt install -y nginx")# 关闭连接
更多相关内容