運維指令碼備忘錄

Mugetsukun發表於2024-07-15

shell巡檢

#!/bin/bash
# Debian12.5

export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
source /etc/profile

if [ $(id -u) -gt 0 ]; then
  echo "Execute the script at root"
  exit 1
fi

# 獲取IP地址
IPADDR=$(hostname -I | awk '{print \$1}')

# 獲取Debian版本
if [ -f /etc/os-release ]; then
  debianVersion=$(grep '^VERSION=' /etc/os-release | cut -d'=' -f2 | tr -d '"')
  if [ -z "$debianVersion" ]; then
    echo "未能獲取Debian版本,請檢查/etc/os-release檔案格式。"
  else
    echo "Debian版本: $debianVersion"
  fi
else
  echo "/etc/os-release 檔案不存在,無法獲取版本資訊。"
fi



VERSION="1.0"

PROGPATH=$(dirname "$(dirname "$(realpath "\$0")")")
if [ -f "$PROGPATH" ]; then
  PROGPATH="."
fi

LOGPATH="$PROGPATH/log"
if [ ! -e "$LOGPATH" ]; then
  mkdir -p "$LOGPATH"
fi

RESULTFILE="$LOGPATH/HostDailyCheck-$IPADDR-$(date +%Y%m%d).txt"

#echo "Debian Version: $debianVersion"
#echo "Program Path: $PROGPATH"
#echo "Log Path: $LOGPATH"
#echo "Result File Path: $RESULTFILE"

report_DateTime="" #日期
report_Hostname="" #主機名
report_OSRelease="" #發行版本
report_Kernel="" #核心
report_Language="" #語言
report_LastReboot="" #最近啟動時間
report_Uptime="" #執行時間(天)
report_CPUs="" #CPU數量
report_CPUType="" #CPU型別
report_Arch="" #CPU架構
report_MemTotal="" #記憶體總容量(MB)
report_MemFree="" #記憶體剩餘(MB)
report_MemUsedPercent="" #記憶體使用率%
report_DiskTotal="" #硬碟總容量(GB)
report_DiskFree="" #硬碟剩餘(GB)
report_DiskUsedPercent="" #硬碟使用率%
report_InodeTotal="" #Inode總量
report_InodeFree="" #Inode剩餘
report_InodeUsedPercent="" #Inode使用率
report_IP="" #IP地址
report_MAC="" #MAC地址
report_Gateway="" #預設閘道器
report_DNS="" #DNS
report_Listen="" #監聽
report_Firewall="" #防火牆
report_USERs="" #使用者
report_USEREmptyPassword="" #空密碼使用者
report_USERTheSameUID="" #相同ID的使用者 
report_PasswordExpiry="" #密碼過期(天)
report_RootUser="" #root使用者
report_Sudoers="" #sudo授權
report_SSHAuthorized="" #SSH信任主機
report_SSHDProtocolVersion="" #SSH協議版本
report_SSHDPermitRootLogin="" #允許root遠端登入
report_DefunctProsess="" #殭屍程序數量
report_SelfInitiatedService="" #自啟動服務數量
report_SelfInitiatedProgram="" #自啟動程式數量
report_RuningService="" #執行中服務數
report_Crontab="" #計劃任務數
report_Syslog="" #日誌服務
report_SNMP="" #SNMP
report_NTP="" #NTP
report_JDK="" #JDK版本
function version(){
echo ""
echo ""
echo "Script :Version $VERSION"
}

function getCpuStatus(){
  echo ""
  echo ""
  echo "--------------------- CPU Check ---------------------"
  Physical_CPUs=$(grep "physical id" /proc/cpuinfo | sort | uniq | wc -l)
  Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l)
  CPU_Kernels=$(grep "cpu cores" /proc/cpuinfo | uniq | awk -F ': ' '{print \$2}')
  CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print \$2}' | sort | uniq)
  CPU_Arch=$(uname -m)
  echo "物理CPU個數: $Physical_CPUs"
  echo "邏輯CPU個數: $Virt_CPUs"
  echo "每CPU核心數: $CPU_Kernels"
  echo "CPU型號: $CPU_Type"
  echo "CPU架構: $CPU_Arch"
  
  report_CPUs=$Virt_CPUs # CPU數量
  report_CPUType=$CPU_Type # CPU型別
  report_Arch=$CPU_Arch # CPU架構
}

