linux巡检 ansible巡检基础 linux常用巡检脚本shell

巡检脚本 shell巡检

https://blog.csdn.net/qq_40907977/article/details/103893287

#!/bin/bash

#脚本功能描述:监控服务器主要性能参数指标
#监控项目:内核信息,主机名称,IP地址,登录账户,内存与swap信息,磁盘信息,CPU负载
#内核信息
kernel=$(uname -r)

#操作系统版本
release=$(cat /etc/redhat-release)

#主机名称
hostname=$HOSTNAME

#本地IP地址列表
localip=$(ip a s | awk '/inet /{print $2}')

#总内存容量
mem_total=$(free | awk '/Mem/{print $2}')

#剩余内存容量
mem_free=$(free | awk '/Mem/{print $NF}')

#总swap容量
swap_total=$(free | awk '/Swap/{print $2}')

#剩余swap容量
swap_free=$(free | awk '/Swap/{print $NF}')

#磁盘信息
disk=$(df | awk '/^\/dev/{print $1,$2,$4}'|column -t)

#CPU最近1分钟的平均负载
load1=$(uptime | sed 's/,//g' | awk '{print $(NF-2)}')

#CPU最近5分钟的平均负载
load5=$(uptime | sed 's/,//g' | awk '{print $(NF-1)}')

#CPU最近15分钟的平均负载
load15=$(uptime | sed 's/,//g' | awk '{print $(NF)}')

#登录用户数量
login_users=$(who | wc -l)

#进程数量
procs=$(ps aux | wc -l)

#系统总账户数量
users=$(sed -n '$=' /etc/passwd)

#CPU型号
cpu_info=$(LANG=C lscpu |awk -F: '/Model name/ {print $2}')

#CPU内核数量
cpu_core=$(awk '/processor/{core++} END{print core}' /proc/cpuinfo)

#安装性能监控软件
yum -y -q  install sysstat &>/dev/null

echo -e "\033[34m提取磁盘性能指标,请稍后...\033[0m"

tps=$(LANG=C sar -d -p 1 6 | awk '/Average/' | tail -n +2 |awk '{print "["$2"]磁盘平均IO数量:"$3}') &

read_write=$(LANG=C sar -d -p 1 6 |awk '/Average/' | tail -n +2 | awk '{print "["$2"]平均每秒读写扇区量:"$4,$5}') &

#中断数量
irq=$(vmstat 1 2 |tail -n +4 | awk '{print $11}')

#上下文切换数量
cs=$(vmstat 1 2|tail -n +4 | awk '{print $12}')

#占用内存资源最多的10个进程列表
top_proc_mem=$(ps --no-headers -eo comm,rss | sort -k2 -n |tail -10)

#占用内存资源最多的10个进程列表
top_proc_cpu=$(ps --no-headers -eo comm,rss | sort -k2 -n |tail -10)

#获取网卡流量信息,接收|发送的数据流量,单位为字节(bytes)
net_monitor=$(cat /proc/net/dev | tail -n +3 |awk 'BEGIN{ print "网卡名称 入站数据流量(bytes) 出站数据流量(bytes)"} {print $1,$2,$10}' | column -t)

#输出数据信息
echo -e "\033[32m************************本机主要参数列表********************\033[0m"

echo -e "本机IP地址列表:\033[32m$localip\033[0m"

echo -e "本机主机名称:\033[32m$hostname\033[0m"

echo -e "操作系统版本为:\033[32m$release\033[0m,内核版本:\033[32m$kernel\033[0m"

echo -e "CPU型号为:\033[32m$cpu_info\033[0m,CPU内核数量:\033[32$kernel\033[0m"

echo -e "本机总内存容量:\033[32m$mem_total\033[0m,剩余可用内存容量:\033[32m$mem_free\033[0m"

echo -e "本机swap总容量:\033[32m$swap_local\033[0m,剩余swap容量:\033[32m$swap_free\033[0m"

echo -e "CPU最近1分钟,5分钟,15分钟的平均负载分别为:\033[32m$load1 $load5 $load15\033[0m"

echo -e "本机总账户数量为:\033[32m$users\033[0m,当前登录系统的账户数量:\033[32m$login_users\033[0m"

echo -e "当前系统中启动的进程数量:\033[32m$procs\033[0m"

echo -e "占用CPU资源最多的10个进程列表为:"

echo -e "\033[32m$top_proc_cpu\033[0m"

echo -e "占用CPU内存资源最多的10个进程列表为:"

echo -e "\033[32m$top_proc_mem\033[0m"

echo -e "CPU中断数量为:\033[32m$irq\033[0m,CPU上下文切换数量:\033[32m$cs\033[0m"

echo -e "每个磁盘分区的总容量与剩余容量信息如下:"

echo -e "$disk"

echo -e "$tps"

echo -e "$read_write"

echo -e "$net_monitor"

echo -e "\033[32m************************巡检结束********************\033[0m"

ansible巡检

https://blog.csdn.net/a1308422754/article/details/106879450

ansible  node -m shell -a "disk=$(expr `df |awk '{print $2}'|sort -nr|head -1` / 1048576) && cpu=$(cat /proc/cpuinfo| grep 'cpu cores'| wc -l),&& men=$(free -h|grep 'Mem'|awk '{print $2}') && echo -e '$disk \t , $cpu \t , $men'" 

大而全脚本

原文:https://blog.csdn.net/liuyang9909/article/details/123369426

#!/bin/bash
# @Author: HanWei
# @Date:   2020-03-16 09:56:57
# @Last Modified by:   HanWei
# @Last Modified time: 2020-03-16 11:06:31
# @E-mail: han_wei_95@163.com
#!/bin/bash
#主机信息每日巡检
 
