当前位置:网站首页>Tencent cloud ceontos server patrol script

Tencent cloud ceontos server patrol script

2022-06-24 05:42:00 User 8639654

#!/bin/bash
# Parameters are defined 
date=`date +"%Y-%m-%d-%H:%M:%S"`
centosVersion=$(awk '{print $(NF-1)}' /etc/redhat-release)
VERSION=`date +%F`
# Log correlation 
LOGPATH="/tmp/awr"
[ -e $LOGPATH ] || mkdir -p $LOGPATH
RESULTFILE="$LOGPATH/HostCheck-`hostname`-`date +%Y%m%d`.txt"

# Call function library 
[ -f /etc/init.d/functions ] && source /etc/init.d/functions
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
source /etc/profile


#root User execution script 
[ $(id -u) -gt 0 ] && echo " Please use root The user executes the script !" && exit 1

 
function version(){
    echo ""
    echo ""
    echo "[${date}] >>> `hostname -s`  Host patrol inspection "
}


function getSystemStatus(){
    echo ""
    echo -e "\033[33m**************************************************** System check ****************************************************\033[0m"
    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=$(cat /etc/redhat-release 2>/dev/null)
    Kernel=$(uname -r)
    OS=$(uname -o)
    Hostname=$(uname -n)
    SELinux=$(/usr/sbin/sestatus | grep "SELinux status: " | awk '{print $3}')
    LastReboot=$(who -b | awk '{print $3,$4}')
    uptime=$(uptime | sed 's/.*up \([^,]*\), .*/\1/')
    echo "      System :$OS"
    echo "  Release version :$Release"
    echo "      kernel :$Kernel"
    echo "    Host name :$Hostname"
    echo "  SELinux:$SELinux"
    echo " Language / code :$default_LANG"
    echo "  current time :$(date +'%F %T')"
    echo "  Finally start :$LastReboot"
    echo "  The elapsed time :$uptime"
    export LANG="$default_LANG"
}

function getCpuStatus(){
    echo ""
    echo -e "\033[33m****************************************************CPU Check *****************************************************\033[0m"
    Physical_CPUs=$(grep "physical id" /proc/cpuinfo| sort | uniq | wc -l)
    Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l)
    CPU_Kernels=$(grep "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 " Physics CPU Number :$Physical_CPUs"
    echo " Logic CPU Number :$Virt_CPUs"
    echo " Every time CPU The core number :$CPU_Kernels"
    echo "    CPU model :$CPU_Type"
    echo "    CPU framework :$CPU_Arch"
}

function getMemStatus(){
    echo ""
    echo  -e "\033[33m************************************************** Memory check *****************************************************\033[0m"
    if [[ $centosVersion < 7 ]];then
        free -mo
    else
        free -h
    fi
    # Report information 
    MemTotal=$(grep MemTotal /proc/meminfo| awk '{print $2}')  #KB
    MemFree=$(grep MemFree /proc/meminfo| awk '{print $2}')    #KB
    let MemUsed=MemTotal-MemFree
    MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}") 
}

function getDiskStatus(){
    echo ""
    echo -e "\033[33m************************************************** Disk check ******************************************************\033[0m"
    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
    # Report information 
    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}}')
}