function getMemStatus(){
  echo ""
  echo ""
  echo "--------------------- Memory Check ---------------------"
  free -h
  MemTotal=$(grep MemTotal /proc/meminfo | awk '{print \$2}')
  MemFree=$(grep MemFree /proc/meminfo | awk '{print \$2}')
  let MemUsed=MemTotal-MemFree
  MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}")
  report_MemTotal="$((MemTotal/1024))MB"
  report_MemFree="$((MemFree/1024))MB"
  report_MemUsedPercent="$MemPercent%"
}

function getDiskStatus(){
  echo ""
  echo ""
  echo "--------------------- Disk Check ---------------------"
  df -hiP | sed 's/Mounted on/Mounted/'> /tmp/inode
  df -hTP | sed 's/Mounted on/Mounted/'> /tmp/disk 
  join /tmp/disk /tmp/inode | awk '{print \$1,\$2,"|",\$3,\$4,\$5,\$6,"|",\$8,\$9,\$10,\$11,"|",\$12}'| column -t

  diskdata=$(df -TP | sed '1d' | awk '\$2!="tmpfs"{print}') #KB
  disktotal=$(echo "$diskdata" | awk '{total+=\$3}END{print total}') #KB
  diskused=$(echo "$diskdata" | awk '{total+=\$4}END{print total}') #KB
  diskfree=$((disktotal-diskused)) #KB
  diskusedpercent=$(echo $disktotal $diskused | awk '{if(\$1==0){printf 100}else{printf "%.2f",\$2*100/\$1}}') 
  inodedata=$(df -iTP | sed '1d' | awk '\$2!="tmpfs"{print}')
  inodetotal=$(echo "$inodedata" | awk '{total+=\$3}END{print total}')
  inodeused=$(echo "$inodedata" | awk '{total+=\$4}END{print total}')
  inodefree=$((inodetotal-inodeused))
  inodeusedpercent=$(echo $inodetotal $inodeused | awk '{if(\$1==0){printf 100}else{printf "%.2f",\$2*100/\$1}}')
  report_DiskTotal=$((disktotal/1024/1024))"GB" #硬碟總容量(GB)
  report_DiskFree=$((diskfree/1024/1024))"GB" #硬碟剩餘(GB)
  report_DiskUsedPercent="$diskusedpercent""%" #硬碟使用率%
  report_InodeTotal=$((inodetotal/1000))"K" #Inode總量
  report_InodeFree=$((inodefree/1000))"K" #Inode剩餘
  report_InodeUsedPercent="$inodeusedpercent""%" #Inode使用率%

  rm -f /tmp/disk /tmp/inode

}

function getSystemStatus(){
  echo ""
  echo ""
  echo "--------------------- System Check ---------------------"
  if [ -e /etc/sysconfig/i18n ]; then
    default_LANG="$(grep "LANG=" /etc/sysconfig/i18n | grep -v "^#" | awk -F '"' '{print \$2}')"
  else
    default_LANG=$LANG
  fi
  export LANG="en_US.UTF-8"
  Release=$(lsb_release -d | cut -f2)
  Kernel=$(uname -r)
  OS=$(uname -o)
  Hostname=$(uname -n)
  LastReboot=$(who -b | awk '{print \$3,\$4}')
  uptime=$(uptime | sed 's/.*up \([^,]*\), .*/\1/')
  echo " 系統:$OS"
  echo " 發行版本:$Release"
  echo " 核心:$Kernel"
  echo " 主機名:$Hostname"
  echo " 語言/編碼:$default_LANG"
  echo " 當前時間:$(date +'%F %T')"
  echo " 最後啟動:$LastReboot"
  echo " 執行時間:$uptime"
  # 報表資訊
  report_DateTime=$(date +"%F %T") #日期
  report_Hostname="$Hostname" #主機名
  report_OSRelease="$Release" #發行版本
  report_Kernel="$Kernel" #核心
  report_Language="$default_LANG" #語言/編碼
  report_LastReboot="$LastReboot" #最近啟動時間
  report_Uptime="$uptime" #執行時間(天)
  export LANG="$default_LANG"
}

