首页 > 其他分享 >运维脚本备忘录

运维脚本备忘录

时间:2024-07-15 15:31:21浏览次数:14  
标签:脚本 grep 运维 etc echo 备忘录 --------------------- report awk

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 "巡检报告" [[email protected]]


标签:脚本,grep,运维,etc,echo,备忘录,---------------------,report,awk
From: https://www.cnblogs.com/mugetsukun/p/18303257

相关文章

  • SFTP一键添加脚本 (Duplicated 2024-07-15 12:39:10)
    創建腳本vimonekey_for_sftpuser.sh腳本內容#!/bin/bash#获取当前日期和时间CURRENT_DATE=$(date'+%Y年%m月%d日%H:%M:%S')echoecho"——————————————————————————————————————————————————————"echo"••......
  • SFTP一键添加脚本 (Duplicated 2024-07-15 12:39:10)
    創建腳本vimonekey_for_sftpuser.sh腳本內容#!/bin/bash#获取当前日期和时间CURRENT_DATE=$(date'+%Y年%m月%d日%H:%M:%S')echoecho"——————————————————————————————————————————————————————"echo"••......
  • 华为云DTSE助力虎彩鲜檬优化运维效率,助力迁移上云
    本文分享自华为云社区《虎彩鲜檬数字化产业变革,迁移上云,助力其打造智慧婚拍新纪元》,作者:HuaweiCloudDeveloper。来源:《华为云DTSE》第四期赋能云专刊在科技日新月异的今天,婚拍摄影行业正迎来一场前所未有的变革。虎彩鲜檬,一家深谙行业变革之道的婚拍摄影品牌,携手华为云DTSE团队......
  • 按键精灵,魔兽世界自动寻路实现脚本及思路
    软件umi截图插件,excel,按键精灵,神梦dll思路先移动一段距离通过计算斜率,换算成角度,判断最终转向脚本Function对接umiocr(图片路径)DimURL,JsonData,json,username,password,base64URL="http://192.168.1.40:1224/api/ocr"Import"SmHTTP.dll"SetSm......
  • 【网络运维的重要性】
    ......
  • 如何理解electron 的预加载脚本
    在Electron应用中,预加载脚本(PreloadScript)是一个非常重要的概念,它允许你在渲染进程(web页面)和主进程之间创建一个安全的桥梁。预加载脚本运行在Node.js环境中,但位于渲染进程的一个单独的上下文中,这意味着它可以访问Node.js的API,但无法直接访问DOM。这种设计使得预......
  • 运维系列:拒绝用户‘root‘@‘172.17.0.1‘访问在本地Docker容器中运行的mysql数据库
    拒绝用户'root'@'172.17.0.1‘访问在本地Docker容器中运行的mysql数据库拒绝用户'root'@'172.17.0.1‘访问在本地Docker容器中运行的mysql数据库问题:答案:拒绝用户’root’@'172.17.0.1‘访问在本地Docker容器中运行的mysql数据库问题:我正在尝试连接到在本地Dock......
  • 企业网络运维-给华为交换机配置sftp,浏览交换机文件并下载上传
    文章目录需求实验开户stelnet权限已完成stelnet账号下的sftp配置使用xshell-sftp访问需求浏览交换机文件并下载上传实验开户stelnet权限参考https://blog.csdn.net/xzzteach/article/details/140419150已完成stelnet账号下的sftp配置服务类型all包括stelnet......
  • 【Playwright+Python】手把手带你写一个自动化测试脚本
     如何使用代理方式打开网页 在playwright.chromium.launch()中传入proxy参数即可,示例代码如下:1、同步写法:fromplaywright.sync_apiimportsync_playwrightproxy={'server':'http:/127.0.0.1:8080'}defrun():withsync_playwright()asp:......
  • 【JavaScript脚本宇宙】解密六大Node.js消息队列库:选对工具,事半功倍
    从Bull到NSQ:探索Node.js消息队列库的全貌前言在现代软件开发中,消息队列是一种常见的通信模式,用于实现异步任务处理、解耦系统组件、以及实现可靠的事件驱动架构。Node.js作为一个流行的后端开发平台,有许多优秀的消息队列库可以供开发者选择和使用。本文将介绍六个流行的No......