如何编写自动配置路由器脚本

wen 实用脚本 3

本文目录导读:

如何编写自动配置路由器脚本

  1. SSH 连接脚本(适用于大多数路由器)
  2. 使用 pexpect(适用于类Unix系统)
  3. Bash 脚本(使用 expect)
  4. 配置模板生成器
  5. 安全建议
  6. 注意事项

我将为您介绍如何编写自动配置路由器的脚本,这通常通过 SSH 或 Telnet 连接到路由器命令行界面实现。

SSH 连接脚本(适用于大多数路由器)

Python 示例(使用 paramiko)

#!/usr/bin/env python3
import paramiko
import time
def configure_router(hostname, username, password, commands):
    """
    自动配置路由器
    """
    try:
        # 创建SSH客户端
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接路由器
        client.connect(hostname, username=username, password=password)
        # 打开shell
        shell = client.invoke_shell()
        # 等待连接建立
        time.sleep(1)
        # 发送配置命令
        for command in commands:
            shell.send(command + '\n')
            time.sleep(1)  # 等待命令执行
        # 获取输出
        output = shell.recv(65535).decode('utf-8')
        print(f"执行结果:\n{output}")
        client.close()
        return True
    except Exception as e:
        print(f"错误: {e}")
        return False
# 使用示例
if __name__ == "__main__":
    router_config = [
        "enable",
        "configure terminal",
        "hostname MyRouter",
        "interface GigabitEthernet0/0",
        "ip address 192.168.1.1 255.255.255.0",
        "no shutdown",
        "exit",
        "end",
        "write memory"
    ]
    configure_router("192.168.1.1", "admin", "password", router_config)

使用 pexpect(适用于类Unix系统)

#!/usr/bin/env python3
import pexpect
import sys
def configure_router_pexpect(host, username, password, enable_password):
    """
    使用pexpect配置路由器
    """
    try:
        # SSH连接
        child = pexpect.spawn(f'ssh {username}@{host}')
        # 处理密码提示
        child.expect('password:')
        child.sendline(password)
        # 等待登录成功
        child.expect('#')
        # 进入特权模式
        child.sendline('enable')
        child.expect('Password:')
        child.sendline(enable_password)
        # 进入全局配置模式
        child.sendline('configure terminal')
        child.expect('\(config\)#')
        # 发送配置命令
        commands = [
            'interface GigabitEthernet0/1',
            'description LAN_Interface',
            'ip address 10.0.0.1 255.255.255.0',
            'no shutdown',
            'exit'
        ]
        for cmd in commands:
            child.sendline(cmd)
            child.expect('\(config\)#', timeout=5)
        # 保存配置
        child.sendline('end')
        child.sendline('write memory')
        child.expect(pexpect.EOF, timeout=10)
        print("配置完成")
        child.close()
    except Exception as e:
        print(f"配置失败: {e}")
# 使用示例
configure_router_pexpect("192.168.1.1", "admin", "password", "enable_pwd")

Bash 脚本(使用 expect)

#!/bin/bash
# 自动配置路由器脚本
ROUTER_IP="192.168.1.1"
USERNAME="admin"
PASSWORD="password"
ENABLE_PASSWORD="enable_pwd"
# 使用expect自动化交互
expect -c "
set timeout 10
spawn ssh $USERNAME@$ROUTER_IP
expect \"password:\"
send \"$PASSWORD\r\"
expect \"#\"
send \"enable\r\"
expect \"Password:\"
send \"$ENABLE_PASSWORD\r\"
expect \"#\"
send \"configure terminal\r\"
expect \"(config)#\"
send \"hostname MyRouter\r\"
expect \"(config)#\"
send \"int gig0/0\r\"
expect \"(config-if)#\"
send \"ip address 192.168.1.1 255.255.255.0\r\"
expect \"(config-if)#\"
send \"no shut\r\"
expect \"(config-if)#\"
send \"exit\r\"
expect \"(config)#\"
send \"end\r\"
expect \"#\"
send \"write memory\r\"
expect \"#\"
send \"exit\r\"
expect eof
"

