加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main control.py 4.76 KB
一键复制 编辑 原始数据 按行查看 历史
unknown 提交于 2022-06-01 22:11 . new shutdown function
# -*- 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)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化