function getServiceStatus(){
  echo ""
  echo ""
  echo "--------------------- Service Check ---------------------"
  echo ""
  
  conf=$(systemctl list-unit-files --type=service --state=enabled --no-pager)
  process=$(systemctl list-units --type=service --state=running --no-pager)
  report_SelfInitiatedService="$(echo "$conf" | grep ".service" | wc -l)" #自啟動服務數量
  report_RuningService="$(echo "$process" | grep ".service" | wc -l)" #執行中服務數量
  
  echo "服務配置"
  echo "--------"
  echo "$conf" | column -t
  echo ""
  echo "正在執行的服務"
  echo "--------------"
  echo "$process"
}


function getAutoStartStatus(){
  echo ""
  echo ""
  echo "--------------------- AutoStart Check ---------------------"
  conf=$(grep -v "^#" /etc/rc.d/rc.local | sed '/^$/d')
  echo "$conf"

  report_SelfInitiatedProgram="$(echo "$conf" | wc -l)" #自啟動程式數量
}

function getLoginStatus(){
  echo ""
  echo ""
  echo "--------------------- Login Check ---------------------"
  last | head
}

function getNetworkStatus(){
  echo ""
  echo ""
  echo "--------------------- Network Check ---------------------"
  
  for iface in $(ip -o link show | awk -F': ' '{print \$2}'); do
    if [[ $iface != "lo" ]]; then
      ip addr show $iface | grep -E "inet " | awk '{print \$2}' | tr '\n' ' '
      echo ""
    fi
  done

GATEWAY=$(ip route | grep default | awk '{print $3}')

DNS=$(grep nameserver /etc/resolv.conf| grep -v "#" | awk '{print $2}' | tr '\n' ',' | sed 's/,$//')

echo ""
echo "閘道器:$GATEWAY "
echo " DNS:$DNS"


IP=$(ip -f inet addr | grep -v 127.0.0.1 | grep inet | awk '{print $NF,$2}' | tr '\n' ',' | sed 's/,$//')
MAC=$(ip link | grep -v "LOOPBACK\|loopback" | awk '{print $2}' | sed 'N;s/\n//' | tr '\n' ',' | sed 's/,$//')
report_IP="$IP" #IP地址
report_MAC=$MAC #MAC地址
report_Gateway="$GATEWAY" #預設閘道器
report_DNS="$DNS" #DNS
}

function getListenStatus(){
  echo ""
  echo ""
  echo "--------------------- Listen Check ---------------------"
  
  TCPListen=$(ss -ntul | column -t)
  echo "$TCPListen"
  
  
  report_Listen="$(echo "$TCPListen" | sed '1d' | awk '/tcp/ {print \$5}' | awk -F: '{print $NF}' | sort | uniq | wc -l)"
}

function getCronStatus(){
  echo ""
  echo ""
  echo "--------------------- Crontab Check ---------------------"
  
  Crontab=0
  for shell in $(grep -v "/sbin/nologin" /etc/shells); do
    for user in $(grep "$shell" /etc/passwd | awk -F: '{print \$1}'); do
      crontab -l -u $user >/dev/null 2>&1
      status=$?
      if [ $status -eq 0 ]; then
        echo "$user"
        echo "--------"
        crontab -l -u $user
        let Crontab=Crontab+$(crontab -l -u $user | wc -l)
        echo ""
      fi
    done
  done
  
  find /etc/cron* -type f | xargs -i ls -l {} | column -t
  let Crontab=Crontab+$(find /etc/cron* -type f | wc -l)
  
  report_Crontab="$Crontab" # 計劃任務數
}

function getHowLongAgo(){
  datetime="$*"
  [ -z "$datetime" ] && echo "Wrong Parameter Value :getHowLongAgo() $*"
  
  Timestamp=$(date +%s -d "$datetime") # 轉化為時間戳
  Now_Timestamp=$(date +%s)
  Difference_Timestamp=$(($Now_Timestamp-$Timestamp))
  
  days=0; hours=0; minutes=0;
  sec_in_day=$((60*60*24));
  sec_in_hour=$((60*60));
  sec_in_minute=60
  
  while (( $(($Difference_Timestamp-$sec_in_day)) > 1 )); do
    let Difference_Timestamp=Difference_Timestamp-sec_in_day
    let days++
  done
  
  while (( $(($Difference_Timestamp-$sec_in_hour)) > 1 )); do
    let Difference_Timestamp=Difference_Timestamp-sec_in_hour
    let hours++
  done
  
  echo "$days 天 $hours 小時前"
}

