C/C++教程

CentOS7系统巡检shell脚本

本文主要是介绍CentOS7系统巡检shell脚本,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

#!/bin/bash
##############################################
#                                                                                        #
# @Author: Mr Liu                                        #
# @Date: 2022-02-16 22:22:22              #
# @Last Modified by: Mr Liu                                             #
# @Last Modified time: 2022-02-16 22:22:11                   #
# @Describe 主机信息每日巡检                                       #
#                                                                                        # 
##############################################

##环境变量PATH没设好,在cron里执行时有很多命令会找不到
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
source /etc/profile
VERSION="V1.1"

[ $(id -u) -gt 0 ] && echo "请使用root用户执行此脚本!" && exit 1
centosVersion=$(awk '{print $(NF-1)}' /etc/redhat-release)

##输出巡检结果
IPADDR=`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|awk 'NR==1{print}'`
PROGPATH=`echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'`
[ -f $PROGPATH ] && PROGPATH="."
LOGPATH="$PROGPATH/log"
[ -e $LOGPATH ] || mkdir $LOGPATH
RESULTFILE="$LOGPATH/HostDailyCheck-$IPADDR-`date +%Y%m%d`.txt"

function version(){
echo ""
echo " CentOS系统巡检脚本: Verison" $VERSION
}

function getCpuInfo(){
echo ""
echo ""
echo "########################## CPU检查 ###########################"
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 "物理CPU个数: $Physical_CPUs"
echo "逻辑CPU个数: $Virt_CPUs"
echo "每CPU核心数: $CPU_Kernels"
echo "CPU型号: $CPU_Type"
echo "CPU架构: $CPU_Arch"
}


function getMemInfo(){
echo ""
echo ""
echo "########################## 内存检查 #########################"
#报表信息
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}}")
report_MemTotal="$((MemTotal/1024))""MB" #内存总容量(MB)
report_MemFree="$((MemFree/1024))""MB" #内存剩余(MB)
report_MemUsedPercent="$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}")""%" #内存使用率%

echo "内存总容量: " $report_MemTotal
echo "内存剩余量: " $report_MemFree
echo "内存使用率: " $report_MemUsedPercent
}

function getDiskInfo(){
echo ""
echo ""
echo "########################## 磁盘检查 ##########################"
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使用率%
echo "硬盘总容量: " $report_DiskTotal
echo "硬盘剩余: " $report_DiskFree
echo "硬盘使用率: " $report_DiskUsedPercent
}


function getSystemInfo(){
echo ""
echo "########################## 系统检查 ##########################"
Release=`cat /etc/redhat-release 2>/dev/null`
Kernel=`uname -r`
OS=`uname -o`
Hostname=`uname -n`
SELinux=`sestatus | grep "SELinux status" | awk '{print $3}'`
LastReboot=`who -b | awk '{print $3,$4}'`
Uptime=`uptime | sed 's/.*up \([^,]*\), .*/\1/'`

echo "系统: $OS"
echo "发行版本: $Release"
echo "内核: $Kernel"
echo "主机名: $Hostname"
echo "SELinux: $SELinux"
echo "语言/编码: $LANG"
echo "当前时间: $(date +'%F %T')"
echo "最后启动时间: $LastReboot"
echo "运行时长: $Uptime"

}

function getServicesInfo(){
echo ""
echo "########################## 服务检查 ##########################"
echo ""
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")
echo "服务配置"
echo "--------"
echo "$conf" | column -t
echo ""
echo "正在运行的服务"
echo "--------------"
echo "$process"
}


function getAutoInfo(){
echo ""
echo "########################## 自启动检查 ##########################"
echo ""
conf=$(grep -v "^#" /etc/rc.d/rc.local| sed '/^$/d')
echo "$conf"
}


function getLoginInfo(){
echo ""
echo "########################## 登录检查 ##########################"
echo ""
last | head
}


function getNetworkInfo(){
echo ""
echo "########################## 网络检查 ##########################"

GATEWAY=`ip route | grep default | awk '{print $3}'`
DNS=`grep nameserver /etc/resolv.conf| grep -v "#" | awk '{print $2}' | tr '\n' ',' | sed 's/,$//'`
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 ""
echo "IP地址: $IP"
echo "MAC地址: $MAC"
echo "网关: $GATEWAY "
echo "DNS: $DNS"
}


function getListenInfo(){
echo ""
echo "########################## 监听检查 ##########################"
TCPListen=`ss -ntul | column -t `
ss -ntul | column -t
}


function getCronInfo(){
echo ""
echo "######################### 计划任务检查 #####################"
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
echo "计划任务数: $Crontab"
}


function getUserInfo(){
echo ""
echo "######################### 用户检查 #####################"
echo ""
Modify=`stat /etc/passwd | grep Modify |tr '.' ' ' | awk '{print$2,$3}'`
echo "/etc/passwd最后修改时间: $Modify"
echo ""
echo "特权用户"
echo "--------"
RootUser=""
for user in $(cat /etc/passwd | awk -F: '{print $1}');do
if [ $(id -u $user) -eq 0 ];then
RootUser="$RootUser,$user"
fi
done
echo $RootUser | sed 's/^,//'

echo ""
echo "用户列表"
echo "--------"
Users=""
for user in $(cat /etc/passwd | grep -v "/sbin/nologin" | awk -F: '{print $1}');do
if [ $(id -u $user) -gt 0 ];then
Users="$Users,$user"
fi
done
echo $Users | sed 's/^,//'
}


function getPasswordInfo(){
echo ""
echo "######################### 密码检查 #####################"
echo ""
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))
let 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 getSudoersInfo(){
echo ""
echo ""
echo "######################## Sudoers检查 #######################"
echo ""
conf=$(grep -v "^#" /etc/sudoers| grep -v "^Defaults" | sed '/^$/d')
echo "$conf"
echo ""
}


function getInstalledInfo(){
echo ""
echo "######################### 软件检查 ##########################"
echo ""
rpm -qa --last | head | column -t
}


function getProcessInfo(){
echo ""
echo ""
echo "############################ 进程检查 ############################"
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 %MEM RSS COMMAND
$(ps aux | awk '{print $2, $4, $6, $11}' | sort -k3rn | head -n 10 )"| column -t
echo ""
echo -e "\033[32mCPU占用TOP10 \033[0m"
echo "------------"
top b -n1 | head -17 | tail -11
}

function getSSHInfo(){
#SSHD服务状态,配置,受信任主机等
echo ""
echo ""
echo "########################## SSH检查 ##########################"
#检查受信任主机
pwdfile="$(cat /etc/passwd)"
echo "服务状态: " `systemctl status sshd|grep Active|awk '{print $2,$3}'`
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
let 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 PermitRootLogin)
firstChar=${config:0:1}
if [ $firstChar == "#" ];then
PermitRootLogin="yes" #默认是允许ROOT远程登录的
else
PermitRootLogin=$(echo $config | awk '{print $2}')
fi
echo "PermitRootLogin $PermitRootLogin"
}


function check(){
version
getCpuInfo
getMemInfo
getDiskInfo
getSystemInfo
getServicesInfo
getAutoInfo
getLoginInfo
getNetworkInfo
getListenInfo
getCronInfo
getUserInfo
getPasswordInfo
getSudoersInfo
getInstalledInfo
getProcessInfo
getSSHInfo
}

#执行检查并保存检查结果
check > $RESULTFILE

这篇关于CentOS7系统巡检shell脚本的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!