first commit
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
import logging
|
||||
import os
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
def log(log_file="zabbix.log", max_bytes=10 * 1024 * 1024, backup_count=5):
|
||||
"""
|
||||
配置日志记录器,输出到/home/zabbix目录且不显示在控制台
|
||||
|
||||
参数:
|
||||
log_file: 日志文件名 (默认: zabbix.log)
|
||||
max_bytes: 单个日志文件最大字节 (默认: 10MB)
|
||||
backup_count: 保留的备份文件数 (默认: 5)
|
||||
"""
|
||||
# 创建日志目录
|
||||
log_dir = "/home/zabbix"
|
||||
os.makedirs(log_dir, exist_ok=True) # 自动创建目录[1,4](@ref)
|
||||
|
||||
# 完整的日志文件路径
|
||||
log_path = os.path.join(log_dir, log_file)
|
||||
|
||||
# 创建记录器
|
||||
logger = logging.getLogger("ZabbixLogger")
|
||||
logger.setLevel(logging.DEBUG) # 设置最低日志级别
|
||||
|
||||
# 配置日志格式
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s - %(filename)s:%(lineno)d - %(levelname)s - %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
|
||||
# 创建文件处理器(带日志轮转功能)[1,3](@ref)
|
||||
file_handler = RotatingFileHandler(
|
||||
log_path,
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding='utf-8'
|
||||
)
|
||||
file_handler.setFormatter(formatter)
|
||||
file_handler.setLevel(logging.INFO) # 文件日志级别
|
||||
|
||||
# 移除所有现有处理器(避免重复)
|
||||
if logger.hasHandlers():
|
||||
logger.handlers.clear()
|
||||
|
||||
# 添加文件处理器(不添加StreamHandler避免控制台输出)[6,8](@ref)
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
# 禁用向父logger传播(避免root logger输出到控制台)[9](@ref)
|
||||
logger.propagate = False
|
||||
|
||||
return logger
|
||||
|
||||
# 使用示例
|
||||
if __name__ == "__main__":
|
||||
# 初始化日志记录器
|
||||
zabbix_logger = setup_zabbix_logger()
|
||||
|
||||
# 记录不同级别日志
|
||||
zabbix_logger.debug("调试信息(不会出现在文件)")
|
||||
zabbix_logger.info("服务启动")
|
||||
zabbix_logger.warning("磁盘空间不足")
|
||||
zabbix_logger.error("数据库连接失败")
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env /opt/miniconda3/envs/py37/bin/python
|
||||
import sys
|
||||
import json
|
||||
from pysnmp.hlapi import *
|
||||
from mylog import log as mylog
|
||||
|
||||
log = mylog()
|
||||
|
||||
|
||||
def snmp_walk(host, oid, format="str", strip_prefix=True, community="zabbix"):
|
||||
res = {}
|
||||
# 使用正确的 nextCmd 函数
|
||||
for errorIndication, errorStatus, errorIndex, varBinds in nextCmd(
|
||||
SnmpEngine(),
|
||||
CommunityData(community),
|
||||
UdpTransportTarget((host, 161), timeout=4.0, retries=3),
|
||||
ContextData(),
|
||||
ObjectType(ObjectIdentity(oid)),
|
||||
lookupMib=False,
|
||||
lexicographicMode=False,
|
||||
):
|
||||
if errorIndication:
|
||||
raise ConnectionError(
|
||||
f'SNMP error: "{str(errorIndication)}". Status={str(errorStatus)}'
|
||||
)
|
||||
elif errorStatus:
|
||||
raise ConnectionError(
|
||||
f'SNMP error: "{str(errorStatus)}" at index {str(errorIndex)}'
|
||||
)
|
||||
else:
|
||||
for varBind in varBinds:
|
||||
oid_str = str(varBind[0])
|
||||
value = varBind[1]
|
||||
|
||||
# 如果指定了去除前缀
|
||||
if strip_prefix:
|
||||
oid_str = oid_str.replace(oid, "", 1).lstrip(".")
|
||||
|
||||
# 根据格式处理值
|
||||
if format == "hex":
|
||||
res[oid_str] = value.asOctets().hex()
|
||||
elif format == "str":
|
||||
res[oid_str] = str(value)
|
||||
else:
|
||||
res[oid_str] = value
|
||||
return res
|
||||
|
||||
|
||||
def machex(mac_part):
|
||||
"""将OID格式的MAC转换为标准格式"""
|
||||
parts = [int(x) for x in mac_part.split(".")]
|
||||
return ":".join(f"{x:02x}" for x in parts[-6:])
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 4:
|
||||
print("Usage: ./switch_monitor.py <mode> <switch_ip> <community> [port]")
|
||||
sys.exit(1)
|
||||
|
||||
mode = sys.argv[1]
|
||||
switch_ip = sys.argv[2]
|
||||
community = sys.argv[3]
|
||||
port_filter = sys.argv[4] if len(sys.argv) >= 5 else None
|
||||
log.info(port_filter, mode, switch_ip, community)
|
||||
# 1. 获取端口映射表
|
||||
port_mapping = {}
|
||||
dot1dBasePortIfIndex = snmp_walk(
|
||||
switch_ip, "1.3.6.1.2.1.17.1.4.1.2", "int", True, community
|
||||
)
|
||||
ifDescr = snmp_walk(switch_ip, "1.3.6.1.2.1.2.2.1.2", "str", True, community)
|
||||
for bridge_index, if_index in dot1dBasePortIfIndex.items():
|
||||
if str(if_index) in ifDescr:
|
||||
port_mapping[str(bridge_index)] = ifDescr[str(if_index)]
|
||||
|
||||
# 2. 获取MAC表
|
||||
mac_table = snmp_walk(switch_ip, "1.3.6.1.2.1.17.4.3.1.2", "int", True, community)
|
||||
# 3. 统计端口MAC数量
|
||||
port_counts = {}
|
||||
mac_details = {}
|
||||
for mac_oid, bridge_index in mac_table.items():
|
||||
standard_mac = machex(mac_oid)
|
||||
if str(bridge_index) in port_mapping:
|
||||
port_name = port_mapping[str(bridge_index)]
|
||||
port_counts[port_name] = port_counts.get(port_name, 0) + 1
|
||||
mac_details.setdefault(port_name, []).append(standard_mac)
|
||||
# 4. 根据模式输出
|
||||
if mode == "discovery":
|
||||
# 输出端口自动发现数据
|
||||
discovery = []
|
||||
for port in port_counts.keys():
|
||||
discovery.append(
|
||||
{
|
||||
"{#SWITCH_IP}": switch_ip,
|
||||
"{#PORT_NAME}": port,
|
||||
"{#COMMUNITY}": community,
|
||||
}
|
||||
)
|
||||
print(json.dumps({"data": discovery}))
|
||||
|
||||
elif mode == "count":
|
||||
# 输出特定端口的MAC数量
|
||||
if not port_filter:
|
||||
print("0")
|
||||
return
|
||||
|
||||
print(str(port_counts.get(port_filter, 0)))
|
||||
|
||||
elif mode == "list":
|
||||
# 输出特定端口的MAC列表
|
||||
if not port_filter:
|
||||
print("[]")
|
||||
return
|
||||
|
||||
if port_filter in mac_details:
|
||||
print(json.dumps(mac_details[port_filter]))
|
||||
else:
|
||||
print("[]")
|
||||
|
||||
elif mode == "details":
|
||||
# 输出详细MAC信息(用于调试)
|
||||
details = {}
|
||||
for port, macs in mac_details.items():
|
||||
details[port] = {"count": len(macs), "macs": macs}
|
||||
print(json.dumps(details))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user