You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Bash Ping脚本以支持CIDR格式输入实现OS检测?

解决Bash脚本支持CIDR格式网段输入的问题

你的脚本核心检测逻辑没问题,只是缺少CIDR格式到目标主机列表的转换能力。下面是修改后的完整脚本,同时我会拆解关键改进点:

修改后的完整脚本

#!/bin/bash

# 处理输入:支持网段前缀(如192.168.1)或CIDR格式(如192.168.1.0/24)
input=$1
if [ -z "$input" ]; then
    echo "Usage: $0 <network_prefix|CIDR>"
    echo "Example: $0 192.168.1 or $0 192.168.1.0/24"
    exit 1
fi

# 生成要扫描的主机列表
if [[ "$input" =~ / ]]; then
    # 处理CIDR格式,优先使用ipcalc工具
    if ! command -v ipcalc &> /dev/null; then
        echo "Error: ipcalc is required to handle CIDR format. Install it via 'sudo apt install ipcalc' (Debian/Ubuntu) or 'sudo dnf install ipcalc' (CentOS/RHEL)."
        exit 1
    fi
    # 获取CIDR范围内的所有可用主机(排除网络和广播地址)
    host_min=$(ipcalc -n -b "$input" | grep HostMin | awk '{print $2}')
    host_max=$(ipcalc -n -b "$input" | grep HostMax | awk '{print $2}')
    # 将IP范围转换为连续主机列表(用fping更高效)
    hosts=$(fping -g "$host_min" "$host_max" 2>/dev/null | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$')
    # 若没有fping,可替换为nmap命令:
    # hosts=$(nmap -sL "$input" | grep "Nmap scan report for" | awk '{print $NF}')
else
    # 处理传统网段前缀格式(如192.168.1)
    hosts=$(seq 1 255 | xargs -I {} echo "$input.{}")
fi

# 遍历主机执行检测
for host in $hosts; do
    # 优化ping命令,屏蔽错误输出
    ttlstr=$(ping -c1 -w1 "$host" 2>/dev/null | grep -o 'ttl=[0-9][0-9]*')
    if [ -z "$ttlstr" ]; then
        printf "%s is Offline\n" "$host"
        continue
    fi
    ttl="${ttlstr#*=}"
    printf "%s is Online, ttl=%d\n" "$host" "$ttl"
    # 修正OS判断逻辑(更符合常见TTL默认值)
    if [ "$ttl" -eq 64 ]; then
        echo "Operating System: Likely Linux/Unix-like"
    elif [ "$ttl" -eq 128 ]; then
        echo "Operating System: Likely Windows"
    elif [ "$ttl" -eq 255 ]; then
        echo "Operating System: Likely Cisco IOS or network device"
    else
        echo "Operating System: Unknown (TTL=$ttl)"
    fi
done

关键改进说明

  • 输入兼容处理:通过检查输入是否包含/来自动区分CIDR和传统网段前缀,适配两种输入格式。
  • CIDR转主机列表:
    • 用ipcalc快速解析CIDR的起始、结束IP,这是Linux发行版普遍支持的轻量工具。
    • 借助fping -g生成IP范围内的所有主机(比手动计算高效),如果没有fping,可以替换成注释里的nmap命令。
  • ping命令优化:添加2>/dev/null屏蔽不可达主机的错误输出,让脚本输出更整洁。
  • OS判断修正:传统IOS设备默认TTL为255,调整后判断逻辑更贴合实际场景。

依赖安装提示

如果你的系统缺少ipcalc或fping,可以用以下命令安装:

  • Debian/Ubuntu:sudo apt install ipcalc fping
  • CentOS/RHEL:sudo dnf install ipcalc fping

内容的提问来源于stack exchange,提问作者Ta219

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:37:47