function get_resource(){
    echo ""
    echo -e "\033[33m************************************************** Resource consumption statistics **************************************************\033[0m"

    echo -e "\033[36m************* Bandwidth resource consumption statistics *************\033[0m"
	# Use an array to store the network card name 
    nic=(`ifconfig | grep ^[a-z] | grep -vE 'lo|docker0'| awk -F: '{print $1}'`)
	time=`date "+%Y-%m-%d %k:%M"`
	num=0
	
    for ((i=0;i<${#nic[@]};i++))
	do
	   # Cycle five times , Avoid seeing accidental data 
       while (( $num<5 ))
	   do
	     rx_before=$(cat /proc/net/dev | grep '${nic[$i]}' | tr : " " | awk '{print $2}')
         tx_before=$(cat /proc/net/dev | grep '${nic[$i]}' | tr : " " | awk '{print $10}')
		 sleep 2
		 # use sed Get the first 7 Column , Reuse awk For the first 2 Column , Again cut cutting , From 7 In the end , That is, only the digital part of network card traffic is cut 
         rx_after=$(cat /proc/net/dev | grep '${nic[$i]}' | tr : " " | awk '{print $2}')
         tx_after=$(cat /proc/net/dev | grep '${nic[$i]}' | tr : " " | awk '{print $10}')
		 # Note the difference in the following intercept 2 The cumulative sum of two seconds is sent bytes( That is, the transmitted and received bits are accumulated )
         rx_result=$[(rx_after-rx_before)/1024/1024/2*8]
         tx_result=$[(tx_after-tx_before)/1024/1024/2*8]
		 echo  "$time Now_In_Speed: $rx_result Mbps  Now_OUt_Speed: $tx_result Mbps" >> /tmp/network.txt
		 let "num++"
	   done
	   # Pay attention to the following grep hinder $time Variables should be enclosed in double quotation marks 
       rx_result=$(cat /tmp/network.txt|grep "$time"|awk '{In+=$4}END{print In}')
       tx_result=$(cat /tmp/network.txt|grep "$time"|awk '{Out+=$7}END{print Out}')
       In_Speed=$(echo "scale=2;$rx_result/5"|bc)
       Out_Speed=$(echo "scale=2;$tx_result/5"|bc)
       echo -e  "\033[32m In_Speed_average: $In_Speed Mbps Out_Speed_average: $Out_Speed Mbps! \033[0m" 
	done


    echo -e "\033[36m*************CPU Resource consumption statistics *************\033[0m"

    # Use vmstat 1 5 Command Statistics 5 Seconds of usage , Calculate the usage per second 
	total=`vmstat 1 5|awk '{x+=$13;y+=$14}END{print x+y}'`
	cpu_average=$(echo "scale=2;$total/5"|bc)
	
	# Judge CPU Usage rate ( Compare floating point numbers with integers )
	if [ `echo "${cpu_average} > 70" | bc` -eq 1 ];then
	    echo -e  "\033[31m Total CPU is already use: ${cpu_average}%, Please handle in time !\033[0m" 
    else 
	    echo -e  "\033[32m Total CPU is already use: ${cpu_average}%! \033[0m" 
    fi


    echo -e "\033[36m************* Disk resource consumption statistics *************\033[0m"
    # Disk usage ( Be careful : Need to use sed You can only accumulate after formatting )
    disk_used=$(df -m | sed '1d;/ /!N;s/\n//;s/ \+/ /;' | awk '{used+=$3} END{print used}')
    disk_totalSpace=$(df -m | sed '1d;/ /!N;s/\n//;s/ \+/ /;' | awk '{totalSpace+=$2} END{print totalSpace}')
    disk_all=$(echo "scale=4;$disk_used/$disk_totalSpace" | bc)
    disk_percent1=$(echo $disk_all | cut -c 2-3)
    disk_percent2=$(echo $disk_all | cut -c 4-5)
    disk_warning=`df -m | sed '1d;/ /!N;s/\n//;s/ \+/ /;' | awk '{if ($5>85) print $6 " Directory usage :" $5;} '`
    
	echo -e  "\033[32m Total disk has used: $disk_percent1.$disk_percent2% \033[0m" 
    #echo -e "\t\t.."  Means line break 
	if [ -n  "$disk_warning" ];then
	    echo -e "\033[31m${disk_warning} \n [Error] The utilization rate of the above directories exceeds 85%, Please handle in time !\033[0m" 
	fi
	
    echo -e "\033[36m************* Memory resource consumption statistics *************\033[0m"
	
    # Get the total memory of the system 
	memery_all=$(free -m | awk 'NR==2' | awk '{print $2}')
	# Get occupied memory ( operating system   angle )
	system_memery_used=$(free -m | awk 'NR==2' | awk '{print $3}')
	# get buffer、cache Take up memory , When the memory is insufficient, it will be recycled in time , So these two parts can be used to calculate the available memory 
	buffer_used=$(free -m | awk 'NR==2' | awk '{print $6}')
	cache_used=$(free -m | awk 'NR==2' | awk '{print $7}')
	# Get used memory , So this part can be used to calculate the available memory , Pay attention to the calculation method 
	actual_used_all=$[memery_all-(free+buffer_used+cache_used)]
	# Get the actual memory used 
	actual_used_all=`expr $memery_all - $free + $buffer_used + $cache_used `
    memery_percent=$(echo "scale=4;$system_memery_used / $memery_all" | bc)
    memery_percent2=$(echo "scale=4; $actual_used_all / $memery_all" | bc)
    percent_part1=$(echo $memery_percent | cut -c 2-3)
    percent_part2=$(echo $memery_percent | cut -c 4-5)
    percent_part11=$(echo $memery_percent2 | cut -c 2-3)
    percent_part22=$(echo $memery_percent2 | cut -c 4-5)
    
	# Get occupied memory ( Operating system perspective )
    echo -e "\033[32m system memery is already use: $percent_part1.$percent_part2% \033[0m"
    # Get the actual memory usage 
    echo -e "\033[32m actual memery is already use: $percent_part11.$percent_part22% \033[0m"
    echo -e "\033[32m buffer is already used : $buffer_used M \033[0m"
    echo -e "\033[32m cache is already used : $cache_used M \033[0m"
}



function getServiceStatus(){
    echo ""
    echo -e "\033[33m************************************************* Service check *******************************************************\033[0m"
    echo ""
    if [[ $centosVersion > 7 ]];then
        conf=$(systemctl list-unit-files --type=service --state=enabled --no-pager | grep "enabled")
        process=$(systemctl list-units --type=service --state=running --no-pager | grep ".service")      
    else
        conf=$(/sbin/chkconfig | grep -E ":on|: Enable ")
        process=$(/sbin/service --status-all 2>/dev/null | grep -E "is running| Running ")        
    fi
	echo -e "\033[36m****************** Service configuration ******************\033[0m"
    echo "$conf"  | column -t
    echo ""
	echo -e "\033[36m************** Running services ****************\033[0m"
    echo "$process"
}


function getAutoStartStatus(){
    echo ""
    echo -e "\033[33m*********************************************** Self start check *******************************************************\033[0m"
    echo -e "\033[36m**************** Self start command *****************\033[0m"
	conf=$(grep -v "^#" /etc/rc.d/rc.local| sed '/^$/d')
    echo "$conf"  
}


function getLoginStatus(){
    echo ""
    echo -e "\033[33m************************************************ Login check ********************************************************\033[0m"
    last | head 
}

function getNetworkStatus(){
    echo ""
    echo -e "\033[33m************************************************ Network check ********************************************************\033[0m"
    if [[ $centosVersion < 7 ]];then
        /sbin/ifconfig -a | grep -v packets | grep -v collisions | grep -v i
		net6
    else
        #ip a
        for i in $(ip link | grep BROADCAST | awk -F: '{print $2}');do ip add show $i | grep -E "BROADCAST|global"| awk '{print $2}' | tr '\n' ' ' ;echo "" ;done
    fi
    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 :$GATEWAY "
    echo "DNS:$DNS"
    # Report information 
    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/,$//')
    echo ""
ping -c 4 www.baidu.com >/dev/null 2>&1
if [ $? -eq 0 ];then
   echo ""
   echo -e "\033[32m network connections : normal !\033[0m" 
else
   echo ""
   echo -e "\033[31m network connections : abnormal !\033[0m" 
fi 
}


function getListenStatus(){
    echo ""
    echo  -e "\033[33m*********************************************** Monitor and check ********************************************************\033[0m"
    TCPListen=$(ss -ntul | column -t)
    echo "$TCPListen"
}


function getCronStatus(){
    echo ""
    echo -e "\033[33m********************************************** Scheduled task check ******************************************************\033[0m"
    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 -e "\033[36m************$user User's scheduled tasks **************\033[0m"
                crontab -l -u $user
                let Crontab=Crontab+$(crontab -l -u $user | wc -l)
                echo ""
            fi
        done
    done
    # Planning tasks 
    #find /etc/cron* -type f | xargs -i ls -l {} | column  -t
    #let Crontab=Crontab+$(find /etc/cron* -type f | wc -l) 
}


function getHowLongAgo(){
    #  Calculate how long a timestamp is from now 
    datetime="$*"
    [ -z "$datetime" ] && echo `stat /etc/passwd|awk "NR==6"`
    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  God  $hours  Hours before "
}


function getUserLastLogin(){
    #  Get the last login time of the user , Including year 
    #  unfortunately last The command does not support displaying the year , Only "last -t YYYYMMDDHHMMSS" Indicates the login between a certain time , I 
    #  We can only use the stupidest way , Compare before today and before New Year's day this year ( Or before last year and the year before last ……) A user 
    #  Login times , If the number of login statistics changes , It means that the last login was this year .
    username=$1
    : ${username:="`whoami`"}
    thisYear=$(date +%Y)
    oldesYear=$(last | tail -n1 | awk '{print $NF}')
    while(( $thisYear >= $oldesYear));do
        loginBeforeToday=$(last $username | grep $username | wc -l)
        loginBeforeNewYearsDayOfThisYear=$(last $username -t $thisYear"0101000000" | grep $username | wc -l)
        if [ $loginBeforeToday -eq 0 ];then
            echo " Never signed in "
            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 -e "\033[33m************************************************* User check *******************************************************\033[0m"
    #/etc/passwd  Last modified 
    pwdfile="$(cat /etc/passwd)"
    Modify=$(stat /etc/passwd | grep Modify | tr '.' ' ' | awk '{print $2,$3}')
    echo "/etc/passwd: $Modify ($(getHowLongAgo $Modify))"
    echo ""
    echo -e "\033[36m****************** Privileged users ******************\033[0m"
    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 -e "\033[36m****************** User list ******************\033[0m"
    USERs=0
    echo "$(
    echo " user name  UID GID HOME SHELL  Last login "
    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 -e "\033[36m****************** Empty password users ****************\033[0m"
    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 -e "\033[36m***************** identical ID user *****************\033[0m"
    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 
}


function getPasswordStatus {
    echo ""
    echo -e "\033[33m************************************************* Password check *******************************************************\033[0m"
    pwdfile="$(cat /etc/passwd)"
    echo ""
    echo -e "\033[36m**************** Password expiration check ****************\033[0m"
    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  Never expire \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))
                let DAYS=$(($diff/(60*60*24)))
                printf "%-15s %s Expires in days \n" $user $DAYS
                result="$result,$user:$DAYS days"
            fi
        done
    done
    report_PasswordExpiry=$(echo $result | sed 's/^,//')
    echo ""
	echo -e "\033[36m**************** Password policy check ****************\033[0m"
    grep -v "#" /etc/login.defs | grep -E "PASS_MAX_DAYS|PASS_MIN_DAYS|PASS_MIN_LEN|PASS_WARN_AGE"
}


function getSudoersStatus(){
    echo ""
    echo -e "\033[33m**********************************************Sudoers Check *******************************************************\033[0m"
    conf=$(grep -v "^#" /etc/sudoers| grep -v "^Defaults" | sed '/^$/d')
    echo "$conf"
    echo ""
}


function getInstalledStatus(){
    echo ""
    echo -e "\033[33m************************************************* Software check *******************************************************\033[0m"
    rpm -qa --last | head | column -t 
}


function getProcessStatus(){
    echo ""
    echo -e "\033[33m************************************************* Process check *******************************************************\033[0m"
    if [ $(ps -ef | grep defunct | grep -v grep | wc -l) -ge 1 ];then
        echo ""
        echo -e "\033[36m*************** Zombie process ***************\033[0m"
        ps -ef | head -n1
        ps -ef | grep defunct | grep -v grep
    fi
	echo ""
    echo -e "\033[36m************CPU Occupy TOP 10 process *************\033[0m"
    echo -e " user   process ID %CPU  command  
	$(ps aux | awk '{print $1, $2, $3, $11}' | sort -k3rn | head -n 10 )"| column -t 
    echo ""
    echo -e "\033[36m************ Memory footprint TOP 10 process *************\033[0m"
    echo -e " user   process ID %MEM  Virtual memory    memory-resident   command  
	$(ps aux | awk '{print $1, $2, $4, $5, $6, $11}' | sort -k3rn | head -n 10 )"| column -t 
	#echo ""
    #echo -e "\033[36m************SWAP Occupy TOP 10 process *************\033[0m"
	#awk: fatal: cannot open file `/proc/18713/smaps' for reading (No such file or directory)
	#for i in `cd /proc;ls |grep "^[0-9]"|awk ' $0 >100'`;do awk '{if (-f /proc/$i/smaps) print "$i file is not exist"; else print "$i"}';done
	#    for i in `cd /proc;ls |grep "^[0-9]"|awk ' $0 >100'` ;do awk '/Swap:/{a=a+$2}END{print '"$i"',a/1024"M"}' /proc/$i/smaps ;done |sort -k2nr > /tmp/swap.txt
	#echo -e " process ID SWAP Use  $(cat /tmp/swap.txt|grep -v awk | head -n 10)"| column -t
}



function getSyslogStatus(){
    echo ""
    echo -e "\033[33m***********************************************syslog Check *******************************************************\033[0m"
    echo "SYSLOG Service status :$(getState rsyslog)"
    echo ""
    echo -e "\033[36m***************rsyslog To configure ******************\033[0m"
    cat /etc/rsyslog.conf 2>/dev/null | grep -v "^#" | grep -v "^\\$" | sed '/^$/d'  | column -t
}


function getFirewallStatus(){
    echo ""
    echo -e "\033[33m*********************************************** Firewall check *******************************************************\033[0m"

    echo -e "\033[36m**************** Firewall status ******************\033[0m"
    if [[ $centosVersion = 7 ]];then
        systemctl status firewalld >/dev/null  2>&1
        status=$?
        if [ $status -eq 0 ];then
                s="active"
        elif [ $status -eq 3 ];then
                s="inactive"
        elif [ $status -eq 4 ];then
                s="permission denied"
        else
                s="unknown"
        fi
    else
        s="$(getState iptables)"
    fi
    echo "firewalld: $s"
    echo ""
    echo -e "\033[36m**************** Firewall configuration ******************\033[0m"
    cat /etc/sysconfig/firewalld 2>/dev/null
}


function getSNMPStatus(){
    #SNMP Service status , Configuration etc. 
    echo ""
    echo -e "\033[33m***********************************************SNMP Check *********************************************************\033[0m"
    status="$(getState snmpd)"
    echo "SNMP Service status :$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'
    fi
}


function getState(){
    if [[ $centosVersion < 7 ]];then
        if [ -e "/etc/init.d/$1" ];then
            if [ `/etc/init.d/$1 status 2>/dev/null | grep -E "is running| Running " | wc -l` -ge 1 ];then
                r="active"
            else
                r="inactive"
            fi
        else
            r="unknown"
        fi
    else
        #CentOS 7+
        r="$(systemctl is-active $1 2>&1)"
    fi
    echo "$r"
}


function getSSHStatus(){
    #SSHD Service status , To configure , Trusted hosts, etc 
    echo ""
    echo -e "\033[33m************************************************SSH Check *********************************************************\033[0m"
    # Check trusted hosts 
    pwdfile="$(cat /etc/passwd)"
    echo "SSH Service status :$(getState sshd)"
    Protocol_Version=$(cat /etc/ssh/sshd_config | grep Protocol | awk '{print $2}')
    echo "SSH Protocol version :$Protocol_Version"
    echo ""
    echo -e "\033[36m**************** Trust host ******************\033[0m"
    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  to grant authorization  \"$authorized_host\"  No password access "
        fi
        let authorized=authorized+$(cat $authorize_file 2>/dev/null | awk '{print $3}'|wc -l)
    done
    echo ""
    echo -e "\033[36m******* Whether to allow ROOT Remote login ***************\033[0m"
    config=$(cat /etc/ssh/sshd_config | grep PermitRootLogin)
    firstChar=${config:0:1}
    if [ $firstChar == "#" ];then
        PermitRootLogin="yes" 
    else
        PermitRootLogin=$(echo $config | awk '{print $2}')
    fi
    echo "PermitRootLogin $PermitRootLogin"
    echo ""
    echo -e "\033[36m*************ssh Service configuration ******************\033[0m"
    cat /etc/ssh/sshd_config | grep -v "^#" | sed '/^$/d'
}


function getNTPStatus(){
    #NTP Service status , current time , Configuration etc. 
    echo ""
    echo -e "\033[33m***********************************************NTP Check **********************************************************\033[0m"
    if [ -e /etc/ntp.conf ];then
        echo "NTP Service status :$(getState ntpd)"
        echo ""
        echo -e "\033[36m*************NTP Service configuration ******************\033[0m"
        cat /etc/ntp.conf 2>/dev/null | grep -v "^#" | sed '/^$/d'
    fi
}


function check(){
    version
    getSystemStatus
	get_resource
    getCpuStatus
    getMemStatus
    getDiskStatus
    getNetworkStatus
    getListenStatus
    getProcessStatus
    getServiceStatus
    getAutoStartStatus
    getLoginStatus
    getCronStatus
    getUserStatus
    getPasswordStatus
    getSudoersStatus
    getFirewallStatus
    getSSHStatus
    getSyslogStatus
    getSNMPStatus
    getNTPStatus
    getInstalledStatus
}
# Perform the inspection and save the inspection results 
check > $RESULTFILE
echo -e "\033[44;37m  The host patrol inspection results are stored in :$RESULTFILE   \033[0m"

# Upload the file of inspection results 
#curl -F "[email protected]$RESULTFILE" "$uploadHostDailyCheckApi" 2>/dev/null
cat $RESULTFILE
原网站

版权声明
本文为[User 8639654]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/08/20210805190122082C.html