function getUserLastLogin(){
  username=\$1
  : ${username:="$(whoami)"}
  
  thisYear=$(date +%Y)
  oldestYear=$(last | tail -n1 | awk '{print $NF}')

  while (( $thisYear >= $oldestYear )); do
    loginBeforeToday=$(last $username | grep $username | wc -l)
    loginBeforeNewYearsDayOfThisYear=$(last $username -t $thisYear"0101000000" | grep $username | wc -l)
    
    if [ $loginBeforeToday -eq 0 ]; then
      echo "從未登入過"
      break
    elif [ $loginBeforeToday -gt $loginBeforeNewYearsDayOfThisYear ]; then
      lastDateTime=$(last -i $username | head -n1 | awk '{for(i=4;i<(NF-2);i++)printf"%s ",$i}')" $thisYear"
      lastDateTime=$(date "+%Y-%m-%d %H:%M:%S" -d "$lastDateTime")
      echo "$lastDateTime"
      break
    else
      thisYear=$((thisYear-1))
    fi
  done
}

function getUserStatus(){
  echo ""
  echo ""
  echo "--------------------- User Check ---------------------"

  # /etc/passwd 最後修改時間
  pwdfile="$(cat /etc/passwd)"
  Modify=$(stat /etc/passwd | grep Modify | tr '.' ' ' | awk '{print \$2,\$3}')

  echo "/etc/passwd 最後修改時間:$Modify ($(getHowLongAgo $Modify))"
  echo ""
  
  echo "特權使用者"
  echo "--------"
  RootUser=""
  for user in $(echo "$pwdfile" | awk -F: '{print \$1}'); do
    if [ $(id -u $user) -eq 0 ]; then
      echo "$user"
      RootUser="$RootUser,$user"
    fi
  done
  echo ""
  
  echo "使用者列表"
  echo "--------"
  USERs=0
  echo "$(
    echo "使用者名稱 UID GID HOME SHELL 最後一次登入"
    for shell in $(grep -v "/sbin/nologin" /etc/shells); do
      for username in $(grep "$shell" /etc/passwd | awk -F: '{print \$1}'); do
        userLastLogin="$(getUserLastLogin $username)"
        echo "$pwdfile" | grep -w "$username" | grep -w "$shell" | awk -F: -v lastlogin="$(echo "$userLastLogin" | tr ' ' '_')" '{print \$1,\$3,\$4,\$6,\$7,lastlogin}'
      done
      let USERs=USERs+$(echo "$pwdfile" | grep "$shell" | wc -l)
    done
  )" | column -t
  echo ""
  
  echo "空密碼使用者"
  echo "----------"
  USEREmptyPassword=""
  for shell in $(grep -v "/sbin/nologin" /etc/shells); do
    for user in $(echo "$pwdfile" | grep "$shell" | cut -d: -f1); do
      r=$(awk -F: '\$2==""{print \$1}' /etc/shadow | grep -w $user)
      if [ ! -z "$r" ]; then
        echo $r
        USEREmptyPassword="$USEREmptyPassword,$r"
      fi
    done 
  done
  
  echo ""
  echo "相同ID的使用者"
  echo "------------"
  USERTheSameUID=""
  UIDs=$(cut -d: -f3 /etc/passwd | sort | uniq -c | awk '\$1>1{print \$2}')
  for uid in $UIDs; do
    echo -n "$uid"
    USERTheSameUID="$uid"
    r=$(awk -F: 'ORS="";\$3=='"$uid"'{print ":",\$1}' /etc/passwd)
    echo "$r"
    echo ""
    USERTheSameUID="$USERTheSameUID $r,"
  done

  report_USERs="$USERs" # 使用者數量
  report_USEREmptyPassword=$(echo $USEREmptyPassword | sed 's/^,//') 
  report_USERTheSameUID=$(echo $USERTheSameUID | sed 's/,$//') 
  report_RootUser=$(echo $RootUser | sed 's/^,//') # 特權使用者
}