IPADDR=$(ifconfig eth0|grep 'inet addr'|awk -F '[ :]' '{print $13}')
#环境变量PATH没设好,在cron里执行时有很多命令会找不到
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
source /etc/profile
 
[ $(id -u) -gt 0 ] && echo "请用root用户执行此脚本!" && exit 1
centosVersion=$(awk '{print $(NF-1)}' /etc/redhat-release)
VERSION="2020-03-16"
 
#日志相关
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"
 
 
#定义报表的全局变量
report_DateTime="" #日期 ok
report_Hostname="" #主机名 ok
report_OSRelease="" #发行版本 ok
report_Kernel="" #内核 ok
report_Language="" #语言/编码 ok
report_LastReboot="" #最近启动时间 ok
report_Uptime="" #运行时间(天) ok
report_CPUs="" #CPU数量 ok
report_CPUType="" #CPU类型 ok
report_Arch="" #CPU架构 ok
report_MemTotal="" #内存总容量(MB) ok
report_MemFree="" #内存剩余(MB) ok
report_MemUsedPercent="" #内存使用率% ok
report_DiskTotal="" #硬盘总容量(GB) ok
report_DiskFree="" #硬盘剩余(GB) ok
report_DiskUsedPercent="" #硬盘使用率% ok
report_InodeTotal="" #Inode总量 ok
report_InodeFree="" #Inode剩余 ok
report_InodeUsedPercent="" #Inode使用率 ok
report_IP="" #IP地址 ok
report_MAC="" #MAC地址 ok
report_Gateway="" #默认网关 ok
report_DNS="" #DNS ok
report_Listen="" #监听 ok
report_Selinux="" #Selinux ok
report_Firewall="" #防火墙 ok
report_USERs="" #用户 ok
report_USEREmptyPassword="" #空密码用户 ok
report_USERTheSameUID="" #相同ID的用户 ok 
report_PasswordExpiry="" #密码过期(天) ok
report_RootUser="" #root用户 ok
report_Sudoers="" #sudo授权 ok
report_SSHAuthorized="" #SSH信任主机 ok
report_SSHDProtocolVersion="" #SSH协议版本 ok
report_SSHDPermitRootLogin="" #允许root远程登录 ok
report_DefunctProsess="" #僵尸进程数量 ok
report_SelfInitiatedService="" #自启动服务数量 ok
report_SelfInitiatedProgram="" #自启动程序数量 ok
report_RuningService="" #运行中服务数 ok
report_Crontab="" #计划任务数 ok
report_Syslog="" #日志服务 ok
report_SNMP="" #SNMP OK
report_NTP="" #NTP ok
report_JDK="" #JDK版本 ok
function version(){
echo ""
echo ""
echo "系统巡检脚本:Version $VERSION"
}
 
function getCpuStatus(){
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"
#报表信息
report_CPUs=$Virt_CPUs #CPU数量
report_CPUType=$CPU_Type #CPU类型
report_Arch=$CPU_Arch #CPU架构
}
 
function getMemStatus(){
echo ""
echo ""
echo "############################ 内存检查 ############################"
if [[ $centosVersion < 7 ]];then
free -mo
else
free -h
fi
#报表信息
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}}")""%" #内存使用率%
}
function getDiskStatus(){
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使用率%
 
}
 
function getSystemStatus(){
echo ""
echo ""
echo "############################ 系统检查 ############################"
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 " 系统:$OS"
echo " 发行版本:$Release"
echo " 内核:$Kernel"
echo " 主机名:$Hostname"
echo " SELinux:$SELinux"
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" #运行时间(天)
report_Selinux="$SELinux"
export LANG="$default_LANG"
}
function getServiceStatus(){
echo ""
echo ""
echo "############################ 服务检查 ############################"
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")
#报表信息
report_SelfInitiatedService="$(echo "$conf" | wc -l)" #自启动服务数量
report_RuningService="$(echo "$process" | wc -l)" #运行中服务数量
else
conf=$(/sbin/chkconfig | grep -E ":on|:启用")
process=$(/sbin/service --status-all 2>/dev/null | grep -E "is running|正在运行")
#报表信息
report_SelfInitiatedService="$(echo "$conf" | wc -l)" #自启动服务数量
report_RuningService="$(echo "$process" | wc -l)" #运行中服务数量
fi
echo "服务配置"
echo "--------"
echo "$conf" | column -t
echo ""
echo "正在运行的服务"
echo "--------------"
echo "$process"
 
}
 
 
function getAutoStartStatus(){
echo ""
echo ""
echo "############################ 自启动检查 ##########################"
conf=$(grep -v "^#" /etc/rc.d/rc.local| sed '/^$/d')
echo "$conf"
#报表信息
report_SelfInitiatedProgram="$(echo $conf | wc -l)" #自启动程序数量
}
 
function getLoginStatus(){
echo ""
echo ""
echo "############################ 登录检查 ############################"
last | head
}
 
function getNetworkStatus(){
echo ""
echo ""
echo "############################ 网络检查 ############################"
if [[ $centosVersion < 7 ]];then
/sbin/ifconfig -a | grep -v packets | grep -v collisions | grep -v inet6
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 "
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 "############################ 监听检查 ############################"
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=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 "错误的参数: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(){
# 获取用户最近一次登录的时间,含年份
# 很遗憾last命令不支持显示年份,只有"last -t YYYYMMDDHHMMSS"表示某个时间之间的登录,我
# 们只能用最笨的方法了,对比今天之前和今年元旦之前(或者去年之前和前年之前……)某个用户
# 登录次数,如果登录统计次数有变化,则说明最近一次登录是今年。
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 "从未登录过"
break
elif [ $loginBeforeToday -gt $loginBeforeNewYearsDayOfThisYear ];then
lastDateTime=$(last -i $username | head -n1 | awk '{for(i=4;i<(NF-2);i++)printf"%s ",$i}')" $thisYear" #格式如: Sat Nov 2 20:33 2015
lastDateTime=$(date "+%Y-%m-%d %H:%M:%S" -d "$lastDateTime")
echo "$lastDateTime"
break
else
thisYear=$((thisYear-1))
fi
done
 
}
 
