Linux双网卡绑定状态验证脚本
前景
公司内交换机切换,需提前验证服务器系统主备网卡绑定状态
脚本
需提前配置好YUM源或已安装lldpd服务
#!/bin/bash
# 安装必要工具
install_lldpad() {
if ! command -v lldptool >/dev/null 2>&1; then
echo "安装lldpad服务..."
yum install -y lldpad >/dev/null 2>&1
echo "启动lldpad服务..."
systemctl start lldpad >/dev/null 2>&1
fi
}
# 可靠的低级LLDP解析
parse_lldp_output() {
local lldp_output="$1"
local chassis_id=""
local port_id=""
local sys_name=""
# 使用IFS读行进行精确解析
while IFS= read -r line; do
# 提取Management Address MAC
if [[ "$line" =~ "Management Address TLV" ]]; then
read -r mac_line
if [[ "$mac_line" =~ MAC:[[:space:]]*([0-9a-f:]{17}) ]]; then
chassis_id="${BASH_REMATCH[1]}"
fi
fi
# 提取Port ID
if [[ "$line" =~ "Port ID TLV" ]]; then
read -r port_line
# 精确匹配Ifname格式
if [[ "$port_line" =~ Ifname:[[:space:]]*(.+) ]]; then
port_id="${BASH_REMATCH[1]}"
fi
fi
# 提取System Name
if [[ "$line" =~ "System Name TLV" ]]; then
read -r sys_line
sys_name="${sys_line}"
fi
done <<< "$lldp_output"
echo "$chassis_id $port_id $sys_name"
}
# 专业的bond处理函数
process_bond() {
local bond="$1"
local bond_file="/proc/net/bonding/$bond"
# 确保bond文件存在
[[ -f "$bond_file" ]] || return
# 精确解析bond信息
local mode=$(grep "Bonding Mode" "$bond_file" | awk -F': ' '{print $2}')
local slaves=$(awk '/Slave Interface:/{slave=$3} /MII Status: up$/{if(slave) print slave}' "$bond_file")
local up_count=$(echo "$slaves" | wc -l)
# 输出关键信息
echo "================================================================="
printf "%-15s: %s\n" "Bond接口" "$bond"
printf "%-15s: %s\n" "绑定模式" "$mode"
printf "%-15s: %d\n" "UP网卡数量" "$up_count"
printf "%-15s: %s\n" "网卡名称" "$(echo $slaves | tr '\n' ' ')"
echo "================================================================="
# 处理所有从网卡
for slave in $slaves; do
[[ -d "/sys/class/net/$slave" ]] || continue
# 配置并获取LLDP信息
lldptool set-lldp -i "$slave" adminStatus=rxtx >/dev/null 2>&1
raw_output=$(lldptool -t -n -i "$slave" 2>&1)
# 精确解析
read -r chassis_id port_id sys_name <<< "$(parse_lldp_output "$raw_output")"
# 最终检查修正(基于您的实际输出)
if [[ "$port_id" == "Ifname:" ]]; then
# 从原始输出重新提取
port_id=$(grep -A1 "Port ID TLV" <<< "$raw_output" | tail -1 | awk '{print $1}')
fi
# 格式化输出
printf "%-15s: %s\n" "网卡名称" "$slave"
printf "%-15s: %s\n" "真实MAC地址" "${chassis_id:-未获取到}"
printf "%-15s: %s\n" "交换机端口" "${port_id:-未获取到}"
printf "%-15s: %s\n" "交换机名称" "${sys_name:-未获取到}"
echo "----------------------------------------"
done
echo # 分隔空行
}
### 主程序 ###
# 安装必要服务
install_lldpad
# 检测所有bond接口
bonds=$(find /proc/net/bonding/ -maxdepth 1 -type f -printf "%f\n" 2>/dev/null)
[[ -z "$bonds" ]] && exit
# 处理每个bond接口
for bond in $bonds; do
process_bond "$bond"
done
阅读剩余
本站代码模板仅供学习交流使用请勿商业运营,严禁从事违法,侵权等任何非法活动,否则后果自负!
THE END