#!/bin/bash
# version:2024.2.22
# 2023.12.18 更新支持云主机硬件采集
# 2024.2.22 解决在debian系统运行时出现的语法错误
# 2024.6.20 兼容x86系统，主机名使用hostname或sn.
# 2026.3.5 添加资产状态字段支持(asset_status)
# Set environment

# ============ 资产状态参数解析 ============
# 用法: ./get_hwinfo.sh [状态码]
# 状态码: Rep(故障替换) Pur(采购) New(新机房) Act(线上,默认) Rec(撤点)
# 大小写兼容 rep/Rep/REP 都支持

# ⚙️ 配置开关：是否允许空参数
# true  = 允许空参数(默认ONLINE) - 适用于线上定时任务
# false = 强制要求参数(无参数报错) - 适用于人工操作环境
ALLOW_EMPTY_PARAM=false

ASSET_STATUS="ONLINE"  # 默认值

# 检查参数要求
if [ "$ALLOW_EMPTY_PARAM" = "false" ] && [ -z "$1" ]; then
    echo "错误: 当前环境要求必须指定资产状态参数"
    echo "用法: $0 [Rep|Pur|New|Act|Rec]"
    echo "使用 --help 查看详细说明"
    exit 1
fi

# 解析第一个参数(状态码)
if [ -n "$1" ]; then
    case "${1,,}" in  # 转小写处理(bash 4+)
        rep)
            ASSET_STATUS="FAILED_REPLACE"
            ;;
        pur)
            ASSET_STATUS="PURCHASE_IN"
            ;;
        new)
            ASSET_STATUS="NEW_DC_OUT"
            ;;
        act)
            ASSET_STATUS="ONLINE"
            ;;
        rec)
            ASSET_STATUS="DECOM_RETURN"
            ;;
        --help|-h)
            cat << 'EOF'
硬件信息采集工具 - 资产状态参数说明
用法: ./get_hwinfo.sh [状态码]

状态码 (大小写兼容):
  Rep  故障替换入库 (FAILED_REPLACE)
  Pur  采购入库 (PURCHASE_IN)
  New  新建机房出库 (NEW_DC_OUT)
  Act  线上资产 (ONLINE)
  Rec  撤点回收入库 (DECOM_RETURN)
  无参 默认线上资产 (ONLINE)

示例:
  ./get_hwinfo.sh        # 定时任务，默认ONLINE
  ./get_hwinfo.sh Pur    # 采购入库
  ./get_hwinfo.sh New    # 新机房部署
  ./get_hwinfo.sh Rep    # 故障替换
  ./get_hwinfo.sh Rec    # 撤点回收
EOF
            exit 0
            ;;
        *)
            echo "错误: 无效的状态码 '$1'"
            echo "有效值: Rep Pur New Act Rec (大小写兼容)"
            exit 1
            ;;
    esac
fi

sleep  $(($RANDOM%60))

n=$(ps aux | grep -v grep| grep "get_hwinfo.sh"|wc -l)
if [ "$n" -gt 2 ];then
    exit 1
fi
if [ -f /etc/debian_version ];then
    system=debian
elif [ -f /etc/rehdat-release ];then
    system=centos
    source /etc/profile
    source /etc/init.d/functions
else
    system=centos
    source /etc/profile
    source /etc/init.d/functions
fi
#
if [ -f /etc/xyapp/hostname ];then
    host_name=$(cat /etc/xyapp/hostname)
elif [ -f /etc/xyapp/.device_id ];then
    #snode
    host_name=$(cat /etc/xyapp/.device_id)
elif [ -f /etc/xyapp/.efuse_sn ];then
    #x86
    host_name=$(cat /etc/xyapp/.efuse_sn)
else
    host_name=$(hostname)
fi
#
num=$(ps aux | grep -v grep | grep yum|wc -l)
if [ $system == debian ];then
    num_apt=$(ps aux | grep -v grep | grep apt-get|wc -l)
    if [ "$num_apt" -le 2 ];then
        [ -f /usr/sbin/smartctl ] || apt-get install -y smartmontools
        [ -f /usr/bin/unzip ] || apt-get install -y unzip
        which lshw &> /dev/null || apt-get install -y lshw
    fi
elif [ "$num" -le 2 ];then
    [ -f /usr/sbin/smartctl ] || yum install -y smartmontools
    [ -f /usr/bin/unzip ] || yum  install -y unzip
    which lshw &> /dev/null || yum install -y lshw
fi
TIME=$(date +%Y%m%d%H%M%S)
report_time=$(date +%F" "%T)
export PATH=/bin/:/sbin:/usr/bin/:/usr/sbin:/usr/local/sbin/:/usr/local/bin/:$PATH
[ -d /usr/local/op-base/log ] || mkdir -p /usr/local/op-base/log/
logfile=/usr/local/op-base/log/hwinfo_v2.log$(date "+%Y%m%d")
WORKDIR=$(mkdir -p /tmp/hwInfo_${CURTIME} && cd /tmp/hwInfo_${CURTIME} && pwd)

#删除90天以前的日志文件
find /usr/local/op-base/log/ -name 'hwinfo*.log*' -mtime +90 -exec rm -rf {} \;

# 上报函数
report_hwinfo() {
    # 参数：host htype manuf sn model stype spec disk_interface disk_form_factor disk_rpm mem_freq disk_health asset_status
    local host="$1"
    local htype="$2"
    local manuf="$3"
    local sn="$4"
    local model="$5"
    local stype="$6"
    local spec="$7"
    local disk_interface="${8:-UNKNOWN}"
    local disk_form_factor="${9:-UNKNOWN}"
    local disk_rpm="${10:-UNKNOWN}"
    local mem_freq="${11:-UNKNOWN}"
    local disk_health="${12:-UNKNOWN}"
    local asset_status="${13:-ONLINE}"
    curl -s --connect-timeout 5 --max-time 10 -H "Content-type: application/json" -X POST -d \
    "{\"host\":\"$host\",\"htype\":\"$htype\",\"manuf\":\"$manuf\",\"sn\":\"$sn\",\"model\":\"$model\",\"stype\":\"$stype\",\"spec\":\"$spec\",\"disk_interface\":\"$disk_interface\",\"disk_form_factor\":\"$disk_form_factor\",\"disk_rpm\":\"$disk_rpm\",\"mem_freq\":\"$mem_freq\",\"disk_health\":\"$disk_health\",\"asset_status\":\"$asset_status\"}" \
    "http://121.228.177.1/o_edge_server_base_info" > /dev/null 2>&1
}

#获取硬盘信息
Micron=(
MTFDDAK480TDC-1AT1ZABYY
MTFDDAK960TDC-1AT1ZABYY
MTFDDAK1T9TDC-1AT1ZABYY
MTFDDAK3T8TDC-1AT1ZABYY
MTFDDAK7T6TDC-1AT1ZABYY
MTFDDAK960TDD-1AT1ZABYY
MTFDDAK1T9TDD-1AT1ZABYY
)