function getPasswordStatus {
  echo ""
  echo ""
  echo "--------------------- Password Check ---------------------"
  pwdfile="$(cat /etc/passwd)"
  
  echo ""
  echo "密碼過期檢查"
  echo "------------"
  result=""
  
  for shell in $(grep -v "/sbin/nologin" /etc/shells); do
    for user in $(echo "$pwdfile" | grep "$shell" | cut -d: -f1); do
      get_expiry_date=$(/usr/bin/chage -l $user | grep 'Password expires' | cut -d: -f2)
      
      if [[ "$get_expiry_date" == ' never' || "$get_expiry_date" == 'never' ]]; then
        printf "%-15s 永不過期\n" $user
        result="$result,$user:never"
      else
        password_expiry_date=$(date -d "$get_expiry_date" "+%s")
        current_date=$(date "+%s")
        diff=$(($password_expiry_date - $current_date))
        DAYS=$(($diff / (60 * 60 * 24)))
        printf "%-15s %s天后過期\n" $user $DAYS
        result="$result,$user:$DAYS days"
      fi
    done
  done
  
  report_PasswordExpiry=$(echo $result | sed 's/^,//')

  echo ""
  echo "密碼策略檢查"
  echo "------------"
  grep -v "#" /etc/login.defs | grep -E "PASS_MAX_DAYS|PASS_MIN_DAYS|PASS_MIN_LEN|PASS_WARN_AGE"
}

function getSudoersStatus(){
  echo ""
  echo ""
  echo "--------------------- Sudoers Check ---------------------"
  conf=$(grep -v "^#" /etc/sudoers | grep -v "^Defaults" | sed '/^$/d')
  echo "$conf"
  echo ""

  report_Sudoers="$(echo "$conf" | wc -l)"
}

function getInstalledStatus(){
  echo ""
  echo ""
  echo "--------------------- Installed Check ---------------------"
  apt-get list --installed | awk -F/ '{print \$1}' | column -t | head -n 10 
}

function getProcessStatus(){
  echo ""
  echo ""
  echo "--------------------- Process Check ---------------------"
  
  # 檢查殭屍程序
  if [ $(ps -ef | grep defunct | grep -v grep | wc -l) -ge 1 ]; then
    echo ""
    echo "殭屍程序"
    echo "--------"
    ps -ef | head -n1
    ps -ef | grep defunct | grep -v grep
  fi
  
  echo ""
  echo "記憶體佔用TOP10"
  echo "-------------"
  echo -e "PID\t%MEM\tRSS\tCOMMAND"
  ps aux --sort=-%mem | awk 'NR==1{print \$2, \$4, \$6, \$11} NR>1{print \$2, \$4, \$6, \$11}' | head -n 11 | column -t
  
  echo ""
  echo "CPU佔用TOP10"
  echo "------------"
  top -b -n1 | head -17 | tail -11
  

  report_DefunctProsess="$(ps -ef | grep defunct | grep -v grep | wc -l)"
}

function getJDKStatus(){
  echo ""
  echo ""
  echo "--------------------- JDK Check ---------------------"
  if command -v java &> /dev/null; then
    java -version 2>&1
  else
    echo "Java 未安裝"
  fi
  echo "JAVA_HOME=\"$JAVA_HOME\""
  
  if command -v java &> /dev/null; then
    report_JDK="$(java -version 2>&1 | grep version | awk '{print \$1,\$3}' | tr -d '"')"
  else
    report_JDK="Java 未安裝"
  fi
}

function getSyslogStatus(){
  echo ""
  echo ""
  echo "--------------------- Syslog Check ---------------------"
  if command -v rsyslogd &> /dev/null; then
    echo "服務狀態:$(systemctl is-active rsyslog)"
  else
    echo "rsyslog 未安裝"
  fi
  echo ""
  echo "/etc/rsyslog.conf"
  echo "-----------------"
  if [ -f /etc/rsyslog.conf ]; then
    cat /etc/rsyslog.conf 2>/dev/null | grep -v "^#" | grep -v "^\\$" | sed '/^$/d' | column -t
  else
    echo "配置檔案 /etc/rsyslog.conf 不存在"
  fi

  if command -v rsyslogd &> /dev/null; then
    report_Syslog="$(systemctl is-active rsyslog)"
  else
    report_Syslog="rsyslog 未安裝"
  fi
}

function getFirewallStatus(){
  echo ""
  echo ""
  echo "--------------------- Firewall Check ---------------------"
  
  if command -v iptables &> /dev/null; then
    if systemctl is-active --quiet iptables; then
      s="active"
    else
      s="inactive"
    fi
  else
    s="iptables未安裝"
  fi
  echo "iptables: $s"
  echo ""

  if [ -e /etc/iptables/rules.v4 ]; then
    echo "/etc/iptables/rules.v4"
    echo "-----------------------"
    cat /etc/iptables/rules.v4 2>/dev/null
  else
    echo "/etc/iptables/rules.v4 檔案不存在或未配置"
  fi

  report_Firewall="$s"
}