function getUserStatus(){
echo ""
echo ""
echo "############################ 用户检查 ############################"
#/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 "############################ 密码检查 ############################"
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 getSudoersStatus(){
echo ""
echo ""
echo "############################ Sudoers检查 #########################"
conf=$(grep -v "^#" /etc/sudoers| grep -v "^Defaults" | sed '/^$/d')
echo "$conf"
echo ""
#报表信息
report_Sudoers="$(echo $conf | wc -l)"
}
 
function getInstalledStatus(){
echo ""
echo ""
echo "############################ 软件检查 ############################"
rpm -qa --last | head | column -t 
}
 
function getProcessStatus(){
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 "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检查 #############################"
java -version 2>/dev/null
if [ $? -eq 0 ];then
java -version 2>&1
fi
echo "JAVA_HOME=\"$JAVA_HOME\""
#报表信息
report_JDK="$(java -version 2>&1 | grep version | awk '{print $1,$3}' | tr -d '"')"
}
function getSyslogStatus(){
echo ""
echo ""
echo "############################ syslog检查 ##########################"
echo "服务状态:$(getState rsyslog)"
echo ""
echo "/etc/rsyslog.conf"
echo "-----------------"
cat /etc/rsyslog.conf 2>/dev/null | grep -v "^#" | grep -v "^\\$" | sed '/^$/d' | column -t
#报表信息
report_Syslog="$(getState rsyslog)"
}
function getFirewallStatus(){
echo ""
echo ""
echo "############################ 防火墙检查 ##########################"
#防火墙状态,策略等
if [[ $centosVersion < 7 ]];then
/etc/init.d/iptables status >/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 "iptables: $s"
echo ""
echo "/etc/sysconfig/iptables"
echo "-----------------------"
cat /etc/sysconfig/iptables 2>/dev/null
#报表信息
report_Firewall="$s"
}
 
function getSNMPStatus(){
#SNMP服务状态,配置等
echo ""
echo ""
echo "############################ SNMP检查 ############################"
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'
fi
#报表信息
report_SNMP="$(getState snmpd)"
}
 
 
 
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|正在运行" | 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服务状态,配置,受信任主机等
echo ""
echo ""
echo "############################ SSH检查 #############################"
#检查受信任主机
pwdfile="$(cat /etc/passwd)"
echo "服务状态:$(getState sshd)"
Protocol_Version=$(cat /etc/ssh/sshd_config | grep 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
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"
 
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(){
#NTP服务状态,当前时间,配置等
echo ""
echo ""
echo "############################ NTP检查 #############################"
if [ -e /etc/ntp.conf ];then
echo "服务状态:$(getState ntpd)"
echo ""
echo "/etc/ntp.conf"
echo "-------------"
cat /etc/ntp.conf 2>/dev/null | grep -v "^#" | sed '/^$/d'
fi
#报表信息
report_NTP="$(getState ntpd)"
}
 
 
function uploadHostDailyCheckReport(){
json="{
\"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\",
\"Selinux\":\"$report_Selinux\",
\"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\"
}"
#echo "$json" 
curl -l -H "Content-type: application/json" -X POST -d "$json" "$uploadHostDailyCheckReportApi" 2>/dev/null
}
 
function getchage_file_24h()
{
echo "############################ 文件检查 #############################"
    check2=$(find / -name '*.sh' -mtime -1)
check21=$(find / -name '*.asp' -mtime -1)
check22=$(find / -name '*.php' -mtime -1)
check23=$(find / -name '*.aspx' -mtime -1)
check24=$(find / -name '*.jsp' -mtime -1)
check25=$(find / -name '*.html' -mtime -1)
check26=$(find / -name '*.htm' -mtime -1)
check9=$(find / -name core -exec ls -l {} \;)
check10=$(cat /etc/crontab)
check12=$(ls -alt /usr/bin | head -10)
cat <<EOF
############################查看所有被修改过的文件返回最近24小时内的############################
${check2}
${check21}
${check22}
${check23}
${check24}
${check25}
${check26}
${line}
############################检查定时文件的完整性############################
${check10}
${line}
############################查看系统命令是否被替换############################
${check12}
${line}
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 "`date "+%Y-%m-%d %H:%M:%S"` 阿里云PHP企业平台巡检报告"  | mail -a $RESULTFILE -s "阿里云PHP企业平台巡检报告"  yourmail@163.com

结果参考 不会输出到屏幕,会输出到文件:

检查结果:./log/HostDailyCheck–20221024.txt

 
 
系统巡检脚本:Version 2020-03-16
 
 
############################ 系统检查 ############################
 系统:GNU/Linux
 发行版本:CentOS Linux release 7.9.2009 (Core)
 内核:3.10.0-1160.el7.x86_64
 主机名:sun
 SELinux:enabled
语言/编码:en_US.UTF-8
 当前时间:2021-11-25 01:06:25
 最后启动:2021-11-25 01:01
 运行时间:4 min
 
 
############################ CPU检查 #############################
物理CPU个数:1
逻辑CPU个数:1
每CPU核心数:1
 CPU型号:Intel(R) Core(TM) i5-1035G1 CPU @ 1.00GHz
 CPU架构:x86_64
 
 
############################ 内存检查 ############################
              total        used        free      shared  buff/cache   available
Mem:           972M        157M        704M        7.6M        110M        685M
Swap:          2.0G          0B        2.0G
 
 
############################ 磁盘检查 ############################
Filesystem               Type      |  Size   Used  Avail  Use%  |  Inodes  IUsed  IFree  IUse%  |  Mounted
devtmpfs                 devtmpfs  |  475M   0     475M   0%    |  119K    386    119K   1%     |  /dev
tmpfs                    tmpfs     |  487M   0     487M   0%    |  122K    1      122K   1%     |  /dev/shm
tmpfs                    tmpfs     |  487M   0     487M   0%    |  122K    753    121K   1%     |  /run
tmpfs                    tmpfs     |  487M   0     487M   0%    |  122K    16     122K   1%     |  /sys/fs/cgroup
tmpfs                    tmpfs     |  487M   7.7M  479M   2%    |  122K    1      122K   1%     |  /dev/shm
tmpfs                    tmpfs     |  487M   7.7M  479M   2%    |  122K    753    121K   1%     |  /run
tmpfs                    tmpfs     |  487M   7.7M  479M   2%    |  122K    16     122K   1%     |  /sys/fs/cgroup
tmpfs                    tmpfs     |  487M   0     487M   0%    |  122K    1      122K   1%     |  /dev/shm
tmpfs                    tmpfs     |  487M   0     487M   0%    |  122K    753    121K   1%     |  /run
tmpfs                    tmpfs     |  487M   0     487M   0%    |  122K    16     122K   1%     |  /sys/fs/cgroup
/dev/mapper/centos-root  xfs       |  17G    2.5G  15G    15%   |  8.5M    61K    8.5M   1%     |  /
/dev/sda1                xfs       |  1014M  138M  877M   14%   |  512K    326    512K   1%     |  /boot
tmpfs                    tmpfs     |  98M    0     98M    0%    |  122K    1      122K   1%     |  /run/user/0
 
 
############################ 网络检查 ############################
ens33: 10.0.0.180/24 
ens37: 192.168.100.20/24 
 
网关:10.0.0.1
192.168.100.254 
 DNS:10.0.0.1
 
 
############################ 监听检查 ############################
Netid  State   Recv-Q  Send-Q  Local          Address:Port  Peer  Address:Port
udp    UNCONN  0       0       *:68           *:*
udp    UNCONN  0       0       127.0.0.1:323  *:*
udp    UNCONN  0       0       [::1]:323      [::]:*
tcp    LISTEN  0       128     *:22           *:*
tcp    LISTEN  0       100     127.0.0.1:25   *:*
tcp    LISTEN  0       128     [::]:22        [::]:*
tcp    LISTEN  0       100     [::1]:25       [::]:*
 
 
############################ 进程检查 ############################
 
内存占用TOP10
-------------
PID   %MEM  RSS    COMMAND
1402  1.7   17448  /usr/bin/python2
952   1.1   11236  /usr/lib/polkit-1/polkitd
987   1.1   10972  /usr/sbin/NetworkManager
1     0.7   7092   /usr/lib/systemd/systemd
1401  0.6   6300   /usr/sbin/rsyslogd
525   0.5   5844   /usr/lib/systemd/systemd-udevd
947   0.5   5632   /usr/sbin/abrtd
1712  0.5   5592   sshd:
1142  0.5   5488   /sbin/dhclient
949   0.5   5024   /usr/bin/VGAuthService
 
CPU占用TOP10
------------
   PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
     1 root      20   0  128436   7092   4144 S  0.0  0.7   0:02.48 systemd
     2 root      20   0       0      0      0 S  0.0  0.0   0:00.00 kthreadd
     3 root      20   0       0      0      0 S  0.0  0.0   0:00.00 kworker/0:0
     4 root       0 -20       0      0      0 S  0.0  0.0   0:00.00 kworker/0:0H
     5 root      20   0       0      0      0 S  0.0  0.0   0:00.02 kworker/u256:0
     6 root      20   0       0      0      0 S  0.0  0.0   0:00.09 ksoftirqd/0
     7 root      rt   0       0      0      0 S  0.0  0.0   0:00.00 migration/0
     8 root      20   0       0      0      0 S  0.0  0.0   0:00.00 rcu_bh
     9 root      20   0       0      0      0 S  0.0  0.0   0:00.69 rcu_sched
    10 root       0 -20       0      0      0 S  0.0  0.0   0:00.00 lru-add-drain
 
 
############################ 服务检查 ############################
 
服务配置
--------
abrt-ccpp.service                           enabled
abrt-oops.service                           enabled
abrt-vmcore.service                         enabled
abrt-xorg.service                           enabled
abrtd.service                               enabled
auditd.service                              enabled
autovt@.service                             enabled
chronyd.service                             enabled
crond.service                               enabled
dbus-org.freedesktop.nm-dispatcher.service  enabled
getty@.service                              enabled
irqbalance.service                          enabled
kdump.service                               enabled
lvm2-monitor.service                        enabled
microcode.service                           enabled
NetworkManager-dispatcher.service           enabled
NetworkManager-wait-online.service          enabled
NetworkManager.service                      enabled
postfix.service                             enabled
rhel-autorelabel-mark.service               enabled
rhel-autorelabel.service                    enabled
rhel-configure.service                      enabled
rhel-dmesg.service                          enabled
rhel-domainname.service                     enabled
rhel-import-state.service                   enabled
rhel-loadmodules.service                    enabled
rhel-readonly.service                       enabled
rsyslog.service                             enabled
sshd.service                                enabled
systemd-readahead-collect.service           enabled
systemd-readahead-drop.service              enabled
systemd-readahead-replay.service            enabled
tuned.service                               enabled
vgauthd.service                             enabled
vmtoolsd.service                            enabled
 
正在运行的服务
--------------
abrt-oops.service        loaded active running ABRT kernel log watcher
abrtd.service            loaded active running ABRT Automated Bug Reporting Tool
auditd.service           loaded active running Security Auditing Service
chronyd.service          loaded active running NTP client/server
crond.service            loaded active running Command Scheduler
dbus.service             loaded active running D-Bus System Message Bus
getty@tty1.service       loaded active running Getty on tty1
lvm2-lvmetad.service     loaded active running LVM2 metadata daemon
NetworkManager.service   loaded active running Network Manager
polkit.service           loaded active running Authorization Manager
postfix.service          loaded active running Postfix Mail Transport Agent
rsyslog.service          loaded active running System Logging Service
sshd.service             loaded active running OpenSSH server daemon
systemd-journald.service loaded active running Journal Service
systemd-logind.service   loaded active running Login Service
systemd-udevd.service    loaded active running udev Kernel Device Manager
tuned.service            loaded active running Dynamic System Tuning Daemon
vgauthd.service          loaded active running VGAuth Service for open-vm-tools
vmtoolsd.service         loaded active running Service for virtual machines hosted on VMware
 
 
############################ 自启动检查 ##########################
touch /var/lock/subsys/local
############################ 登录检查 ############################
root     pts/0        192.168.100.1    Thu Nov 25 01:05   still logged in   
root     tty1                          Thu Nov 25 01:03   still logged in   
reboot   system boot  3.10.0-1160.el7. Thu Nov 25 01:01 - 01:06  (00:04)    
test1    pts/1        192.168.100.1    Tue Nov 16 22:31 - crash (8+02:30)   
root     pts/0        192.168.100.1    Tue Nov 16 22:18 - crash (8+02:43)   
root     pts/0        192.168.100.1    Tue Nov 16 01:14 - 17:24  (16:10)    
reboot   system boot  3.10.0-1160.el7. Mon Nov 15 22:19 - 01:06 (9+02:47)   
root     pts/0        192.168.100.1    Mon Nov 15 04:24 - 04:52  (00:28)    
reboot   system boot  3.10.0-1160.el7. Mon Nov 15 04:23 - 04:52  (00:29)    
root     pts/0        192.168.100.1    Tue Mar 30 22:14 - crash (229+07:08) 
 
 
############################ 计划任务检查 ########################
-rw-r--r--.  1  root  root  128  Aug  8   2019  /etc/cron.d/0hourly
-rwx------.  1  root  root  219  Mar  31  2020  /etc/cron.daily/logrotate
-rwxr-xr-x.  1  root  root  618  Oct  30  2018  /etc/cron.daily/man-db.cron
-rw-------.  1  root  root  0    Aug  8   2019  /etc/cron.deny
-rwxr-xr-x.  1  root  root  392  Aug  8   2019  /etc/cron.hourly/0anacron
-rw-r--r--.  1  root  root  451  Jun  9   2014  /etc/crontab
############################ 用户检查 ############################
/etc/passwd 最后修改时间:2021-11-16 22:21:53 (82 小时前)
 
特权用户
--------
root
 
用户列表
--------
用户名  UID   GID   HOME         SHELL      最后一次登录
root    0     0     /root        /bin/bash  2021-11-25_01:05:00
test1   1000  1000  /home/test1  /bin/bash  2021-11-16_22:31:00
 
空密码用户
----------
 
相同ID的用户
------------
 
 
############################ 密码检查 ############################
 
密码过期检查
------------
root            永不过期
test1           永不过期
 
密码策略检查
------------
PASS_MAX_DAYS	99999
PASS_MIN_DAYS	0
PASS_MIN_LEN	5
PASS_WARN_AGE	7
 
 
############################ Sudoers检查 #########################
root	ALL=(ALL) 	ALL
test1	ALL=NOPASSWD	:ALL
%wheel	ALL=(ALL)	ALL
############################ JDK检查 #############################
JAVA_HOME=""
 
 
############################ 防火墙检查 ##########################
iptables: inactive
/etc/sysconfig/iptables
-----------------------
############################ SSH检查 #############################
服务状态:active
SSH协议版本:
 
信任主机
--------
 
是否允许ROOT远程登录
--------------------
PermitRootLogin yes
 
/etc/ssh/sshd_config
--------------------
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
SyslogFacility AUTHPRIV
PermitRootLogin yes
AuthorizedKeysFile	.ssh/authorized_keys
PasswordAuthentication yes
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
UsePAM yes
X11Forwarding yes
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
Subsystem	sftp	/usr/libexec/openssh/sftp-server
 
 
############################ syslog检查 ##########################
服务状态:active
/etc/rsyslog.conf
-----------------
*.info;mail.none;authpriv.none;cron.none  /var/log/messages
authpriv.*                                /var/log/secure
mail.*                                    -/var/log/maillog
cron.*                                    /var/log/cron
*.emerg                                   :omusrmsg:*
uucp,news.crit                            /var/log/spooler
local7.*                                  /var/log/boot.log
############################ SNMP检查 ############################
服务状态:unknown
 
 
 
############################ NTP检查 #############################
 
 
############################ 软件检查 ############################
shc-4.0.3-1.el7.x86_64                        Mon  15  Nov  2021  04:27:10  AM  EST
wget-1.14-18.el7_6.1.x86_64                   Tue  30  Mar  2021  10:15:48  PM  EDT
lrzsz-0.12.20-36.el7.x86_64                   Wed  24  Mar  2021  04:55:26  AM  EDT
net-tools-2.0-0.25.20131004git.el7.x86_64     Wed  24  Mar  2021  02:03:54  AM  EDT
iwl7260-firmware-25.30.13.0-79.el7.noarch     Wed  17  Mar  2021  08:55:41  AM  EDT
iwl6000g2a-firmware-18.168.6.1-79.el7.noarch  Wed  17  Mar  2021  08:55:41  AM  EDT
iwl6000-firmware-9.221.4.1-79.el7.noarch      Wed  17  Mar  2021  08:55:41  AM  EDT
iwl3945-firmware-15.32.2.9-79.el7.noarch      Wed  17  Mar  2021  08:55:41  AM  EDT
iwl100-firmware-39.31.5.1-79.el7.noarch       Wed  17  Mar  2021  08:55:41  AM  EDT
iwl6050-firmware-41.28.5.1-79.el7.noarch      Wed  17  Mar  2021  08:55:39  AM  EDT
############################ 文件检查 #############################
 
############################查看所有被修改过的文件返回最近24小时内的############################
/root/jiaoben/xj.sh
 
 
 
 
 
 
 
 
############################检查定时文件的完整性############################
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
 
# For details see man 4 crontabs
 
# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
 
 
############################查看系统命令是否被替换############################
total 114668
dr-xr-xr-x.   2 root root      28672 Nov 15 04:27 .
lrwxrwxrwx.   1 root root          7 Mar 17  2021 latrace-ctl -> latrace
lrwxrwxrwx.   1 root root          4 Mar 17  2021 byacc -> yacc
lrwxrwxrwx.   1 root root          4 Mar 17  2021 flex++ -> flex
lrwxrwxrwx.   1 root root          4 Mar 17  2021 lex -> flex
lrwxrwxrwx.   1 root root         10 Mar 17  2021 lsdiff -> filterdiff
lrwxrwxrwx.   1 root root         10 Mar 17  2021 grepdiff -> filterdiff
lrwxrwxrwx.   1 root root          9 Mar 17  2021 flipdiff -> interdiff
lrwxrwxrwx.   1 root root          9 Mar 17  2021 combinediff -> interdiff
 

230313巡检脚本:
https://blog.51cto.com/u_15054039/4213064

sys_check(){
        echo "主机名称:`hostname`"
        #echo "操作系统:`cat /etc/*-release|awk 'END{print}'`"
        echo "操作系统:`cat /etc/*-release|awk 'END{print}'|cut -d \= -f 2|sed                                                                                                                                                              's/\"//g'`"
        echo "系统内核:`uname -r`"
        #echo "SELinux:`/usr/sbin/sestatus | grep 'SELinux status:' | awk '{pri                                                                                                                                                             nt $3}'`"
        echo "系统语言:`echo $LANG |awk -F "." '{print $1}'`"
        echo "系统编码:`echo $LANG |awk -F "." '{print $2}'`"
        echo "当前时间:`date +%F_%T`"
        echo "启动时间:`who -b | awk '{print $3,$4}'`"
        echo "运行时间:`uptime | awk '{print $3 " " $4}' | sed 's/,//g'`"
        }

cpu_Info(){
        echo "CPU架构:`uname -m`"
        echo "CPU型号:`cat /proc/cpuinfo | grep "model name" | uniq|awk -F":" '                                                                                                                                                             {print $2}'`"
#        echo "CPU数量:`cat /proc/cpuinfo | grep "physical id"|sort|uniq|wc -l`                                                                                                                                                              颗"
 #       echo "CPU核心:`cat /proc/cpuinfo | grep "cpu cores"|sort|uniq|awk -F "                                                                                                                                                             :" '{print $2}'` 核"
        echo "CPU线程:`cat /proc/cpuinfo | grep "processor" | awk '{print $3}'                                                                                                                                                              | sort | uniq | wc -l` 线程"

        }

cpu_Check(){
        Check_Res=`sar -u 1 5 |grep Average`
        echo "CPU用户占比:`echo $Check_Res|awk '{printf $3}'`%"
        echo "CPU内核占比:`echo $Check_Res|awk '{printf $5}'`%"
        echo "ResCheck_CPURate:`echo $Check_Res|awk '{printf $3+$5}'`%"
        echo "CPU可用占比:`echo $Check_Res|awk '{printf $8}'`%"
        }


mem_check(){
        free_total=`free -m | grep Mem|awk '{printf $2}'`
        free_used=`free -m | grep -v Swap|awk 'END{printf $3}'`
        #free_available=`free -m | grep Mem|awk '{printf $4}'`
        #used_baifen=`echo "scale=2;$free_used/$free_total*100"|bc`
        echo "内存合计:`free -g | awk "NR==2"| awk '{print $2}'` GB "
        echo "内存used:`free -g | grep -v Swap | awk 'END{print $3}'` GB"
        #echo "内存buff/cache:`free -g | awk "NR==2"| awk '{print $6}'` GB"
        #echo "内存使用:`free -m | awk "NR==2"| awk '{printf ("%.2f\n", ($3+$6)                                                                                                                                                             /1024)}'` GB 占比 `echo "scale=2;$free_used/$free_total*100"|bc`%"
        echo "ResCheck_MemRate: `echo "scale=2;($free_used/$free_total)*100"|bc                                                                                                                                                             `%"
        # echo "内存使用:`free -mh | awk "NR==2"| awk '{print $3+$6}'` G占比 `e                                                                                                                                                             cho "scale=2;$free_used/$free_total*100"|bc`%"
        #echo "内存可用:`free -g | awk "NR==2"| awk '{print $4}'` GB 占比 `echo                                                                                                                                                              "scale=2;$free_available/$free_total*100"|bc`% "
        #echo "内存可用:`free -g | awk "NR==2"| awk '{print $4}'` GB 占比 `echo                                                                                                                                                              "scale=2;$free_available/$free_total*100"|bc`% "
        }

disk_Check(){

        echo "`df -h | sort |grep -E "/sd|/mapper" |awk '{print "ResCheck_DiskRa                                                                                                                                                             te:分区" $1  ," 合 计"$2" 已用" $3 " 剩余"$4 " 使用占比 " $5}'`"

       # echo "`df -h | sort |grep /sd |awk '{print "ResCheck_DiskRate:分区" $1                                                                                                                                                               ," 合计"$2" 已用" $3 " 剩余"$4 " 使用占比 " $5}'`"
        }

ip_Addr(){

        echo "`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6 |awk -F " "                                                                                                                                                              'BEGIN {count=0} {count=count+1; print "IP地址" count ":" $2}'`"
}



sys_check
cpu_Info
cpu_Check
mem_check
disk_Check
ip_Addr

simple 巡检

sys_check(){
        echo "主机名称:`hostname`"
        #echo "操作系统:`cat /etc/*-release|awk 'END{print}'`"
        echo "操作系统:`cat /etc/*-release|awk 'END{print}'|cut -d \= -f 2|sed                                                                                                                                                              's/\"//g'`"
        echo "系统内核:`uname -r`"
        #echo "SELinux:`/usr/sbin/sestatus | grep 'SELinux status:' | awk '{pri                                                                                                                                                             nt $3}'`"
        echo "系统语言:`echo $LANG |awk -F "." '{print $1}'`"
        echo "系统编码:`echo $LANG |awk -F "." '{print $2}'`"
        echo "当前时间:`date +%F_%T`"
        echo "启动时间:`who -b | awk '{print $3,$4}'`"
        echo "运行时间:`uptime | awk '{print $3 " " $4}' | sed 's/,//g'`"
        }

cpu_Info(){
        echo "CPU架构:`uname -m`"
        echo "CPU型号:`cat /proc/cpuinfo | grep "model name" | uniq|awk -F":" '                                                                                                                                                             {print $2}'`"
#        echo "CPU数量:`cat /proc/cpuinfo | grep "physical id"|sort|uniq|wc -l`                                                                                                                                                              颗"
 #       echo "CPU核心:`cat /proc/cpuinfo | grep "cpu cores"|sort|uniq|awk -F "                                                                                                                                                             :" '{print $2}'` 核"
        echo "CPU线程:`cat /proc/cpuinfo | grep "processor" | awk '{print $3}'                                                                                                                                                              | sort | uniq | wc -l` 线程"

        }

cpu_Check(){
        Check_Res=`sar -u 1 5 |grep Average`
        echo "CPU用户占比:`echo $Check_Res|awk '{printf $3}'`%"
        echo "CPU内核占比:`echo $Check_Res|awk '{printf $5}'`%"
        echo "ResCheck_CPURate:`echo $Check_Res|awk '{printf $3+$5}'`%"
        echo "CPU可用占比:`echo $Check_Res|awk '{printf $8}'`%"
        }


mem_check(){
        free_total=`free -m | grep Mem|awk '{printf $2}'`
        free_used=`free -m | grep -v Swap|awk 'END{printf $3}'`
        #free_available=`free -m | grep Mem|awk '{printf $4}'`
        #used_baifen=`echo "scale=2;$free_used/$free_total*100"|bc`
        echo "内存合计:`free -g | awk "NR==2"| awk '{print $2}'` GB "
        echo "内存used:`free -g | grep -v Swap | awk 'END{print $3}'` GB"
        #echo "内存buff/cache:`free -g | awk "NR==2"| awk '{print $6}'` GB"
        #echo "内存使用:`free -m | awk "NR==2"| awk '{printf ("%.2f\n", ($3+$6)                                                                                                                                                             /1024)}'` GB 占比 `echo "scale=2;$free_used/$free_total*100"|bc`%"
        echo "ResCheck_MemRate: `echo "scale=2;($free_used/$free_total)*100"|bc                                                                                                                                                             `%"
        # echo "内存使用:`free -mh | awk "NR==2"| awk '{print $3+$6}'` G占比 `e                                                                                                                                                             cho "scale=2;$free_used/$free_total*100"|bc`%"
        #echo "内存可用:`free -g | awk "NR==2"| awk '{print $4}'` GB 占比 `echo                                                                                                                                                              "scale=2;$free_available/$free_total*100"|bc`% "
        #echo "内存可用:`free -g | awk "NR==2"| awk '{print $4}'` GB 占比 `echo                                                                                                                                                              "scale=2;$free_available/$free_total*100"|bc`% "
        }

disk_Check(){

        echo "`df -h | sort |grep -E "/sd|/mapper" |awk '{print "ResCheck_DiskRa                                                                                                                                                             te:分区" $1  ," 合 计"$2" 已用" $3 " 剩余"$4 " 使用占比 " $5}'`"

       # echo "`df -h | sort |grep /sd |awk '{print "ResCheck_DiskRate:分区" $1                                                                                                                                                               ," 合计"$2" 已用" $3 " 剩余"$4 " 使用占比 " $5}'`"
        }

ip_Addr(){

        echo "`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6 |awk -F " "                                                                                                                                                              'BEGIN {count=0} {count=count+1; print "IP地址" count ":" $2}'`"
}



sys_check
cpu_Info
cpu_Check
mem_check
disk_Check
ip_Addr

输出

主机名称:it-ansible
操作系统:CentOS Linux release 7.6.1810 (Core)
系统内核:3.10.0-957.27.2.el7.x86_64
系统语言:zh_CN
系统编码:UTF-8
当前时间:2023-06-15_14:05:26
启动时间:14:01
运行时间:35 days
CPU架构:x86_64
CPU型号: Intel® Xeon® CPU E5-2673 v4 @ 2.30GHz
CPU线程:4 线程
CPU用户占比:%
CPU内核占比:%
ResCheck_CPURate:0%
CPU可用占比:%
内存合计:15 GB
内存used:7 GB
ResCheck_MemRate: 44.00%
ResCheck_DiskRa te:分区/dev/sda1 合 计497M 已用65M 剩余433M 使用占比 13%
ResCheck_DiskRa te:分区/dev/sda2 合 计256G 已用22G 剩余235G 使用占比 9%
ResCheck_DiskRa te:分区/dev/sdb1 合 计32G 已用49M 剩余30G 使用占比 1%
ResCheck_DiskRa te:分区/dev/sdc 合 计126G 已用66G 剩余55G 使用占比 55%
IP地址1:192.168.58.1
IP地址2:172.18.0.1
IP地址3:192.168.49.1
IP地址4:172.19.0.1
IP地址5:172.17.0.1

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用Ansible执行shell脚本可以通过在Ansible Playbook中使用`shell`模块来实现。具体步骤如下: 1. 创建一个Ansible Playbook文件,并在其中定义一个任务,该任务使用`shell`模块来执行shell脚本。 例如,下面的代码演示了如何使用`shell`模块执行一个简单的shell脚本: ``` - name: 执行shell脚本 hosts: your_host tasks: - name: 运行脚本 shell: /path/to/your/script.sh ``` 在上面的示例中,`/path/to/your/script.sh`是要执行的shell脚本的路径。可以将此路径替换为自己的脚本路径。 2. 保存并运行Ansible Playbook文件。可以使用`ansible-playbook`命令来运行Playbook文件,例如: ``` ansible-playbook your_playbook.yml ``` 在执行过程中,Ansible将连接到远程主机并执行指定的shell脚本。 注意:在执行shell脚本时,请确保有足够的权限来运行脚本,并且脚本本身是可执行的。此外,还应确保在Playbook文件中正确指定了主机和用户名等必要的信息。 ### 回答2: Ansible是一个使用Python语言编写的自动化工具,它可以管理多台远程主机,批量执行指定的任务。Ansible可以通过配置文件和模块来实现各种自动化任务,其中执行Shell脚本就是其中一种任务。 执行Shell脚本Ansible自动化工具的一项重要功能。通过Ansible执行一个Shell脚本,可以批量地运行一系列命令,并且可以避免手动在远程主机上执行任务的风险和不可控性。 要在Ansible中执行Shell脚本,首先需要编写一个playbook文件,包含以下基本元素:主机列表、任务列表、变量、模块以及条件控制结构。下面将逐一介绍这些基本元素。 1. 主机列表 主机列表指定需要执行Shell脚本的远程主机。可以通过IP地址、主机名或标记来指定主机列表。主机列表可以单独指定,也可以通过变量定义。 示例: ``` --- - name: Execute shell scripts on remote hosts hosts: all become: true tasks: - name: Run script on remote hosts shell: | /bin/bash /path/to/script.sh ``` 2. 任务列表 任务列表包含要在远程主机上执行的任务。任务列表可以包含多个任务,每个任务都有自己的名称、模块、参数和变量。 示例: ``` tasks: - name: Run script on remote hosts shell: | /bin/bash /path/to/script.sh ``` 3. 变量 变量允许向playbook传递自定义参数和设置。最常见的变量类型是主机参数和组参数。 示例: ``` vars: script_name: script.sh tasks: - name: Run script on remote hosts shell: | /bin/bash /path/to/{{ script_name }} ``` 4. 模块 模块是Ansible中最常用的元素之一,它定义了可以执行远程任务的操作。例如,如果要在远程主机上执行Shell脚本,则需要使用“shell”模块。 示例: ``` tasks: - name: Run script on remote hosts shell: | /bin/bash /path/to/script.sh ``` 5. 条件控制结构 条件控制结构允许根据主机或组的条件来选择要执行的任务。 示例: ``` tasks: - name: Run script on remote hosts shell: | /bin/bash /path/to/script.sh when: "'db' in group_names" ``` 总的来说,在Ansible中执行Shell脚本是一个非常常见和有用的任务。通过编写一个playbook文件,按照上述基本元素进行配置,即可实现批量执行Shell脚本的自动化过程。在执行过程中,需要注意一些技巧,例如使用“shell”模块来指定脚本路径和参数,使用条件控制结构来选择要运行的主机,以及使用变量来传递自定义参数等。 ### 回答3: Ansible是一款自动化工具,它可用于管理、协调和自动化IT基础设施配置。Ansible在执行多个任务时非常有用,这些任务需要在一个设每台主机运行,而且需要一些脚本来管理它们。 在Ansible中执行shell脚本可以通过使用Shell Module来实现。Shell Module是Ansible的一个核心模块,它允许用户在远程主机上执行shell脚本或命令。 在Ansible Playbook中使用Shell Module执行脚本的基本语法如下: ```yaml - name: Execute script on remote host hosts: remote-server gather_facts: no tasks: - name: Run script shell: /path/to/script.sh ``` 在上面的示例中,playbook将在`remote-server`主机上执行`/path/to/script.sh`脚本。`gather_facts`选项已经设置为no,因为该选项允许收集有关主机的事实信息。在执行脚本时,您可能不需要这些信息。 您还可以使用`args`参数来传递脚本的参数。下面是一个示例: ```yaml - name: Execute script on remote host hosts: remote-server gather_facts: no tasks: - name: Run script shell: /path/to/script.sh args: arg1: value1 arg2: value2 ``` 在上面的示例中,如果你的脚本需要两个参数,那么你可以使用args参数来传递这两个值。这使得在一行中完整传递所有参数变得更加容易。 总的来说,使用Ansible执行shell脚本是非常简单的。您只需要使用Shell Module,并提供要在目标主机上执行的脚本的路径即可。 无论您是执行基本shell命令还是执行复杂的脚本Ansible都是一个高效且易于使用的工具,帮助您管理、协调和自动化IT基础设施。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值