代码拉取完成,页面将自动刷新
# -*- coding: utf-8 -*-
"""
Created on Sat May 28 15:38:07 2022
@author: saber
"""
import re
import time
import pandas as pd
from ping3 import ping
from netmiko import ConnectHandler
from os import listdir
def device_info(default_path=r"./device_info//"): #提取excle中设备信息
device_file_path = default_path + listdir(default_path)[0]
device_data = pd.read_excel(device_file_path, sheet_name = "Sheet1") # sheet_name不指定时默认返回全表数据
return device_data
def login_device(host="", username="", password="", port="22", device_type="hp_comware"): #登录设备
device = {'device_type': device_type,
'host': host,
'port': port,
'username': username,
'password': password, }
return ConnectHandler(**device)
def property_detection(host):
if ping(host):
print(f"{host}:有效资产")
else:
print(f"{host}:无效资产")
def config_backup(session,host,default_path=r"./backup_config"):#设备配置文件备份
commands = ["dis current-configuration"]
output = session.send_config_set(commands)
pattern = re.compile(r'#.*#\nreturn',re.S)
result = re.findall(pattern=pattern,string=output)[0]
with open (default_path + f"//{host}.startup.conf","w",encoding="utf8") as file:
file.write(result )
print(f"{host}:备份成功")
def shutdow_limit_port(session, host, limit_vlan=""):#关闭被划入限制VLAN的端口
command = f"display interface brief | include ^GE.*DOWN.*A.*{limit_vlan}"
output = session.send_config_set(command)
pattern = re.compile(r"GE[0-9]/[0-9]/[0-9]+",re.S)
result = re.findall(pattern=pattern, string=output)
commands = ["system-view"]
for interface in result:
commands.append(f"interface {interface}\nshutdown")
session.send_config_set(commands)
print(f"{host}:限制VLAN端口已关闭")
def batch_config_read(config_file="./commands/config.txt"):#读取解析配置文件
with open(config_file, "r", encoding="utf8") as file:
info = file.read()
return info.strip().split("\n")
def batch_config_deploy(session, host ,commands):#批量配置
session.send_config_set(commands)
print(f"{host}:配置成功")
def batch_config_save(session,host):#批量保存配置
session.send_config_set("save force")
print(f"{host}:保存成功")
def mac_bind(session,host): #mac地址绑定
for inter_number in range(1,49):
look_int_command = f"dis mac-address interface g1/0/{inter_number}"
output = session.send_config_set(look_int_command)
if "Wrong parameter" in output:
break
pattern = re.compile(r"(\w{4}-\w{4}-\w{4})\s+(\d+)",re.S)
result = re.findall(pattern=pattern, string=output)
if not result or len(result) > 1: #排除打印设备和trunk口
continue
result = result[0]
commands = ["system-view", f"interface GE1/0/{inter_number}", f"mac-address static {result[0]} vlan {result[-1]} ", "mac-address max-mac-count 0 "] #存放单个接口下存放命令的列表
session.send_config_set(commands)
time.sleep(0.5)
print(f"{host}:MAC绑定成功")
def main():
text_content = """
<q>退出主操作面板
<1>资产检测
<2>自动备份所有设备的配置文件
<3>自动保存配置
<4>自动关闭限制端口
<5>批量部署配置文件:只支持commands文件
<6>端口MAC地址绑定
"""
print(text_content)
option = input("请输入操作项:")
df = device_info()
for index, row in df.iterrows():
if option == "1":
property_detection(row["设备管理地址"])
if option == "2":
session = login_device(row["设备管理地址"],row["SSH管理账户"],row["SSH账户密码"])
config_backup(session,row["设备管理地址"])
if option == "3":
session = login_device(row["设备管理地址"],row["SSH管理账户"],row["SSH账户密码"])
batch_config_save(session,host=row["设备管理地址"])
if option == '4':
session = login_device(row["设备管理地址"],row["SSH管理账户"],row["SSH账户密码"])
shutdow_limit_port(session, host=row["设备管理地址"],limit_vlan=1)
if option == '5':
session = login_device(row["设备管理地址"],row["SSH管理账户"],row["SSH账户密码"])
batch_config_deploy(session, host=row["设备管理地址"],commands=batch_config_read())
if option == '5':
session = login_device(row["设备管理地址"],row["SSH管理账户"],row["SSH账户密码"])
mac_bind(session, host=row["设备管理地址"])
if __name__ == "__main__":
try:
main()
except Exception as e:
print(e)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。