function getSNMPStatus(){
  echo ""
  echo ""
  echo "--------------------- SNMP Check ---------------------"
  status="$(getState snmpd)"
  echo "服務狀態:$status"
  echo ""
  if [ -e /etc/snmp/snmpd.conf ]; then
    echo "/etc/snmp/snmpd.conf"
    echo "--------------------"
    cat /etc/snmp/snmpd.conf 2>/dev/null | grep -v "^#" | sed '/^$/d'
  else
    echo "/etc/snmp/snmpd.conf 檔案不存在"
  fi

  report_SNMP="$status"
}

function getState(){
  # 直接使用 systemctl 來獲取服務狀態
  local service=\$1
  if command -v systemctl &> /dev/null; then
    if systemctl list-units --type=service --all | grep -q "$service.service"; then
      systemctl is-active "$service" 2>&1
    else
      echo "unknown"
    fi
  else
    echo "systemctl not found"
  fi
}

function getSSHStatus(){
  # SSHD服務狀態,配置,受信任主機等
  echo ""
  echo ""
  echo "--------------------- SSH Check ---------------------"

  pwdfile="$(cat /etc/passwd)"
  echo "服務狀態:$(getState sshd)"
  Protocol_Version=$(cat /etc/ssh/sshd_config | grep -i Protocol | awk '{print \$2}')
  echo "SSH協議版本:$Protocol_Version"
  echo ""
  echo "信任主機"
  echo "--------"
  authorized=0
  for user in $(echo "$pwdfile" | grep /bin/bash | awk -F: '{print \$1}'); do
    authorize_file=$(echo "$pwdfile" | grep -w $user | awk -F: '{printf \$6"/.ssh/authorized_keys"}')
    authorized_host=$(cat $authorize_file 2>/dev/null | awk '{print \$3}' | tr '\n' ',' | sed 's/,$//')
    if [ ! -z "$authorized_host" ]; then
      echo "$user 授權 \"$authorized_host\" 無密碼訪問"
    fi
    authorized=$((authorized + $(cat $authorize_file 2>/dev/null | awk '{print \$3}' | wc -l)))
  done

  echo ""
  echo "是否允許ROOT遠端登入"
  echo "--------------------"
  config=$(cat /etc/ssh/sshd_config | grep -i PermitRootLogin)
  firstChar=${config:0:1}
  if [ "$firstChar" == "#" ]; then
    PermitRootLogin="yes" # 預設是允許ROOT遠端登入的
  else
    PermitRootLogin=$(echo "$config" | awk '{print \$2}')
  fi
  echo "PermitRootLogin $PermitRootLogin"

  echo ""
  echo "/etc/ssh/sshd_config"
  echo "--------------------"
  cat /etc/ssh/sshd_config | grep -v "^#" | sed '/^$/d'


  report_SSHAuthorized="$authorized" # SSH信任主機
  report_SSHDProtocolVersion="$Protocol_Version" # SSH協議版本
  report_SSHDPermitRootLogin="$PermitRootLogin" # 允許root遠端登入
}

function getNTPStatus(){
  echo ""
  echo ""
  echo "--------------------- NTP Check ---------------------"

  if command -v ntpd &> /dev/null; then
    echo "服務狀態:$(getState ntp)"
    echo ""
  elif command -v timedatectl &> /dev/null; then
    echo "NTP同步狀態:$(timedatectl status | grep "NTP synchronized")"
  fi

  if [ -e /etc/ntp.conf ]; then
    echo "/etc/ntp.conf"
    echo "-------------"
    cat /etc/ntp.conf 2>/dev/null | grep -v "^#" | sed '/^$/d'
  fi

  if command -v ntpd &> /dev/null; then
    report_NTP="$(getState ntp)"
  elif command -v timedatectl &> /dev/null; then
    report_NTP="$(timedatectl status | grep "NTP synchronized")"
  else
    report_NTP="NTP未安裝或未啟用"
  fi
}


