一、说明
1、使用python脚本实现交换机管理的自动化
2、批量化管理,将账密单独使用csv存放即可
3、还是使用pyexpect,nornir有点复杂,paramiko在事件触发上不够友好,大批量容易出现太多无效等待
4、pyexect有自己超时处理,不过多线程需要自己处理
5、脚本效果
失效自动登录交换机,将所有UP端口的进出流量一次性统计输出
二、单台交换机自动化管理
# -*- coding: utf-8 -*-
import re
import pexpect
import time
def manage_switch(ip, user, password):
# 使用特殊参数连接SSH
ssh_command = f"ssh -o Ciphers=aes256-cbc -o HostKeyAlgorithms=+ssh-rsa {user}@{ip}"
# 开始SSH会话
child = pexpect.spawn(ssh_command)
# 处理首次连接的密钥确认提示
index = child.expect(['fingerprint', 'Enter password:'],timeout=40)
if index == 0:
child.sendline('yes')
child.expect('Enter password:', timeout=10) # 等待密码提示
child.sendline(password) # 输入密码
elif index == 1:
child.sendline(password) # 输入密码
else:
return
# 输入密码
child.expect(r'<.*?>',timeout=10)
# 设置屏幕长度
child.sendline('screen-length 0 temporary')
child.expect('>',timeout=10)
# 发送显示设备名称的命令
child.sendline('display sysname')
child.expect('\r\n')
child.expect(r'<.*?>',timeout=10)
# 获取输出内容
dev_name = child.before.decode().strip()
# 发送命令以显示接口状态
child.sendline('display interface brief | in up')
child.expect('>', timeout=10) # 等待命令执行完成
output = child.before.decode()
interfaces = re.findall(r'(\d*GE\d/\d+/\d+)(?=\s+up\s+up)', output)
interface_detail = {}
for interface in interfaces:
child.sendline(f'display interface {interface}')
child.expect('>', timeout=10) # 等待命令执行完成
# 获取当前接口的详细信息
details_output = child.before.decode()
pattern = re.compile(r'(Input|Output)\s*:\s*(\d+)\s+bytes')
matches = pattern.findall(details_output)
input_bytes = matches[0][1]
output_bytes = matches[1][1]
interface_detail[interface] = f"{dev_name},{interface},{input_bytes},{output_bytes}"
print(interface_detail[interface])
child.sendline('exit') # 退出SSH
child.close()
manage_switch('10.12.100.17', 'kignredfly', 'krf@#123456')
三、注意事项
1、ssh初始化登录、非初始化登录均要考虑到
index = child.expect(['fingerprint', 'Enter password:'],timeout=40)
if index == 0:
child.sendline('yes')
child.expect('Enter password:', timeout=10) # 等待密码提示
child.sendline(password) # 输入密码
elif index == 1:
child.sendline(password) # 输入密码
else:
return
2、特殊ssh参数添加(如涉及)
ssh_command = f"ssh -o Ciphers=aes256-cbc -o HostKeyAlgorithms=+ssh-rsa {user}@{ip}"
3、注意输出
child.before/child.after输出,一般使用child.before,after一般用户看看脚本expect提示符之后的输出.
本处有两个关键点。 child.expect(‘\r\n’)清理输入命令,避免命令也作为输出结果输出,第二点就是expect r’<.*?>',如果单纯输入 >,就会出现结果中包含>之前的提示信息部分内容
# 发送显示设备名称的命令
child.sendline('display sysname')
child.expect('\r\n')
child.expect(r'<.*?>',timeout=10)
# 获取输出内容
dev_name = child.before.decode().strip()