# 检查磁盘健康度函数
# 参数: $1=设备路径 (如: /dev/sda 或 sda), $2=smartctl输出文件路径
# 输出: PASSED | FAILED | UNKNOWN
check_disk_health() {
    local device="$1"
    local smartctl_file="$2"
    
    [ ! -f "$smartctl_file" ] && echo "UNKNOWN" && return 0
    
    local smartctl_output=$(cat "$smartctl_file")
    
    # 确保设备路径格式正确
    [[ "$device" != /dev/* ]] && device="/dev/$device"
    
    # 检查是否为 SSD/NVMe (包含Solid State或SSD或NVMe字符串)
    if ! echo "$smartctl_output" | grep -Eiq "Solid State|SSD|NVMe"; then
        # ========== HDD 检查逻辑 ==========
        
        # 1. UDMA_CRC_Error_Count (CRC错误计数) - HDD最常见的故障指标
        local crc_error=$(echo "$smartctl_output" | grep -i "UDMA_CRC_Error_Count" | awk '{print $NF}')
        if [ -n "$crc_error" ] && [ "$crc_error" -gt 100 ] 2>/dev/null; then
            echo "FAILED"
            return 0
        fi
        
        # 2. Offline_Uncorrectable (离线无法纠正错误)
        local offline_uncorr=$(echo "$smartctl_output" | grep -i "Offline_Uncorrectable" | awk '{print $NF}')
        if [ -n "$offline_uncorr" ] && [ "$offline_uncorr" -gt 0 ] 2>/dev/null; then
            echo "FAILED"
            return 0
        fi
        
        # 3. ATA Error Count (错误计数日志)
        local ata_error=$(echo "$smartctl_output" | grep -i "ATA Error Count:" | awk -F":" '{print $2}' | awk '{print $1}')
        if [ -n "$ata_error" ] && [ "$ata_error" -gt 10 ] 2>/dev/null; then
            echo "FAILED"
            return 0
        fi
    else
        # ========== SSD 检查逻辑 ==========
        
        # 1. 优先检查 Percentage Used (NVMe)
        local percent_used=$(echo "$smartctl_output" | grep -i "Percentage Used" | head -1 | awk -F":" '{print $2}' | sed 's/[%[:space:]]*//g')
        if [ -n "$percent_used" ] && [ "$percent_used" -gt 0 ] 2>/dev/null; then
            if [ "$percent_used" -gt 10 ]; then
                echo "FAILED"
            else
                echo "PASSED"
            fi
            return 0
        fi
        
        # 2. 检查磁盘健康度指标 - Wear_Leveling_Count (ID 177)
        local wear_leveling=$(echo "$smartctl_output" | grep -i "Wear_Leveling_Count" | awk '{print $4}')
        if [ -n "$wear_leveling" ] && [ "$wear_leveling" -ge 90 ] 2>/dev/null; then
            echo "PASSED"
            return 0
        fi
        if [ -n "$wear_leveling" ] && [ "$wear_leveling" -lt 90 ] 2>/dev/null; then
            echo "FAILED"
            return 0
        fi
        
        # 3. 检查Media_Wearout_Indicator (ID 233)
        local media_wearout=$(echo "$smartctl_output" | grep -i "Media_Wearout_Indicator" | awk '{print $4}')
        if [ -n "$media_wearout" ] && [ "$media_wearout" -ge 90 ] 2>/dev/null; then
            echo "PASSED"
            return 0
        fi
        if [ -n "$media_wearout" ] && [ "$media_wearout" -lt 90 ] 2>/dev/null; then
            echo "FAILED"
            return 0
        fi
    fi
    
    # 通用检查 (SSD和HDD都适用)
    # 4. Reallocated_Sector_Ct (重新分配扇区)
    local reallocated=$(echo "$smartctl_output" | grep -i "Reallocated_Sector_Ct" | awk '{print $NF}')
    if [ -n "$reallocated" ] && [ "$reallocated" -gt 0 ] 2>/dev/null; then
        echo "FAILED"
        return 0
    fi
    
    # 5. Current_Pending_Sector (当前待映射扇区)
    local pending=$(echo "$smartctl_output" | grep -i "Current_Pending_Sector" | awk '{print $NF}')
    if [ -n "$pending" ] && [ "$pending" -gt 0 ] 2>/dev/null; then
        echo "FAILED"
        return 0
    fi
    
    # 6. 检查SMART overall-health (优先级最低)
    local overall_health=$(echo "$smartctl_output" | grep -i "SMART overall-health" | awk -F":" '{print $2}' | sed 's/^[[:space:]]*//g' | awk '{print $1}')
    if [ -n "$overall_health" ]; then
        if echo "$overall_health" | grep -Eiq "PASSED|OK"; then
            echo "PASSED"
            return 0
        else
            echo "FAILED"
            return 0
        fi
    fi
    
    echo "UNKNOWN"
    return 0
}
declare -x -A SERVER=(
[SA5112M4]=1U
[SA5212M4]=2U
[SA5212H2]=2U
[NF5270M3]=2U
[ProLiant_DL380p_Gen8]=2U
[ProLiant_DL380_Gen9]=2U
[ProLiant_DL360p_Gen8]=2U
[ProLiant_DL360_G7]=1U
[XH320_V2]=2U
[PR2012GS]=2U
[PR2014RS]=2U
[PR1710G]=1U
[PR1715G]=1U
[PowerEdge_R430]=2U
[PowerEdge_R510]=2U
[PowerEdge_R620]=1U
[PowerEdge_R630]=1U
[PowerEdge_R720xd]=2U
[PowerEdge_R730]=2U
[PowerEdge_R730xd]=2U
[PowerEdge_R730XD]=2U
[PowerEdge_R720]=2U
[RH2288H_V2-12L]=2U
[RH1288_V3]=1U
[RH2288_V3]=2U
[RH2288H_V3]=2U
[RH2288_V2-12]=2U
[RH1288_V2-8S]=1U
[1288H_V5]=1U
[RH2285_V2-12L]=2U
[Tecal_RH2285]=2U
[Tecal_RH1288_V2-8S]=1U
[Tecal_RH2288H_V2-12L]=2U
[XH321_V2]=2U
[RD450X]=2U
[ThinkServer_RD540_]=1U
)
#
get_diskinfo_smartctl() {
    local smartctl_output=$(smartctl -a /dev/$1 2>/dev/null)
    if echo "$smartctl_output" |grep -E "Model Family"|grep -Eiq "Intel" ;then
	MFT=Intel
    elif echo "$smartctl_output" | grep -i "Model"|grep -Eiq "TOSHIBA|MG04ACA600E";then
        MFT=TOSHIBA
    else 
       MFT=$(echo "$smartctl_output" |grep -E "Model Family"|tr -s " "|awk -F":" '{print $2}'|awk '{print $1}')
    fi
    [ ! -n "$MFT" ] && MFT=$(echo "$smartctl_output" |grep -E "Vendor"|awk -F":" '{print $2}'|awk '{print $1}')
    MOD=$(echo "$smartctl_output" |grep -E "Device Model"|tr -s " "|awk -F":" '{print $2}')
    [ ! -n "$MOD" ] && MOD=$(echo "$smartctl_output" |grep -E "Product"|tr -s " "|awk -F":" '{print $2}')
    if echo "$MOD" | grep -qi "HUS";then
        [ ! -n "$MFT" ] && MFT=HGST
    elif echo "$MOD" | grep -qi "SSDSC";then
	[ ! -n "$MFT" ] && MFT=Intel
    elif echo "$MOD" | grep -qi "P5E-2TB";then
	[ ! -n "$MFT" ] && MFT=KingSpec
    elif echo "$MOD" | grep "MK0800GCTZB";then
	[ ! -n "$MFT" ] && MFT=Intel
    elif echo "$MOD" | grep -qi "KIOXIA";then
	[ ! -n "$MFT" ] && MFT=KIOXIA
    elif echo "$MOD" | grep -qiE "MTFDDAK|Crucial|Micron";then
	[ ! -n "$MFT" ] && MFT=Micron
    elif echo "$MOD" | grep -Ewqi "GLOWAY|tigo|HP|WD|WDC|Samsung|Gomos";then
        [ ! -n "$MFT" ] && MFT=$(echo "$MOD" | grep -Ewoi "GLOWAY|tigo|HP|WD|WDC|Samsung|Gomos")
    fi
    MEDIA=$(echo "$smartctl_output" |grep -E "Rotation Rate"|awk -F":" '{print $2}')
    SIZE=$(echo "$smartctl_output" |grep -E "Capacity"|grep -Eio "[0-9.]* TB|[0-9]* GB")
    SN=$(echo "$smartctl_output" |grep -E "Serial" | awk '{print $3}')
    
    # 获取健康度 - 通过临时文件传递数据，避免变量传递导致的问题
    local health_tmp="/tmp/smartctl_$1_$$.tmp"
    echo "$smartctl_output" > "$health_tmp"
    HEALTH=$(check_disk_health "$1" "$health_tmp")
    rm -f "$health_tmp"
    [ -z "$HEALTH" ] && HEALTH="UNKNOWN"
    
    # 获取接口类型
    INTERFACE=$(echo "$smartctl_output" | grep -E "SATA Version is|Transport protocol" | head -1 | awk '{if(/SATA/) print "SATA"; else if(/SAS/) print "SAS"; else if(/NVMe/) print "NVMe"; else print "UNKNOWN"}')
    [ -z "$INTERFACE" ] && INTERFACE=$(lsblk -d -o NAME,TRAN 2>/dev/null | grep -w "$1" | awk '{print $2}' | tr '[:lower:]' '[:upper:]')
    [ -z "$INTERFACE" ] && INTERFACE="UNKNOWN"
    
    # 获取物理尺寸 (Form Factor 字段)
    FORM_FACTOR=$(echo "$smartctl_output" | grep -E "Form Factor" | awk -F":" '{print $2}' | sed 's/^[[:space:]]*//g')
    FORM_FACTOR=$(echo "$FORM_FACTOR" | tr -d '"' | sed -E 's/[[:space:]]*inches?//Ig' | sed -E 's/[[:space:]]+$//g')
    [ -z "$FORM_FACTOR" ] && FORM_FACTOR="UNKNOWN"
    
    # 获取转速
    if echo "$MEDIA" | grep -Eiq "Solid State|SSD"; then
        RPM="0"
    else
        RPM=$(echo "$MEDIA" | grep -Eo "[0-9]+" | head -1)
        [ -z "$RPM" ] && RPM="UNKNOWN"
    fi
    
    [ ! -n "$MFT" ] && MFT=NULL
    [ ! -n "$MOD" ] && MOD=NULL
    [ ! -n "$SIZE" ] && SIZE=NULL 
    tran_disk_unit $SIZE
    [ ! -n "$SN" ] && SN=$1
    if echo $MFT | grep -iq SSD || echo $MEDIA | grep -iq Solid ;then
        TYPE=SSD
        RPM="0"
    else
        TYPE=HDD
    fi
    if [ "$TYPE" = "SSD" ] && [ "$FORM_FACTOR" = "UNKNOWN" ]; then
        FORM_FACTOR="2.5"
    fi
    echo "${host_name}, Hardwre_type:Disk, Manufacturer:$MFT, SN:$SN, Model:$MOD, Type:$TYPE, Form:$SIZE, Interface:$INTERFACE, FormFactor:$FORM_FACTOR, RPM:$RPM, Health:$HEALTH, AssetStatus:$ASSET_STATUS"
    echo -e "${report_time}\x01${host_name}\x01Disk\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${SIZE}\x01${INTERFACE}\x01${FORM_FACTOR}\x01${RPM}\x01UNKNOWN\x01${HEALTH}\x01${ASSET_STATUS}" >> $logfile
    report_hwinfo "$host_name" "Disk" "$MFT" "$SN" "$MOD" "$TYPE" "$SIZE" "$INTERFACE" "$FORM_FACTOR" "$RPM" "UNKNOWN" "$HEALTH" "$ASSET_STATUS"
}
#
get_diskinfo_sas() {
    line=$*    
    # 解析容量大小
    if echo $line | grep -qi MB ;then
        SIZE=$(echo  $line|grep -Eo "[0-9]+/[0-9]+"|awk -F"/" '{print $1 "MB"}')
    elif echo $line | grep -qi GB ;then
        SIZE=$(echo  $line|grep -Eo "[0-9]+/[0-9]+"|awk -F"/" '{print $1 "GB"}')
    else
        SIZE=$(echo  $line|grep -Eo "[0-9]+/[0-9]+"|awk -F"/" '{print $1}')
    fi
    [ ! -n "$SIZE" ] && SIZE=NULL 
    tran_disk_unit $SIZE
    MFT=$(echo $line|awk -F"," '{print $2}'|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
    MOD=$(echo $line|awk -F"," '{print $3}'|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
    if echo $MOD | grep -iq intel;then
	MOD=$(echo $MOD|awk '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
    fi
    SN=$(echo $line|awk -F"," '{print $4}'|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
    Drive_TYPE=$(echo $line|awk -F"," '{print $6}'|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
    if echo $line | grep -qi SSD ;then
        TYPE=SSD
        RPM="0"
    else
	TYPE=HDD
        RPM="UNKNOWN"
    fi
    # SAS接口固定为SAS类型
    INTERFACE="SAS"
    FORM_FACTOR="UNKNOWN"
    if [ "$TYPE" = "SSD" ] && [ "$FORM_FACTOR" = "UNKNOWN" ]; then
        FORM_FACTOR="2.5"
    fi
    # 尝试通过 smartctl 获取 SAS 磁盘的健康状态、FormFactor 和 RPM
    HEALTH="UNKNOWN"
    # 查找 /dev/sd* 设备中与此 SN 匹配的设备
    for dev in /dev/sd[a-z]*; do
        if [ -e "$dev" ]; then
            dev_sn=$(smartctl -i "$dev" 2>/dev/null | grep -i "Serial Number" | awk -F":" '{print $2}' | sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
            if [ "$dev_sn" = "$SN" ]; then
                # 找到了匹配的设备，获取完整的 smartctl 输出
                smartctl_output=$(smartctl -a "$dev" 2>/dev/null)
                if [ -n "$smartctl_output" ]; then
                    # 使用临时文件方式调用 check_disk_health
                    local health_tmp="/tmp/smartctl_sas_${dev##*/}_$$.tmp"
                    echo "$smartctl_output" > "$health_tmp"
                    HEALTH=$(check_disk_health "${dev##*/}" "$health_tmp")
                    rm -f "$health_tmp"
                    
                    # 从 smartctl 输出中提取 FormFactor
                    FORM_FACTOR=$(echo "$smartctl_output" | grep -E "Form Factor" | awk -F":" '{print $2}' | sed 's/^[[:space:]]*//g')
                    FORM_FACTOR=$(echo "$FORM_FACTOR" | tr -d '"' | sed -E 's/[[:space:]]*inches?//Ig' | sed -E 's/[[:space:]]+$//g')
                    [ -z "$FORM_FACTOR" ] && FORM_FACTOR="UNKNOWN"
                    
                    # 从 smartctl 输出中提取 RPM（转速）
                    MEDIA=$(echo "$smartctl_output" | grep -E "Rotation Rate" | awk -F":" '{print $2}')
                    if echo "$MEDIA" | grep -Eiq "Solid State|SSD"; then
                        RPM="0"
                    else
                        RPM=$(echo "$MEDIA" | grep -Eo "[0-9]+" | head -1)
                        [ -z "$RPM" ] && RPM="UNKNOWN"
                    fi
                fi
                break
            fi
        fi
    done
    echo "${host_name}, Hardwre_type:Disk, Manufacturer:$MFT, SN:$SN, Model:$MOD, Type:$TYPE, Form:$SIZE, Interface:$INTERFACE, FormFactor:$FORM_FACTOR, RPM:$RPM, Health:$HEALTH, AssetStatus:$ASSET_STATUS"
    echo -e "${report_time}\x01${host_name}\x01Disk\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${SIZE}\x01${INTERFACE}\x01${FORM_FACTOR}\x01${RPM}\x01UNKNOWN\x01${HEALTH}\x01${ASSET_STATUS}" >> $logfile
    report_hwinfo "$host_name" "Disk" "$MFT" "$SN" "$MOD" "$TYPE" "$SIZE" "$INTERFACE" "$FORM_FACTOR" "$RPM" "UNKNOWN" "$HEALTH" "$ASSET_STATUS"
}
#
get_diskinfo_mega() {
    if smartctl -d megaraid,$1 -a /dev/sda |grep -E "Model Family"|grep -Ei "Intel" ;then
        MFT=Intel
    elif smartctl -a megaraid,$1 | grep -i "Model"|grep -Eiq "TOSHIBA";then
        MFT=TOSHIBA
    else
        MFT=$(smartctl -d megaraid,$1 -a /dev/sda |grep -E "Model Family"|awk -F":" '{print $2}')
    fi
    [ ! -N "$MFT" ] && MFT=$(smartctl -d megaraid,$1 -a /dev/sda |grep -E "Vendor"|tr -s " "|awk -F":" '{print $2}')
    #
    MOD=$(smartctl -d megaraid,$1 -a /dev/sda |grep -E "Device Model"|tr -s " "|awk -F":" '{print $2}')
    [ ! -N "$MOD" ] && MOD=$(smartctl -d megaraid,$1 -a /dev/sda |grep -E "Product"|tr -s " "|awk -F":" '{print $2}')
    #
    MEDIA=$(smartctl -d megaraid,$1 -a /dev/sda |grep -E "Rotation Rate"|awk -F":" '{print $2}')
    SN=$(smartctl -d megaraid,$1 -a /dev/sda |grep -E "Serial" | awk '{print $3}')
    SIZE=$(smartctl -d megaraid,$1 -a /dev/sda |grep -E "Capacity"|grep -Eio "[0-9.]* TB|[0-9]* GB")
    
    # 获取转速
    if echo "$MEDIA" | grep -Eiq "Solid State|SSD"; then
        RPM="0"
    else
        RPM=$(echo "$MEDIA" | grep -Eo "[0-9]+" | head -1)
        [ -z "$RPM" ] && RPM="UNKNOWN"
    fi
    
    [ ! -n "$MFT" ] && MFT=NULL
    [ ! -n "$MOD" ] && MOD=NULL
    [ ! -n "$SIZE" ] && SIZE=NULL 
    tran_disk_unit $SIZE
    [ ! -n "$SN" ] && SN=$1
    if echo $MFT | grep -iq SSD || echo $MEDIA | grep -iq Solid ;then
        TYPE=SSD
        RPM="0"
    else
        TYPE=HDD
    fi
    
    # MegaRAID 阵列卡接口类型通常为SAS/SATA
    INTERFACE="RAID"
    FORM_FACTOR="UNKNOWN"
    if [ "$TYPE" = "SSD" ] && [ "$FORM_FACTOR" = "UNKNOWN" ]; then
        FORM_FACTOR="2.5"
    fi
    # 尝试通过 smartctl 获取 MegaRAID 磁盘的健康状态
    HEALTH="UNKNOWN"
    smartctl_output=$(smartctl -d megaraid,$1 -a /dev/sda 2>/dev/null)
    if [ -n "$smartctl_output" ]; then
        local health_tmp="/tmp/smartctl_mega_$1_$$.tmp"
        echo "$smartctl_output" > "$health_tmp"
        HEALTH=$(check_disk_health "sda" "$health_tmp")
        rm -f "$health_tmp"
        [ -z "$HEALTH" ] && HEALTH="UNKNOWN"
        
        # 从 smartctl 输出中提取 FormFactor
        FORM_FACTOR=$(echo "$smartctl_output" | grep -E "Form Factor" | awk -F":" '{print $2}' | sed 's/^[[:space:]]*//g')
        FORM_FACTOR=$(echo "$FORM_FACTOR" | tr -d '"' | sed -E 's/[[:space:]]*inches?//Ig' | sed -E 's/[[:space:]]+$//g')
        [ -z "$FORM_FACTOR" ] && FORM_FACTOR="UNKNOWN"
    fi
    echo "${host_name}, Hardwre_type:Disk, Manufacturer:$MFT, SN:$SN, Model:$MOD, Type:$TYPE, Form:$SIZE, Interface:$INTERFACE, FormFactor:$FORM_FACTOR, RPM:$RPM, Health:$HEALTH, AssetStatus:$ASSET_STATUS"
    echo -e "${report_time}\x01${host_name}\x01Disk\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${SIZE}\x01${INTERFACE}\x01${FORM_FACTOR}\x01${RPM}\x01UNKNOWN\x01${HEALTH}\x01${ASSET_STATUS}" >> $logfile
    report_hwinfo "$host_name" "Disk" "$MFT" "$SN" "$MOD" "$TYPE" "$SIZE" "$INTERFACE" "$FORM_FACTOR" "$RPM" "UNKNOWN" "$HEALTH" "$ASSET_STATUS"
}

get_diskinfo_mega2() {
    line=$*
    if echo $line | grep -q "MTFDDAK";then
        MFT=Micron
        MOD=$(echo $line|grep -Eo "MTFDDAK[0-9A-Z-]*")
        SN=$(echo $line|awk -F"," '{print $3}'|awk '{print $3}'|awk -F"MTFDDAK" '{print $1}')
    elif echo $line | grep -Eq "CT1000|CT960";then
	MFT=Micron
        MOD=$(echo $line|awk -F"," '{print $3}'|awk '{print $4}')                                                                                                         
        SN=$(echo $line |awk -F"," '{print $3}'|awk '{print $3}') 
    elif echo $line | grep -iq "SEAGATE";then
        MFT=SEAGATE
        MOD=$(echo $line|awk -F"," '{print $3}'|awk '{print $4}')
        SN=$(echo $line |awk -F"," '{print $3}'|awk '{print $5}')
    elif echo $line | grep -Eqi "ST9100|ST6000";then
        MFT=SEAGATE
        MOD=$(echo $line|awk -F"," '{print $3}'|awk '{print $3}'|grep -Eo "(ST9100|ST6000)[0-9A-Z-]*")
        SN=$(echo $line|awk -F"," '{print $3}'|awk '{print $3}'|awk -F"ST" '{print $1}')
    elif echo $line | grep -iq "HGST";then
        MFT=HGST
        MOD=$(echo $line|awk -F"," '{print $3}'|awk '{print $4}')
        SN=$(echo $line|awk -F"," '{print $3}'|awk '{print $3}'|awk -F "HGST" '{print $1}')
    elif echo $line | grep -iqE "SSDSC|INTEL";then
        MFT=Intel
        MOD=$(echo $line|grep -Eo "SSDSC[0-9A-Z]*")
        SN=$(echo $line|awk -F"," '{print $3}'|awk '{print $3}'|awk -F"SSDSC" '{print $1}'|sed -e 's/INTEL//' -e 's/ATA//')
        [[ "$MOD" == *PHDV* || "$MOD" == *BTWA* ]] && MOD=$(echo $MOD|awk -F"PHDV|BTWA" '{print $1}') && SN=$(echo $line|grep -Eo "PHDV[0-9A-Z]*|BTWA[0-9A-Z]*")
    elif echo $line | grep -iqE "VK0800GDJYA";then
        MFT=Intel
        MOD=$(echo $line|awk -F"," '{print $3}'|awk '{print $4}')
        SN=$(echo $line |awk -F"," '{print $3}'|awk '{print $3}')                                                                                                   
    elif echo $line | grep -iqE "SAMSUNG";then
	MFT=SAMSUNG
        MOD=$(echo $line|awk -F"," '{print $3}'|awk -F"SAMSUNG" '{print $2}'|awk '{print $1}')
        SN=$(echo $line|awk -F"," '{print $3}'|awk -F"SAMSUNG" '{print $1}'|awk '{print $3}')
    elif echo $line | grep -iqE "SDLF1DAM";then
        MFT=SanDisk
        MOD=$(echo $line|awk -F"," '{print $3}'|grep -Eo "SDLF1DAM[0-9A-Z-]*")
        SN=$(echo $line|awk -F"," '{print $3}'|awk -F"SDLF1DAM" '{print $1}')
    else
        MFT=$(echo $line|awk -F"," '{print $3}'|awk '{print $4}')                                                                                                         
        MOD=$(echo $line|awk -F"," '{print $3}'|awk '{print $5}')                                                                                                         
        SN=$(echo $line |awk -F"," '{print $3}'|awk '{print $3}')                                                                                                   
    fi
    SIZE=$(echo $line|awk -F"," '{print $2}'|awk '{print $3" "$4}')                                                                          
    [ ! -n "$MFT" ] && MFT=NULL
    [ ! -n "$MOD" ] && MOD=NULL
    [ ! -n "$SIZE" ] && SIZE=NULL 
    tran_disk_unit $SIZE
    [ ! -n "$SN" ] && SN=NULL
    echo $line|awk -F"," '{print $4}'| grep -iq solid && TYPE=SSD || TYPE=HDD 
    [[ "$MOD" == *SSD* ]] && TYPE=SSD
    
    # 设置转速
    if [ "$TYPE" == "SSD" ]; then
        RPM="0"
    else
        RPM="UNKNOWN"
    fi
    
    INTERFACE="RAID"
    FORM_FACTOR="UNKNOWN"
    if [ "$TYPE" = "SSD" ] && [ "$FORM_FACTOR" = "UNKNOWN" ]; then
        FORM_FACTOR="2.5"
    fi
    # 尝试通过 smartctl 获取 MegaCli64 磁盘的健康状态
    HEALTH="UNKNOWN"
    if [ -n "$SN" ] && [ "$SN" != "NULL" ]; then
        # 查找 /dev/sd* 设备中与此 SN 匹配的设备
        for dev in /dev/sd[a-z]*; do
            if [ -e "$dev" ]; then
                dev_sn=$(smartctl -i "$dev" 2>/dev/null | grep -i "Serial Number" | awk -F":" '{print $2}' | sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
                if [ "$dev_sn" = "$SN" ]; then
                    # 找到了匹配的设备，获取完整的 smartctl 输出
                    smartctl_output=$(smartctl -a "$dev" 2>/dev/null)
                    if [ -n "$smartctl_output" ]; then
                        local health_tmp="/tmp/smartctl_mega2_${dev##*/}_$$.tmp"
                        echo "$smartctl_output" > "$health_tmp"
                        HEALTH=$(check_disk_health "${dev##*/}" "$health_tmp")
                        rm -f "$health_tmp"
                        [ -z "$HEALTH" ] && HEALTH="UNKNOWN"
                        
                        # 从 smartctl 输出中提取 FormFactor 和 RPM
                        FORM_FACTOR=$(echo "$smartctl_output" | grep -E "Form Factor" | awk -F":" '{print $2}' | sed 's/^[[:space:]]*//g')
                        FORM_FACTOR=$(echo "$FORM_FACTOR" | tr -d '"' | sed -E 's/[[:space:]]*inches?//Ig' | sed -E 's/[[:space:]]+$//g')
                        [ -z "$FORM_FACTOR" ] && FORM_FACTOR="UNKNOWN"
                        
                        MEDIA=$(echo "$smartctl_output" | grep -E "Rotation Rate" | awk -F":" '{print $2}')
                        if echo "$MEDIA" | grep -Eiq "Solid State|SSD"; then
                            RPM="0"
                        else
                            RPM=$(echo "$MEDIA" | grep -Eo "[0-9]+" | head -1)
                            [ -z "$RPM" ] && RPM="UNKNOWN"
                        fi
                    fi
                    break
                fi
            fi
        done
    fi
    echo "${host_name}, Hardwre_type:Disk, Manufacturer:$MFT, SN:$SN, Model:$MOD, Type:$TYPE, Form:$SIZE, Interface:$INTERFACE, FormFactor:$FORM_FACTOR, RPM:$RPM, Health:$HEALTH, AssetStatus:$ASSET_STATUS"
    echo -e "${report_time}\x01${host_name}\x01Disk\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${SIZE}\x01${INTERFACE}\x01${FORM_FACTOR}\x01${RPM}\x01UNKNOWN\x01${HEALTH}\x01${ASSET_STATUS}" >> $logfile
    report_hwinfo "$host_name" "Disk" "$MFT" "$SN" "$MOD" "$TYPE" "$SIZE" "$INTERFACE" "$FORM_FACTOR" "$RPM" "UNKNOWN" "$HEALTH" "$ASSET_STATUS"
}

get_diskinfo_nvme() {
    dev=$1
    local smartctl_output=$(smartctl -a /dev/$dev 2>/dev/null)
    MOD=$(echo "$smartctl_output" | grep -iE "Model Number|Device Model|Product" | head -1 | awk -F":" '{print $2}' | sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
    [ -z "$MOD" ] && MOD=$(echo "$smartctl_output" | grep -i "Model" | head -1 | sed -e 's/.*Model[^:]*:[[:space:]]*//g' -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')

    if echo "$MOD" | grep -Eqi "^WUS|^WDS|^WD|Western Digital|WDC"; then
        MFT=WDC
    elif echo "$MOD" | grep -Eqi "CT1000|CT2000|CT960|MTFDDAK|Crucial|Micron"; then
        MFT=Micron
    elif echo "$MOD" | grep -Eqi "INTEL|SSDSC"; then
        MFT=Intel
    elif echo "$MOD" | grep -Eqi "KIOXIA"; then
        MFT=KIOXIA
    elif echo "$MOD" | grep -Eqi "SAMSUNG"; then
        MFT=SAMSUNG
    else
        MFT=$(echo "$smartctl_output" | grep -iE "Model Family|Vendor" | head -1 | awk -F":" '{print $2}' | awk '{print $1}')
    fi

    SIZE=$(echo "$smartctl_output" | grep -E "Total NVM Capacity|Namespace 1 Size/Capacity|User Capacity|Capacity" | head -1 | grep -Eo "[0-9]+\.?[0-9]* TB|[0-9]+\.?[0-9]* GB")
    [ -z "$SIZE" ] && SIZE=$(lsblk | grep -w disk |grep $dev|awk '{print$4}'|sed -e's/G/ G/' -e's/T/ T/') 
    SN=$(echo "$smartctl_output" | grep -i "Serial Number" | head -1 | awk -F":" '{print $2}' | sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
    [ -z "$SN" ] && SN=$(echo "$smartctl_output" | grep -i "Serial" | awk '{print $3}')
    [ ! -n "$MFT" ] && MFT=NULL
    [ ! -n "$MOD" ] && MOD=$dev
    [ ! -n "$SIZE" ] && SIZE=NULL 
    tran_disk_unit $SIZE
    [ ! -n "$SN" ] && SN=$dev
    TYPE=SSD
    RPM="0"
    INTERFACE="NVMe"
    FORM_FACTOR="M.2"
    
    # 获取NVMe健康度 - 通过临时文件传递数据
    local health_tmp="/tmp/smartctl_nvme_$dev_$$.tmp"
    echo "$smartctl_output" > "$health_tmp"
    HEALTH=$(check_disk_health "/dev/$dev" "$health_tmp")
    rm -f "$health_tmp"
    [ -z "$HEALTH" ] && HEALTH="UNKNOWN"
    
    echo "${host_name}, Hardwre_type:Disk, Manufacturer:$MFT, SN:$SN, Model:$MOD, Type:$TYPE, Form:$SIZE, Interface:$INTERFACE, FormFactor:$FORM_FACTOR, RPM:$RPM, Health:$HEALTH, AssetStatus:$ASSET_STATUS"
    echo -e "${report_time}\x01${host_name}\x01Disk\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${SIZE}\x01${INTERFACE}\x01${FORM_FACTOR}\x01${RPM}\x01UNKNOWN\x01${HEALTH}\x01${ASSET_STATUS}" >> $logfile
    report_hwinfo "$host_name" "Disk" "$MFT" "$SN" "$MOD" "$TYPE" "$SIZE" "$INTERFACE" "$FORM_FACTOR" "$RPM" "UNKNOWN" "$HEALTH" "$ASSET_STATUS"
}

get_diskinfo_vm() {
    dev=$1
    #MFT=vmdisk
    #MOD=vmdisk
    SIZE=$(lsblk | grep -w disk |grep -w $dev|awk '{print$4}'|sed -e 's/G/ G/' -e 's/T/ T/')
    if echo $SIZE | grep -q "G";then
        SIZE=$(echo $SIZE|sed 's/G//')
    elif echo $SIZE | grep -q "T";then
        SIZE=$(echo $SIZE|sed 's/T//'|awk '{print $1*1000}')
    fi
    [ ! -n "$SIZE" ] && SIZE=NULL
    SN=$1
    if [ "$dev" == "vda" ];then
	TYPE=sysdisk
    else
	TYPE=datadisk
    fi
    
    # 虚拟机磁盘字段
    INTERFACE="VIRTIO"
    FORM_FACTOR="VIRTUAL"
    RPM="VIRTUAL"
    HEALTH="UNKNOWN"
    
    echo "${host_name}, Hardwre_type:Disk, Manufacturer:$MFT, SN:$SN, Model:$MOD, Type:$TYPE, Form:$SIZE, Interface:$INTERFACE, FormFactor:$FORM_FACTOR, RPM:$RPM, Health:$HEALTH, AssetStatus:$ASSET_STATUS"
    echo -e "${report_time}\x01${host_name}\x01Disk\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${SIZE}\x01${INTERFACE}\x01${FORM_FACTOR}\x01${RPM}\x01UNKNOWN\x01${HEALTH}\x01${ASSET_STATUS}" >> $logfile
    report_hwinfo "$host_name" "Disk" "$MFT" "$SN" "$MOD" "$TYPE" "$SIZE" "$INTERFACE" "$FORM_FACTOR" "$RPM" "UNKNOWN" "$HEALTH" "$ASSET_STATUS"
}
#
tran_disk_unit() {
    SIZE=$*
    if echo $SIZE | egrep -qi "M|m";then
        num=$(echo $SIZE|awk -F "M|m" '{print $1}'|sed 's/[[:space:]]*//g')
        if [ $(echo "$num > 999.99"|bc) -eq 1 -a $(echo "$num < 1000000" |bc) -eq 1 ];then
	    num=$(echo "${num}*1.024*1.024/1000"|bc)
            SIZE=${num}GB
        elif [ $(echo "$num > 999999.99"|bc) -eq 1 ];then
	    num=$(echo "scale=2; ${num}*1.024*1.024/1000/1000"|bc)
            SIZE=${num}TB
        else
	    num=$(echo "${num}/1"|bc)
            SIZE=${num}MB
	fi
    elif echo $SIZE | egrep -qi "G|g";then
        num=$(echo $SIZE|awk -F "G|g" '{print $1}'|sed 's/[[:space:]]*//g')
        if [ $(echo "$num > 999.99"|bc) -eq 1 ];then
            num=$(echo "scale=2;${num}*1.024*1.024*1.024/1000"|bc)
	    SIZE=${num}TB
	else
	    num=$(echo "${num}/1"|bc)
	    SIZE=${num}GB
	fi
    elif echo $SIZE | egrep -qi "T|t";then
 	num=$(echo $SIZE|awk -F "T|t" '{print $1}'|sed 's/[[:space:]]*//g')
        if echo $num | grep -q "\." ;then
            num=$(echo "scale=2;${num}/1"|bc)
	    SIZE=${num}TB	
	fi
    fi 
}
#
get_diskinfo() {
#获取系统能识别到的磁盘
lsblk |grep -w "disk" |egrep -v "sr|fd|loop" |awk '{print $1}' |sort |uniq > /tmp/fdisk_txt
##
if cat /tmp/fdisk_txt|grep -q nvme;then
   for dev in $(cat /tmp/fdisk_txt|grep nvme);do
       get_diskinfo_nvme $dev
   done
   sed -i '/nvme/d' /tmp/fdisk_txt
fi
#
if lspci -m | grep -iE "sas|raid|sata"| grep -qi MegaRAID ;then
    if [ ! -f /opt/MegaRAID/MegaCli/MegaCli64 ] ;then
        wget  http://thunder:xunlei@apt.sandai.net/basic_setup/dkj/MegeCli_inst.sh -O /tmp/MegeCli_inst.sh  && sh /tmp/MegeCli_inst.sh
    fi
    if lspci -m | grep -i "MegaRAID SAS 1078"|grep Dell ; then
        slot=$(/opt/MegaRAID/MegaCli/MegaCli64 -LdPdInfo -aALL | grep -E "Slot Number"|awk '{print $3}')
        for n in $slot;do
            get_diskinfo_mega $n
        done
    else
        /opt/MegaRAID/MegaCli/MegaCli64 -PDList -aALL | grep -E "Inquiry Data|PD Type|Raw Size|Media Type"|awk '{if (NR%4==0) {print} else {printf "%s,",$0}}'|tr -s " " > /tmp/disk.log
        cat /tmp/disk.log|while read line 
        do
            get_diskinfo_mega2 $line
        done
    fi
elif lspci -m | grep -i lsi | grep -qEi "SAS-2" ;then
    if [ ! -x /usr/bin/sas2ircu ] ;then
	wget  http://thunder:xunlei@apt.sandai.net/initos/down/sas/sas2ircu -O /usr/bin/sas2ircu && chmod 755 /usr/bin/sas2ircu
    fi
    sas2ircu 0 display | egrep -A13 "Hard disk" |grep -Ei "Manufacturer|Serial[[:space:]]*No[[:space:]]*:|Model|SIZE|Type" |awk '{if (NR%5==0) {print} else {printf "%s,",$0}}'|tr -s " " > /tmp/disk.log
    cat /tmp/disk.log|while read line 
    do
        get_diskinfo_sas $line
    done
elif lspci -m | grep -i lsi | egrep -qEi "SAS-3" ;then
    if [ ! -x /usr/bin/sas3ircu ] ; then
	wget  http://thunder:xunlei@apt.sandai.net/initos/down/sas/sas3ircu -O /usr/bin/sas3ircu && chmod 755 /usr/bin/sas3ircu
    fi
    sas3ircu 0 display | egrep -A13 "Hard disk" |grep -Ei "Manufacturer|Serial[[:space:]]*No[[:space:]]*:|Model|SIZE|Type" |awk '{if (NR%5==0) {print} else {printf "%s,",$0}}'|tr -s " " > /tmp/disk.log
    cat /tmp/disk.log|while read line 
    do
        get_diskinfo_sas $line
    done
elif lspci -m | grep -iE "sas|raid|sata|scsi"| grep -qEi "QEMU|Virtual|Virtio" ;then
    for dev in $(cat /tmp/fdisk_txt);do                                                                                                                              
        get_diskinfo_vm $dev                                                                                                                                       
    done   
else
    for dev in $(cat /tmp/fdisk_txt);do
        get_diskinfo_smartctl $dev
    done
fi
}


#获取物理主机信息
get_hostinfo() {
    MFT=$(dmidecode -s system-manufacturer|grep -v "^#" |egrep -wo "|Dell|HP|IBM|Huawei|Inspur|O.E.M.|Supermicro|Alibaba|Baidu|Sugon|VMware|ctyun|Powerleader") 
    [ -z "$MFT" ] && MFT=$(dmidecode -s system-manufacturer|grep -v "^#" | sed s#[[:space:]]##g)
    MOD=$(dmidecode -s system-product-name|grep -v "^#" |sed -e 's#^[[:space:]]##g' -e 's/[[:space:]]\+/_/g')
    SN=$(dmidecode -s system-serial-number |grep -v "^#" | sed s#[[:space:]]##g)
    SIZE=${SERVER[$MOD]}
    [ -z "$SIZE" ] && SIZE=NULL 
    TYPE=NULL
    echo "${host_name}, Hardwre_type:Host, Manufacturer:$MFT, SN:$SN, Model:$MOD, Type:NULL, Form:$SIZE, AssetStatus:$ASSET_STATUS" 
    echo -e "${report_time}\x01${host_name}\x01Host\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${SIZE}\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01${ASSET_STATUS}" >> $logfile
    report_hwinfo "$host_name" "Host" "$MFT" "$SN" "$MOD" "$TYPE" "$SIZE" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "$ASSET_STATUS"
}
get_vm_hostinfo(){
    #MFT=$(dmidecode -s system-manufacturer|grep -v "^#" |egrep -wo "Huawei|Alibaba|Baidu||VMware|ctyun")
    #MOD=$(dmidecode -s system-product-name|grep -v "^#" |sed -e 's#^[[:space:]]##g' -e 's/[[:space:]]\+/_/g')
    SN=$(dmidecode -s system-serial-number |grep -v "^#" | sed s#[[:space:]]##g)
    cpu=$(lscpu | grep -i "^CPU(s):"|awk '{print $2}')
    mem=$(dmidecode -t memory | grep "Maximum Capacity"|awk '{print $3}')
    TYPE=NULL
    SIZE=${cpu}C${mem}G
    echo "${host_name}, Hardwre_type:Host, Manufacturer:$MFT, SN:$SN, Model:$MOD, Type:NULL, Form:$SIZE, AssetStatus:$ASSET_STATUS" 
    echo -e "${report_time}\x01${host_name}\x01Host\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${SIZE}\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01${ASSET_STATUS}" >> $logfile
    report_hwinfo "$host_name" "Host" "$MFT" "$SN" "$MOD" "$TYPE" "$SIZE" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "$ASSET_STATUS"
}
#获取cpu的信息
get_cpuinfo() {
    MFT=$(lscpu | grep "Vendor ID"|tr -s " "|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
    MOD=$(lscpu | grep "Model name" | awk -F":" '{print $2}'| sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g' -e "s#[[:space:]]\+#_#g")
    [ -z "$MOD" ] && MOD=$(cat /proc/cpuinfo|grep -i "model name"|head -1|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g' -e "s#[[:space:]]\+#_#g")
    cpu_sockets=$(lscpu | grep -i "^Socket(s):"|awk '{print $2}')
    [ -z "$cpu_sockets" ] && cpu_sockets=1
    cpu_threads=$(lscpu | grep -i "^CPU(s):"|awk '{print $2}')
    cpu_threads=$((cpu_threads/cpu_sockets))
    SN=NULL
    echo "${host_name}, Hardwre_type:CPU, Manufacturer:${MFT}, SN:${SN}, Model:$MOD, Type:${cpu_sockets}P, Form:${cpu_threads}C, AssetStatus:$ASSET_STATUS"
    echo -e "${report_time}\x01${host_name}\x01CPU\x01${MFT}\x01${SN}\x01${MOD}\x01${cpu_sockets}P\x01${cpu_threads}C\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01${ASSET_STATUS}" >> $logfile
    report_hwinfo "$host_name" "CPU" "$MFT" "$SN" "$MOD" "${cpu_sockets}P" "${cpu_threads}C" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "$ASSET_STATUS"
}
#获取内存信息
get_memoryinfo(){
    [ -f /tmp/memory_details_${TIME}.txt ] && rm -f /tmp/memory_details_${TIME}.txt
    for i in  $(dmidecode -t memory  | grep "^Handle" | awk -F '[ ,]+' '{print$2}');do
       mem_size=$(dmidecode -t memory | grep -A22 $i | grep  -i size | awk '{print$2}')
       expr 1 "+" $mem_size &>/dev/null
       if [ $? -eq 0 ];then
         echo "$i "$(dmidecode -t memory | grep -A22 $i  | grep -E "Size|Locator|Type|Speed|Manufacturer|Part Number|Serial Number" | \
	 egrep -v "Bank Locator|Type Detail|Configured Clock Speed|Configured Memory Speed" | sed s#[[:space:]]##g | xargs -n 6 )>> /tmp/memory_details_${TIME}.txt
       else
           continue
       fi
    done
    n=1
    [ ! -f /tmp/memory_details_${TIME}.txt ] &&  dmidecode -t memory | grep -E "^Handle" > /tmp/memory_details_${TIME}.txt
    while read line;do
        SIZE=$(echo $line|awk '{print $2}'|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
        TYPE=$(echo $line|awk '{print $4}'|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
        SPEED=$(echo $line|awk '{print $5}'|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
        MFT=$(echo $line|awk '{print $6}'|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
 	    SN=$(echo $line|awk '{print $7}'|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
        MOD=$(echo $line|awk '{print $8}'|awk -F":" '{print $2}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g')
        if [[ -z "$SN" || "$SN" =~ "None" || "$SN" =~ "none" ]];then
	     SN=$n
        fi
        if echo $SIZE | egrep -qi "MB|mb";then
            SIZE=$(echo $SIZE|awk -F "M|m" '{print int($1/1024)"GB"}')
        elif echo $SIZE | egrep -qi "GB|gb";then
            SIZE=$(echo $SIZE|awk -F "G|g" '{print int($1)"GB"}')
	fi
        
        # 处理内存频率
        [ -z "$SPEED" ] && SPEED="UNKNOWN"
        [[ "$SPEED" =~ ^[0-9]+$ ]] && SPEED="${SPEED}MHz"
        
        echo "${host_name}, Hardwre_type:Memory, Manufacturer:$MFT, SN:$SN, Model:$MOD, Type:$TYPE, Form:$SIZE, Freq:$SPEED, AssetStatus:$ASSET_STATUS"
    	echo -e "${report_time}\x01${host_name}\x01Memory\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${SIZE}\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01${SPEED}\x01UNKNOWN\x01${ASSET_STATUS}" >> $logfile
        report_hwinfo "$host_name" "Memory" "$MFT" "$SN" "$MOD" "$TYPE" "$SIZE" "UNKNOWN" "UNKNOWN" "UNKNOWN" "$SPEED" "UNKNOWN" "$ASSET_STATUS"
        let n+=1
    done < /tmp/memory_details_${TIME}.txt
}
#
#获取网卡信息
get_nicinfo() {
    lshwfile=/tmp/lshw_short.log
    which lshw &> /dev/null && lshw -short > $lshwfile
    [ -f /tmp/lshw_short.log ] || echo "lshw failed" > $lshwfile
    cat /proc/net/dev|grep -vE "tun|face|lo|Inter|ppp|docker|galaxy|virbr|macvlan|dummy"|awk -F":" '{print $1}'|sed s/[[:space:]]//g |grep -vE "\.|:"|sort >${WORKDIR}/eth_list.log
    nics=$(ls /sys/class/net/ | egrep "eth|ens|em|enp|eno|p[0-9]+p[0-9]+" | egrep -v ":|\.|veth")
    for nic in ${nics};do
        eth_mac=$(ethtool -P $nic|awk '{print $NF}')
        eth_port=$(ethtool $nic | grep "Supported ports" | awk -F ":" '{print$2}'| sed s/[[:space:]]//g)
        #eth_max_speed=$(ethtool $nic |grep base|tail -1|grep -Eo "[0-9]+"|head -1)
        eth_max_speed=$(ethtool $nic |grep base|grep -Eo "[0-9]+"|sort|tail -1)
        eth_speed=$(ethtool $nic | grep "Speed" | awk  -F":" '{print$2}'|sed s/[[:space:]]//g|awk -F "g|G|m|M" '{print $1}')
        if echo "$eth_speed" | grep  -qi know;then eth_speed="";fi
        #MOD=$(grep -w $nic $lshwfile|awk '{$1=$2=$3="";print}'|head -n 1|sed 's/^[ ]*//g'|awk '{print $1" "$2" "$3}' |sed 's/[[:space:]]\+/_/g')
        MOD=$(grep -w $nic $lshwfile|awk '{$1=$2=$3="";print}'|head -n 1|awk '{print $1" "$2" "$3}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g'|sed 's/[[:space:]]\+/_/g')
        [ -z "$MOD" ] && MOD=NULL 
        MFT=$nic
        TYPE=${eth_port}
        [ -z "$TYPE" ] && TYPE=NULL
        SN=${eth_mac}
        SPEED=""
        [ ! -z "${eth_max_speed}" ] && SPEED=${eth_max_speed}
        [ -z "${SPEED}" ] && [ ! -z "${eth_speed}" ] && SPEED=${eth_speed}
        [ -z "${SPEED}" ] && SPEED=1000
        
        if [ "$SPEED" -gt 100 ];then
	    SPEED=$(echo $SPEED|awk '{print $1/1000"Gb"}')
        elif [ "$SPEED" -eq 100 ];then
	    SPEED=$(echo $SPEED|awk '{print $1"Mb"}')
        fi
        echo "${host_name}, Hardwre_type:Nic, Manufacturer:${MFT}, SN:${SN}, Model:${MOD},Type:$TYPE, Form:$SPEED, AssetStatus:$ASSET_STATUS"
        echo -e "${report_time}\x01${host_name}\x01Nic\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${SPEED}\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01${ASSET_STATUS}" >> $logfile
        report_hwinfo "$host_name" "Nic" "$MFT" "$SN" "$MOD" "$TYPE" "$SPEED" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "$ASSET_STATUS"
    done
}

get_vm_nicinfo() {
    lshwfile=/tmp/lshw_short.log
    which lshw &> /dev/null && lshw -short > $lshwfile
    [ -f /tmp/lshw_short.log ] || echo "lshw failed" > $lshwfile
    cat /proc/net/dev|grep -vE "tun|face|lo|Inter|ppp|docker|galaxy|virbr|macvlan|dummy"|awk -F":" '{print $1}'|sed s/[[:space:]]//g |grep -vE "\.|:"|sort >${WORKDIR}/eth_list.log
    nics=$(ls /sys/class/net/ | egrep "eth|ens|em|enp|eno|p[0-9]+p[0-9]+" | egrep -v ":|\.|veth")
    for nic in ${nics};do
        eth_mac=$(ethtool -P $nic|awk '{print $NF}')
        eth_port=$(ethtool $nic | grep "Supported ports" | awk -F ":" '{print$2}'| sed s/[[:space:]]//g)
        eth_max_speed=$(ethtool $nic |grep base|grep -Eo "[0-9]+"|sort|tail -1)
        eth_speed=$(ethtool $nic | grep "Speed" | awk  -F":" '{print$2}'|sed s/[[:space:]]//g|awk -F "g|G|m|M" '{print $1}')
        if echo "$eth_speed" | grep  -qi know;then eth_speed="";fi
        #MOD=$(grep -w $nic $lshwfile|awk '{$1=$2=$3="";print}'|head -n 1|awk '{print $1" "$2" "$3}'|sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g'|sed 's/[[:space:]]\+/_/g')
        [ -z "$MOD" ] && MOD=NULL 
        TYPE=${nic}
        [ -z "$TYPE" ] && TYPE=NULL
        if [ "$TYPE" == "eth0" ];then
		FORM=MNC
	else
		FORM=SNC
	fi
        SN=${eth_mac}
        SPEED=""
        [ ! -z "${eth_max_speed}" ] && SPEED=${eth_max_speed}
        [ -z "${SPEED}" ] && [ ! -z "${eth_speed}" ] && SPEED=${eth_speed}
        [ -z "${SPEED}" ] && SPEED=1000
        
        if [ "$SPEED" -gt 100 ];then
	    SPEED=$(echo $SPEED|awk '{print $1/1000"Gb"}')
        elif [ "$SPEED" -eq 100 ];then
	    SPEED=$(echo $SPEED|awk '{print $1"Mb"}')
        fi
        echo "${host_name}, Hardwre_type:Nic, Manufacturer:${MFT}, SN:${SN}, Model:${MOD},Type:$TYPE, Form:$FORM, AssetStatus:$ASSET_STATUS"
        echo -e "${report_time}\x01${host_name}\x01Nic\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${FORM}\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01${ASSET_STATUS}" >> $logfile
        report_hwinfo "$host_name" "Nic" "$MFT" "$SN" "$MOD" "$TYPE" "$FORM" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "$ASSET_STATUS"
    done
}
##获取IP信息
get_vm_ipinfo(){
    #获取ipv4地址
    ip add | grep -w inet | egrep -v "127.0.0.1|inet 10\.|inet 192.168.|inet 172.1[6-9].|inet 172.2[0-9].|inet 172.3[0-1]." > /tmp/ipinfo.log
    while read line ;do
        TYPE=$(echo $line |awk '{print $NF}')
        SN=$(echo $line |awk '{print $2}'|awk -F"/" '{print $1}')
        #MOD=NULL
        FORM=IPV4
        echo "${host_name}, Hardwre_type:IP, Manufacturer:${MFT}, SN:${SN}, Model:${MOD},Type:$TYPE, Form:$FORM, AssetStatus:$ASSET_STATUS"
        echo -e "${report_time}\x01${host_name}\x01IP\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${FORM}\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01${ASSET_STATUS}" >> $logfile
        report_hwinfo "$host_name" "IP" "$MFT" "$SN" "$MOD" "$TYPE" "$FORM" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "$ASSET_STATUS"
    done < /tmp/ipinfo.log
    #获取ipv6地址
    nics=$(ls /sys/class/net/ | egrep "eth|ens|em|enp|eno|p[0-9]+p[0-9]+" | egrep -v ":|\.|veth")
    for nic in ${nics};do
        #MFT=$nic
        #MOD=IPV6
        FORM=IPV6
        num=$(ip addr show $nic | egrep -w "inet6"|egrep -v "inet6 ::1|inet6 fe80::"|wc -l)
        if [ "$num" -eq 0 ];then
            continue
        else
            ip addr show $nic |egrep -w "inet6"|egrep -v "inet6 ::1|inet6 fe80::" > /tmp/ipv6info.log
            while read line;do
                SN=$(echo $line|awk '{print $2}'|awk -F"/" '{print $1}')
                if echo $SN | grep "inet6 240e:";then
                    TYPE=tel
                elif  echo $SN | grep "inet6 2408:8";then
                    TYPE=cnc
                elif echo $SN | grep "inet6 2409:8";then
                    TYPE=mob
                else
                    TYPE=other
                fi
                echo "${host_name}, Hardwre_type:IP, Manufacturer:${MFT}, SN:${SN}, Model:${MOD},Type:$TYPE, Form:$FORM, AssetStatus:$ASSET_STATUS"
                echo -e "${report_time}\x01${host_name}\x01IP\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${FORM}\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01${ASSET_STATUS}" >> $logfile           
                report_hwinfo "$host_name" "IP" "$MFT" "$SN" "$MOD" "$TYPE" "$FORM" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "$ASSET_STATUS"
            done < /tmp/ipv6info.log
        fi
    done
}
# 获取raid卡信息
get_raidcard() {
    FORM=$(lspci | grep LSI | grep -Eo "SAS[- 23]*[0-9]{2,}"|sed "s#[[:space:]]\+#_#g")
    if lspci | grep LSI| grep -q "SCSI controller";then
        TYPE=SAS
    elif lspci | grep LSI| grep -q "RAID";then
	TYPE=RAID
    else
	TYPE=NULL
    fi
    SN=NULL
    MFT=$(lspci -m | grep LSI | grep -E "SAS[- 23]*[0-9]{2,}"|awk 'BEGIN { FS="\"" ;}{print $8}')
    [ ! -z "$MFT" ] && MFT=$(echo $MFT |sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g' -e "s#[[:space:]]\+#_#g")|| MFT=NULL
    MOD=$(lspci -m | grep LSI | grep -E "SAS[- 23]*[0-9]{2,}"|awk 'BEGIN { FS="\"" ;}{print $10}')
    [ ! -z "$MOD" ] && MOD=$(echo $MOD |sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g' -e "s#[[:space:]]\+#_#g")|| MOD=NULL
    echo "${host_name}, Hardwre_type:RaidCard, Manufacturer:${MFT}, SN:NULL, Model:${MOD},Type:$TYPE, Form:$FORM, AssetStatus:$ASSET_STATUS"
    echo -e "${report_time}\x01${host_name}\x01RaidCard\x01${MFT}\x01${SN}\x01${MOD}\x01${TYPE}\x01${FORM}\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01UNKNOWN\x01${ASSET_STATUS}" >> $logfile
    report_hwinfo "$host_name" "RaidCard" "$MFT" "$SN" "$MOD" "$TYPE" "$FORM" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "UNKNOWN" "$ASSET_STATUS"
}
#####
if dmidecode -s system-manufacturer|grep -v "^#" |egrep -wo "Alibaba|Baidu|Vmware|ctyun";then
    MFT=$(dmidecode -s system-manufacturer|grep -v "^#" |egrep -wo "Huawei|Alibaba|Baidu||VMware|ctyun")
    MOD=$(cat /etc/hostname|awk -F"-" '{print $1"-"$2}')
    get_vm_hostinfo
    get_diskinfo
    get_vm_nicinfo
    get_vm_ipinfo
else
    get_hostinfo 
    get_cpuinfo
    get_memoryinfo
    get_diskinfo
    get_nicinfo
    get_raidcard
fi
#end
#