function uploadHostDailyCheckReport(){
  json=$(cat <<EOF
{
  "DateTime": "$report_DateTime",
  "Hostname": "$report_Hostname",
  "OSRelease": "$report_OSRelease",
  "Kernel": "$report_Kernel",
  "Language": "$report_Language",
  "LastReboot": "$report_LastReboot",
  "Uptime": "$report_Uptime",
  "CPUs": "$report_CPUs",
  "CPUType": "$report_CPUType",
  "Arch": "$report_Arch",
  "MemTotal": "$report_MemTotal",
  "MemFree": "$report_MemFree",
  "MemUsedPercent": "$report_MemUsedPercent",
  "DiskTotal": "$report_DiskTotal",
  "DiskFree": "$report_DiskFree",
  "DiskUsedPercent": "$report_DiskUsedPercent",
  "InodeTotal": "$report_InodeTotal",
  "InodeFree": "$report_InodeFree",
  "InodeUsedPercent": "$report_InodeUsedPercent",
  "IP": "$report_IP",
  "MAC": "$report_MAC",
  "Gateway": "$report_Gateway",
  "DNS": "$report_DNS",
  "Listen": "$report_Listen",
  "Firewall": "$report_Firewall",
  "USERs": "$report_USERs",
  "USEREmptyPassword": "$report_USEREmptyPassword",
  "USERTheSameUID": "$report_USERTheSameUID",
  "PasswordExpiry": "$report_PasswordExpiry",
  "RootUser": "$report_RootUser",
  "Sudoers": "$report_Sudoers",
  "SSHAuthorized": "$report_SSHAuthorized",
  "SSHDProtocolVersion": "$report_SSHDProtocolVersion",
  "SSHDPermitRootLogin": "$report_SSHDPermitRootLogin",
  "DefunctProsess": "$report_DefunctProsess",
  "SelfInitiatedService": "$report_SelfInitiatedService",
  "SelfInitiatedProgram": "$report_SelfInitiatedProgram",
  "RuningService": "$report_RuningService",
  "Crontab": "$report_Crontab",
  "Syslog": "$report_Syslog",
  "SNMP": "$report_SNMP",
  "NTP": "$report_NTP",
  "JDK": "$report_JDK"
}
EOF
)

  # 傳送JSON資料到API
  curl -s -H "Content-type: application/json" -X POST -d "$json" "$uploadHostDailyCheckReportApi"
}

function getchage_file_24h() {
  echo "--------------------- File Check ---------------------"

  line="-------------------------------------------"

  check2=$(find / -type f -name '*.sh' -mtime -1 2>/dev/null)
  check21=$(find / -type f -name '*.asp' -mtime -1 2>/dev/null)
  check22=$(find / -type f -name '*.php' -mtime -1 2>/dev/null)
  check23=$(find / -type f -name '*.aspx' -mtime -1 2>/dev/null)
  check24=$(find / -type f -name '*.jsp' -mtime -1 2>/dev/null)
  check25=$(find / -type f -name '*.html' -mtime -1 2>/dev/null)
  check26=$(find / -type f -name '*.htm' -mtime -1 2>/dev/null)
  check9=$(find / -name core -exec ls -l {} \; 2>/dev/null)
  check10=$(cat /etc/crontab 2>/dev/null)
  check12=$(ls -alt /usr/bin | head -10 2>/dev/null)

  cat <<EOF

# View all modified files returned within the last 24 hours 

${check2}
${line}
${check21}
${line}
${check22}
${line}
${check23}
${line}
${check24}
${line}
${check25}
${line}
${check26}

#Check the integrity of the timing file

${line}
${check10}

#Check whether the system command is replaced

${line}
${check12}
EOF
}

function check() {
  version
  getSystemStatus
  getCpuStatus
  getMemStatus
  getDiskStatus
  getNetworkStatus
  getListenStatus
  getProcessStatus
  getServiceStatus
  getAutoStartStatus
  getLoginStatus
  getCronStatus
  getUserStatus
  getPasswordStatus
  getSudoersStatus
  getJDKStatus
  getFirewallStatus
  getSSHStatus
  getSyslogStatus
  getSNMPStatus
  getNTPStatus
  getInstalledStatus
  getchage_file_24h
}

check > "$RESULTFILE"
echo "檢查結果已儲存到:$RESULTFILE"
echo -e "\n$(date "+%Y-%m-%d %H:%M:%S") 巡檢報告" >> "$RESULTFILE"

echo "傳送巡檢報告:"
# mail -a $RESULTFILE -s "巡檢報告" [your-email@example.com]


相關文章