配置模板生成器

#!/usr/bin/env python3
import jinja2
from dataclasses import dataclass
from typing import List
@dataclass
class RouterConfig:
    hostname: str
    interfaces: List[dict]
    static_routes: List[dict]
    acl_rules: List[dict]
class RouterConfigGenerator:
    def __init__(self):
        self.template = """
! Router Configuration Script
hostname {{ config.hostname }}
!
{% for interface in config.interfaces %}
interface {{ interface.name }}
 description {{ interface.description }}
 ip address {{ interface.ip_address }} {{ interface.subnet_mask }}
 no shutdown
!
{% endfor %}
{% for route in config.static_routes %}
ip route {{ route.destination_network }} {{ route.subnet_mask }} {{ route.next_hop }}
!
{% endfor %}
{% for rule in config.acl_rules %}
access-list {{ rule.number }} {{ rule.action }} {{ rule.source_ip }} {{ rule.source_mask }}
{% endfor %}
!
end
write memory
"""
    def generate(self, config: RouterConfig) -> str:
        template = jinja2.Template(self.template)
        return template.render(config=config)
# 使用示例
generator = RouterConfigGenerator()
config = RouterConfig(
    hostname="CoreRouter",
    interfaces=[
        {
            "name": "GigabitEthernet0/0",
            "description": "WAN Connection",
            "ip_address": "10.0.0.1",
            "subnet_mask": "255.255.255.0"
        },
        {
            "name": "GigabitEthernet0/1", 
            "description": "LAN Connection",
            "ip_address": "192.168.1.1",
            "subnet_mask": "255.255.255.0"
        }
    ],
    static_routes=[
        {
            "destination_network": "0.0.0.0",
            "subnet_mask": "0.0.0.0",
            "next_hop": "10.0.0.254"
        }
    ],
    acl_rules=[
        {
            "number": "100",
            "action": "permit",
            "source_ip": "192.168.1.0",
            "source_mask": "0.0.0.255"
        }
    ]
)
config_text = generator.generate(config)
print(config_text)

安全建议

#!/usr/bin/env python3
import os
import subprocess
from cryptography.fernet import Fernet
class SecureRouterConfig:
    def __init__(self, key_file='config_key.key'):
        self.key_file = key_file
        self.load_or_create_key()
    def load_or_create_key(self):
        """加载或创建加密密钥"""
        if not os.path.exists(self.key_file):
            key = Fernet.generate_key()
            with open(self.key_file, 'wb') as f:
                f.write(key)
            os.chmod(self.key_file, 0o600)  # 仅所有者可读写
        with open(self.key_file, 'rb') as f:
            self.key = f.read()
        self.cipher = Fernet(self.key)
    def encrypt_config(self, config_text: str) -> bytes:
        """加密配置文本"""
        return self.cipher.encrypt(config_text.encode())
    def decrypt_config(self, encrypted_config: bytes) -> str:
        """解密配置"""
        return self.cipher.decrypt(encrypted_config).decode()
    def save_config(self, config_text: str, filename: str):
        """安全保存配置"""
        encrypted = self.encrypt_config(config_text)
        with open(filename, 'wb') as f:
            f.write(encrypted)
        os.chmod(filename, 0o600)  # 仅所有者可读写
# 使用安全配置
secure = SecureRouterConfig()
secure.save_config("your_router_config_here", "router_config.encrypted")

注意事项

  1. 测试环境:先在模拟环境测试脚本
  2. 备份配置:修改前先备份当前配置
  3. 错误处理:添加充分的错误处理机制
  4. 日志记录:记录所有操作日志
  5. 访问控制:限制脚本访问权限
  6. 密码安全:避免在脚本中明文存储密码

这些脚本可以根据您的路由器品牌(Cisco、华为、H3C等)和具体需求进行调整,建议先在虚拟机或模拟器中测试。

抱歉,评论功能暂时关闭!