运维联盟俱乐部

 找回密码
 立即注册
查看: 2670|回复: 0

linux巡检脚本

[复制链接]
  • TA的每日心情
    开心
    2023-8-9 11:05
  • 发表于 2019-12-26 02:07:51 | 显示全部楼层 |阅读模式
    一款linux巡检脚本,架构设计的不错,保存了,留着以后改造用。
    1. #!/bin/bash
    2. ###################################################################
    3. # Functions: this script from polling system status
    4. # Info: be suitable for CentOS/RHEL 6/7
    5. # Changelog:
    6. #      2016-09-15    shaon     initial commit
    7. ###################################################################
    8. #set path env,if not set will some command not found in crontab

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


    11. # run this script use root
    12. [ $(id -u) -gt 0 ] && echo "please use root run the script! " && exit 1

    13. # check system  version
    14. OS_Version=$(awk '{print $(NF-1)}' /etc/redhat-release)

    15. # declare script version date
    16. Script_Version="2016.08.09"


    17. # define polling log path
    18. LOGPATH=/var/log/polling
    19. [ -d $LOGPATH ] || mkdir -p $LOGPATH
    20. RESULTFILE="$LOGPATH/HostDailyCheck-`hostname`-`date +%Y%m%d`.txt"


    21. # define globle variable
    22. report_DateTime=""    #日期 ok
    23. report_Hostname=""    #主机名 ok
    24. report_OSRelease=""    #发行版本 ok
    25. report_Kernel=""    #内核 ok
    26. report_Language=""    #语言/编码 ok
    27. report_LastReboot=""    #最近启动时间 ok
    28. report_Uptime=""    #运行时间(天) ok
    29. report_CPUs=""    #CPU数量 ok
    30. report_CPUType=""    #CPU类型 ok
    31. report_Arch=""    #CPU架构 ok
    32. report_MemTotal=""    #内存总容量(MB) ok
    33. report_MemFree=""    #内存剩余(MB) ok
    34. report_MemUsedPercent=""    #内存使用率% ok
    35. report_DiskTotal=""    #硬盘总容量(GB) ok
    36. report_DiskFree=""    #硬盘剩余(GB) ok
    37. report_DiskUsedPercent=""    #硬盘使用率% ok
    38. report_InodeTotal=""    #Inode总量 ok
    39. report_InodeFree=""    #Inode剩余 ok
    40. report_InodeUsedPercent=""    #Inode使用率 ok
    41. report_IP=""    #IP地址 ok
    42. report_MAC=""    #MAC地址 ok
    43. report_Gateway=""    #默认网关 ok
    44. report_DNS=""    #DNS ok
    45. report_Listen=""    #监听 ok
    46. report_Selinux=""    #Selinux ok
    47. report_Firewall=""    #防火墙 ok
    48. report_USERs=""    #用户 ok
    49. report_USEREmptyPassword=""   #空密码用户 ok
    50. report_USERTheSameUID=""      #相同ID的用户 ok
    51. report_PasswordExpiry=""    #密码过期(天) ok
    52. report_RootUser=""    #root用户 ok
    53. report_Sudoers=""    #sudo授权  ok
    54. report_SSHAuthorized=""    #SSH信任主机 ok
    55. report_SSHDProtocolVersion=""    #SSH协议版本 ok
    56. report_SSHDPermitRootLogin=""    #允许root远程登录 ok
    57. report_DefunctProsess=""    #僵尸进程数量 ok
    58. report_SelfInitiatedService=""    #自启动服务数量 ok
    59. report_SelfInitiatedProgram=""    #自启动程序数量 ok
    60. report_RuningService=""           #运行中服务数  ok
    61. report_Crontab=""    #计划任务数 ok
    62. report_Syslog=""    #日志服务 ok
    63. report_SNMP=""    #SNMP  OK
    64. report_NTP=""    #NTP ok
    65. report_JDK=""    #JDK版本 ok


    66. function version(){
    67.     echo ""
    68.     echo "System Polling:Version $Script_Version "
    69.     echo ""
    70. }


    71. function getCpuStatus(){
    72.     echo ""
    73.     echo "############################ Check CPU Status#############################"
    74.     Physical_CPUs=$(grep "physical id" /proc/cpuinfo| sort | uniq | wc -l)
    75.     Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l)
    76.     CPU_Kernels=$(grep "cores" /proc/cpuinfo|uniq| awk -F ': ' '{print $2}')
    77.     CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq)
    78.     CPU_Arch=$(uname -m)
    79.     echo "物理CPU个数:$Physical_CPUs"
    80.     echo "逻辑CPU个数:$Virt_CPUs"
    81.     echo "每CPU核心数:$CPU_Kernels"
    82.     echo "    CPU型号:$CPU_Type"
    83.     echo "    CPU架构:$CPU_Arch"
    84.     # report information
    85.     report_CPUs=$Virt_CPUs    #CPU数量
    86.     report_CPUType=$CPU_Type  #CPU类型
    87.     report_Arch=$CPU_Arch     #CPU架构
    88. }


    89. function getMemStatus(){
    90.     echo ""
    91.     echo "############################ Check Memmory Usage ###########################"
    92.     if [[ $OS_Version < 7 ]];then
    93.         free -mo
    94.     else
    95.         free -h
    96.     fi
    97.     # report information
    98.     MemTotal=$(grep MemTotal /proc/meminfo| awk '{print $2}')  #KB
    99.     MemFree=$(grep MemFree /proc/meminfo| awk '{print $2}')    #KB
    100.     let MemUsed=MemTotal-MemFree
    101.     MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf "%.2f",$MemUsed*100/$MemTotal}}")
    102.     report_MemTotal="$((MemTotal/1024))""MB"        #内存总容量(MB)
    103.     report_MemFree="$((MemFree/1024))""MB"          #内存剩余(MB)
    104.     report_MemUsedPercent="$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf "%.2f",$MemUsed*100/$MemTotal}}")""%"   #内存使用率%
    105. }


    106. function getDiskStatus(){
    107.     echo ""
    108.     echo "############################ Check Disk Status ############################"
    109.     df -hiP | sed 's/Mounted on/Mounted/' > /tmp/inode
    110.     df -hTP | sed 's/Mounted on/Mounted/' > /tmp/disk
    111.     join /tmp/disk /tmp/inode | awk '{print $1,$2,"|",$3,$4,$5,$6,"|",$8,$9,$10,$11,"|",$12}'| column -t
    112.     # report information
    113.     diskdata=$(df -TP | sed '1d' | awk '$2!="tmpfs"{print}') #KB
    114.     disktotal=$(echo "$diskdata" | awk '{total+=$3}END{print total}') #KB
    115.     diskused=$(echo "$diskdata" | awk '{total+=$4}END{print total}')  #KB
    116.     diskfree=$((disktotal-diskused)) #KB
    117.     diskusedpercent=$(echo $disktotal $diskused | awk '{if($1==0){printf 100}else{printf "%.2f",$2*100/$1}}')
    118.     inodedata=$(df -iTP | sed '1d' | awk '$2!="tmpfs"{print}')
    119.     inodetotal=$(echo "$inodedata" | awk '{total+=$3}END{print total}')
    120.     inodeused=$(echo "$inodedata" | awk '{total+=$4}END{print total}')
    121.     inodefree=$((inodetotal-inodeused))
    122.     inodeusedpercent=$(echo $inodetotal $inodeused | awk '{if($1==0){printf 100}else{printf "%.2f",$2*100/$1}}')
    123.     report_DiskTotal=$((disktotal/1024/1024))"GB"   #硬盘总容量(GB)
    124.     report_DiskFree=$((diskfree/1024/1024))"GB"     #硬盘剩余(GB)
    125.     report_DiskUsedPercent="$diskusedpercent""%"    #硬盘使用率%
    126.     report_InodeTotal=$((inodetotal/1000))"K"       #Inode总量
    127.     report_InodeFree=$((inodefree/1000))"K"         #Inode剩余
    128.     report_InodeUsedPercent="$inodeusedpercent""%"  #Inode使用率%
    129.     echo ""
    130. }


    131. function getSystemStatus(){
    132.     echo ""
    133.     echo "############################ Check System Status ############################"
    134.     if [ -e /etc/sysconfig/i18n ];then
    135.         default_LANG="$(grep "LANG=" /etc/sysconfig/i18n | grep -v "^#" | awk -F '"' '{print $2}')"
    136.     else
    137.         default_LANG=$LANG
    138.     fi
    139.     export LANG="en_US.UTF-8"
    140.     Release=$(cat /etc/redhat-release 2>/dev/null)
    141.     Kernel=$(uname -r)
    142.     OS=$(uname -o)
    143.     Hostname=$(uname -n)
    144.     SELinux=$(/usr/sbin/sestatus | grep "SELinux status: " | awk '{print $3}')
    145.     LastReboot=$(who -b | awk '{print $3,$4}')
    146.     uptime=$(uptime | sed 's/.*up [,]∗, .*/\1/')
    147.     echo "     系统:$OS"
    148.     echo " 发行版本:$Release"
    149.     echo "     内核:$Kernel"
    150.     echo "   主机名:$Hostname"
    151.     echo "  SELinux:$SELinux"
    152.     echo "语言/编码:$default_LANG"
    153.     echo " 当前时间:$(date +'%F %T')"
    154.     echo " 最后启动:$LastReboot"
    155.     echo " 运行时间:$uptime"
    156.     # report information
    157.     report_DateTime=$(date +"%F %T")  #日期
    158.     report_Hostname="$Hostname"       #主机名
    159.     report_OSRelease="$Release"       #发行版本
    160.     report_Kernel="$Kernel"           #内核
    161.     report_Language="$default_LANG"   #语言/编码
    162.     report_LastReboot="$LastReboot"   #最近启动时间
    163.     report_Uptime="$uptime"           #运行时间(天)
    164.     report_Selinux="$SELinux"
    165.     export LANG="$default_LANG"
    166.     echo ""
    167. }

    168. function getServiceStatus(){
    169.     echo ""
    170.     echo "############################ Check Service Status ############################"
    171.     if [[ $OS_Version > 7 ]];then
    172.         conf=$(systemctl list-unit-files --type=service --state=enabled --no-pager | grep "enabled")
    173.         process=$(systemctl list-units --type=service --state=running --no-pager | grep ".service")
    174.         # report information
    175.         report_SelfInitiatedService="$(echo "$conf" | wc -l)"       #自启动服务数量
    176.         report_RuningService="$(echo "$process" | wc -l)"           #运行中服务数量
    177.     else
    178.         conf=$(/sbin/chkconfig | grep -E ":on|:启用")
    179.         process=$(/sbin/service --status-all 2>/dev/null | grep -E "is running|正在运行")
    180.         # report information
    181.         report_SelfInitiatedService="$(echo "$conf" | wc -l)"       #自启动服务数量
    182.         report_RuningService="$(echo "$process" | wc -l)"           #运行中服务数量
    183.     fi
    184.     echo "Service Configure"
    185.     echo "--------------------------------"
    186.     echo "$conf" | column -t
    187.     echo ""
    188.     echo "The Running Services"
    189.     echo "--------------------------------"
    190.     echo "$process"
    191. }

    192. function getAutoStartStatus(){
    193.     echo ""
    194.     echo "############################ Check Self-starting Services ##########################"
    195.     conf=$(grep -v "^#" /etc/rc.d/rc.local| sed '/^$/d')
    196.     echo "$conf"
    197.     # report information
    198.     report_SelfInitiatedProgram="$(echo $conf | wc -l)"    #自启动程序数量
    199. }


    200. function getLoginStatus(){
    201.     echo ""
    202.     echo "############################ Check Login In ############################"
    203.     last | head
    204. }

    205. function getNetworkStatus(){
    206.     echo ""
    207.     echo "############################ Check Network ############################"
    208.     if [[ $OS_Version < 7 ]];then
    209.         /sbin/ifconfig -a | grep -v packets | grep -v collisions | grep -v inet6
    210.     else
    211.         #ip address
    212.         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
    213.     fi
    214.     GATEWAY=$(ip route | grep default | awk '{print $3}')
    215.     DNS=$(grep nameserver /etc/resolv.conf| grep -v "#" | awk '{print $2}' | tr '\n' ',' | sed 's/,$//')
    216.     echo ""
    217.     echo "Gateway: $GATEWAY "
    218.     echo " DNS: $DNS"
    219.     # report information
    220.     IP=$(ip -f inet addr | grep -v 127.0.0.1 |  grep inet | awk '{print $NF,$2}' | tr '\n' ',' | sed 's/,$//')
    221.     MAC=$(ip link | grep -v "LOOPBACK\|loopback" | awk '{print $2}' | sed 'N;s/\n//' | tr '\n' ',' | sed 's/,$//')
    222.     report_IP="$IP"            #IP地址
    223.     report_MAC=$MAC            #MAC地址
    224.     report_Gateway="$GATEWAY"  #默认网关
    225.     report_DNS="$DNS"          #DNS
    226. }


    227. function getListenStatus(){
    228.     echo ""
    229.     echo "############################ Check Connect Status ############################"
    230. #    TCPListen=$(ss -ntul | column -t)
    231.     TCPListen=$(netstat -ntulp | column -t)
    232.     AllConnect=$(ss -an | awk 'NR>1 {++s[$1]} END {for(k in s) print k,s[k]}' | column -t)
    233.     echo "$TCPListen"
    234.     echo "$AllConnect"
    235.     # report information
    236.     report_Listen="$(echo "$TCPListen"| sed '1d' | awk '/tcp/ {print $5}' | awk -F: '{print $NF}' | sort | uniq | wc -l)"
    237. }

    238. function getCronStatus(){
    239.     echo ""
    240.     echo "############################ Check Crontab ########################"
    241.     Crontab=0
    242.     for shell in $(grep -v "/sbin/nologin" /etc/shells);do
    243.         for user in $(grep "$shell" /etc/passwd | awk -F: '{print $1}');do
    244.             crontab -l -u $user >/dev/null 2>&1
    245.             status=$?
    246.             if [ $status -eq 0 ];then
    247.                 echo "$user"
    248.                 echo "-------------"
    249.                 crontab -l -u $user
    250.                 let Crontab=Crontab+$(crontab -l -u $user | wc -l)
    251.                 echo ""
    252.             fi
    253.         done
    254.     done
    255.     # scheduled task
    256.     find /etc/cron* -type f | xargs -i ls -l {} | column  -t
    257.     let Crontab=Crontab+$(find /etc/cron* -type f | wc -l)
    258.     # report information
    259.     report_Crontab="$Crontab"    #计划任务数
    260. }

    261. function getHowLongAgo(){
    262.     # 计算一个时间戳离现在有多久了
    263.     datetime="$*"
    264.     [ -z "$datetime" ] && echo "错误的参数:getHowLongAgo() $*"
    265.     Timestamp=$(date +%s -d "$datetime")    #转化为时间戳
    266.     Now_Timestamp=$(date +%s)
    267.     Difference_Timestamp=$(($Now_Timestamp-$Timestamp))
    268.     days=0;hours=0;minutes=0;
    269.     sec_in_day=$((60*60*24));
    270.     sec_in_hour=$((60*60));
    271.     sec_in_minute=60
    272.     while (( $(($Difference_Timestamp-$sec_in_day)) > 1 ))
    273.     do
    274.         let Difference_Timestamp=Difference_Timestamp-sec_in_day
    275.         let days++
    276.     done
    277.     while (( $(($Difference_Timestamp-$sec_in_hour)) > 1 ))
    278.     do
    279.         let Difference_Timestamp=Difference_Timestamp-sec_in_hour
    280.         let hours++
    281.     done
    282.     echo "$days 天 $hours 小时前"
    283. }


    284. function getUserLastLogin(){
    285.     # 获取用户最近一次登录的时间,含年份
    286.     # 很遗憾last命令不支持显示年份,只有"last -t YYYYMMDDHHMMSS"表示某个时间之间的登录,我
    287.     # 们只能用最笨的方法了,对比今天之前和今年元旦之前(或者去年之前和前年之前……)某个用户
    288.     # 登录次数,如果登录统计次数有变化,则说明最近一次登录是今年。
    289.     username=$1
    290.     : ${username:="`whoami`"}
    291.     thisYear=$(date +%Y)
    292.     oldesYear=$(last | tail -n1 | awk '{print $NF}')
    293.     while(( $thisYear >= $oldesYear));do
    294.         loginBeforeToday=$(last $username | grep $username | wc -l)
    295.         loginBeforeNewYearsDayOfThisYear=$(last $username -t $thisYear"0101000000" | grep $username | wc -l)
    296.         if [ $loginBeforeToday -eq 0 ];then
    297.             echo "Never Login"
    298.             break
    299.         elif [ $loginBeforeToday -gt $loginBeforeNewYearsDayOfThisYear ];then
    300.             lastDateTime=$(last -i $username | head -n1 | awk '{for(i=4;i<(NF-2);i++)printf"%s ",$i}')" $thisYear" #格式如: Sat Nov 2 20:33 2015
    301.             lastDateTime=$(date "+%Y-%m-%d %H:%M:%S" -d "$lastDateTime")
    302.             echo "$lastDateTime"
    303.             break
    304.         else
    305.             thisYear=$((thisYear-1))
    306.         fi
    307.     done
    308. }

    309. function getUserStatus(){
    310.     echo ""
    311.     echo "############################ Check User ############################"
    312.     # /etc/passwd the last modification time
    313.     pwdfile="$(cat /etc/passwd)"
    314.     Modify=$(stat /etc/passwd | grep Modify | tr '.' ' ' | awk '{print $2,$3}')
    315.     echo "/etc/passwd The last modification time:$Modify ($(getHowLongAgo $Modify))"
    316.     echo ""
    317.     echo "A privileged user"
    318.     echo "-----------------"
    319.     RootUser=""
    320.     for user in $(echo "$pwdfile" | awk -F: '{print $1}');do
    321.         if [ $(id -u $user) -eq 0 ];then
    322.             echo "$user"
    323.             RootUser="$RootUser,$user"
    324.         fi
    325.     done
    326.     echo ""
    327.     echo "User List"
    328.     echo "--------"
    329.     USERs=0
    330.     echo "$(
    331.     echo "UserName UID GID HOME SHELL LasttimeLogin"
    332.     for shell in $(grep -v "/sbin/nologin" /etc/shells);do
    333.         for username in $(grep "$shell" /etc/passwd| awk -F: '{print $1}');do
    334.             userLastLogin="$(getUserLastLogin $username)"
    335.             echo "$pwdfile" | grep -w "$username" |grep -w "$shell"| awk -F: -v lastlogin="$(echo "$userLastLogin" | tr ' ' '_')" '{print $1,$3,$4,$6,$7,lastlogin}'
    336.         done
    337.         let USERs=USERs+$(echo "$pwdfile" | grep "$shell"| wc -l)
    338.     done
    339.     )" | column -t
    340.     echo ""
    341.     echo "Null Password User"
    342.     echo "------------------"
    343.     USEREmptyPassword=""
    344.     for shell in $(grep -v "/sbin/nologin" /etc/shells);do
    345.             for user in $(echo "$pwdfile" | grep "$shell" | cut -d: -f1);do
    346.             r=$(awk -F: '$2=="!!"{print $1}' /etc/shadow | grep -w $user)
    347.             if [ ! -z $r ];then
    348.                 echo $r
    349.                 USEREmptyPassword="$USEREmptyPassword,"$r
    350.             fi
    351.         done   
    352.     done
    353.     echo ""
    354.     echo "The Same UID User"
    355.     echo "----------------"
    356.     USERTheSameUID=""
    357.     UIDs=$(cut -d: -f3 /etc/passwd | sort | uniq -c | awk '$1>1{print $2}')
    358.     for uid in $UIDs;do
    359.         echo -n "$uid";
    360.         USERTheSameUID="$uid"
    361.         r=$(awk -F: 'ORS="";$3=='"$uid"'{print ":",$1}' /etc/passwd)
    362.         echo "$r"
    363.         echo ""
    364.         USERTheSameUID="$USERTheSameUID $r,"
    365.     done
    366.     # report information
    367.     report_USERs="$USERs"    #用户
    368.     report_USEREmptyPassword=$(echo $USEREmptyPassword | sed 's/^,//')
    369.     report_USERTheSameUID=$(echo $USERTheSameUID | sed 's/,$//')
    370.     report_RootUser=$(echo $RootUser | sed 's/^,//')    #特权用户
    371. }


    372. function getPasswordStatus {
    373.     echo ""
    374.     echo "############################ Check Password Status ############################"
    375.     pwdfile="$(cat /etc/passwd)"
    376.     echo ""
    377.     echo "Password Expiration Check"
    378.     echo "-------------------------"
    379.     result=""
    380.     for shell in $(grep -v "/sbin/nologin" /etc/shells);do
    381.         for user in $(echo "$pwdfile" | grep "$shell" | cut -d: -f1);do
    382.             get_expiry_date=$(/usr/bin/chage -l $user | grep 'Password expires' | cut -d: -f2)
    383.             if [[ $get_expiry_date = ' never' || $get_expiry_date = 'never' ]];then
    384.                 printf "%-15s never expiration\n" $user
    385.                 result="$result,$user:never"
    386.             else
    387.                 password_expiry_date=$(date -d "$get_expiry_date" "+%s")
    388.                 current_date=$(date "+%s")
    389.                 diff=$(($password_expiry_date-$current_date))
    390.                 let DAYS=$(($diff/(60*60*24)))
    391.                 printf "%-15s %s expiration after days\n" $user $DAYS
    392.                 result="$result,$user:$DAYS days"
    393.             fi
    394.         done
    395.     done
    396.     report_PasswordExpiry=$(echo $result | sed 's/^,//')
    397.     echo ""
    398.     echo "Check The Password Policy"
    399.     echo "------------"
    400.     grep -v "#" /etc/login.defs | grep -E "PASS_MAX_DAYS|PASS_MIN_DAYS|PASS_MIN_LEN|PASS_WARN_AGE"
    401.     echo ""
    402. }

    403. function getSudoersStatus(){
    404.     echo ""
    405.     echo "############################ Sudoers Check #########################"
    406.     conf=$(grep -v "^#" /etc/sudoers| grep -v "^Defaults" | sed '/^$/d')
    407.     echo "$conf"
    408.     echo ""
    409.     # report information
    410.     report_Sudoers="$(echo $conf | wc -l)"
    411. }


    412. function getInstalledStatus(){
    413.     echo ""
    414.     echo "############################ Software Check ############################"
    415.     rpm -qa --last | head | column -t
    416. }

    417. function getProcessStatus(){
    418.     echo ""
    419.     echo "############################ Process Check ############################"
    420.     if [ $(ps -ef | grep defunct | grep -v grep | wc -l) -ge 1 ];then
    421.         echo ""
    422.         echo "zombie process";
    423.         echo "--------"
    424.         ps -ef | head -n1
    425.         ps -ef | grep defunct | grep -v grep
    426.     fi
    427.     echo ""
    428.     echo "Merory Usage TOP10"
    429.     echo "-------------"
    430.     echo -e "PID %MEM RSS COMMAND
    431.     $(ps aux | awk '{print $2, $4, $6, $11}' | sort -k3rn | head -n 10 )"| column -t
    432.     echo ""
    433.     echo "CPU Usage TOP10"
    434.     echo "------------"
    435.     top b -n1 | head -17 | tail -11
    436.     # report information
    437.     report_DefunctProsess="$(ps -ef | grep defunct | grep -v grep|wc -l)"
    438. }


    439. function getJDKStatus(){
    440.     echo ""
    441.     echo "############################ JDK Check #############################"
    442.     java -version 2>/dev/null
    443.     if [ $? -eq 0 ];then
    444.         java -version 2>&1
    445.     fi
    446.     echo "JAVA_HOME="$JAVA_HOME""
    447.     # report information
    448.     report_JDK="$(java -version 2>&1 | grep version | awk '{print $1,$3}' | tr -d '"')"
    449. }

    450. function getSyslogStatus(){
    451.     echo ""
    452.     echo "############################ Syslog Check ##########################"
    453.     echo "Service Status:$(getState rsyslog)"
    454.     echo ""
    455.     echo "/etc/rsyslog.conf"
    456.     echo "-----------------"
    457.     cat /etc/rsyslog.conf 2>/dev/null | grep -v "^#" | grep -v "^\\$" | sed '/^$/d'  | column -t
    458.     #report information
    459.     report_Syslog="$(getState rsyslog)"
    460. }


    461. function getFirewallStatus(){
    462.     echo ""
    463.     echo "############################ Firewall Check ##########################"
    464.     # Firewall Status/Poilcy
    465.     if [[ $OS_Version < 7 ]];then
    466.         /etc/init.d/iptables status >/dev/null  2>&1
    467.         status=$?
    468.         if [ $status -eq 0 ];then
    469.                 s="active"
    470.         elif [ $status -eq 3 ];then
    471.                 s="inactive"
    472.         elif [ $status -eq 4 ];then
    473.                 s="permission denied"
    474.         else
    475.                 s="unknown"
    476.         fi
    477.     else
    478.         s="$(getState iptables)"
    479.     fi
    480.     echo "iptables: $s"
    481.     echo ""
    482.     echo "/etc/sysconfig/iptables"
    483.     echo "-----------------------"
    484.     cat /etc/sysconfig/iptables 2>/dev/null
    485.     # report information
    486.     report_Firewall="$s"
    487. }


    488. function getSNMPStatus(){
    489.     #SNMP Service Status,Configure
    490.     echo ""
    491.     echo "############################ SNMP Check ############################"
    492.     status="$(getState snmpd)"
    493.     echo "Service Status:$status"
    494.     echo ""
    495.     if [ -e /etc/snmp/snmpd.conf ];then
    496.         echo "/etc/snmp/snmpd.conf"
    497.         echo "--------------------"
    498.         cat /etc/snmp/snmpd.conf 2>/dev/null | grep -v "^#" | sed '/^$/d'
    499.     fi
    500.     # report information
    501.     report_SNMP="$(getState snmpd)"
    502. }

    503. function getState(){
    504.     if [[ $OS_Version < 7 ]];then
    505.         if [ -e "/etc/init.d/$1" ];then
    506.             if [ `/etc/init.d/$1 status 2>/dev/null | grep -E "is running|正在运行" | wc -l` -ge 1 ];then
    507.                 r="active"
    508.             else
    509.                 r="inactive"
    510.             fi
    511.         else
    512.             r="unknown"
    513.         fi
    514.     else
    515.         #CentOS 7+
    516.         r="$(systemctl is-active $1 2>&1)"
    517.     fi
    518.     echo "$r"
    519. }

    520. function getSSHStatus(){
    521.     #SSHD Service Status,Configure
    522.     echo ""
    523.     echo "############################ SSH Check #############################"
    524.     # Check the trusted host
    525.     pwdfile="$(cat /etc/passwd)"
    526.     echo "Service Status:$(getState sshd)"
    527.     Protocol_Version=$(cat /etc/ssh/sshd_config | grep Protocol | awk '{print $2}')
    528.     echo "SSH Protocol Version:$Protocol_Version"
    529.     echo ""
    530.     echo "Trusted Host"
    531.     echo "------------"
    532.     authorized=0
    533.     for user in $(echo "$pwdfile" | grep /bin/bash | awk -F: '{print $1}');do
    534.         authorize_file=$(echo "$pwdfile" | grep -w $user | awk -F: '{printf $6"/.ssh/authorized_keys"}')
    535.         authorized_host=$(cat $authorize_file 2>/dev/null | awk '{print $3}' | tr '\n' ',' | sed 's/,$//')
    536.         if [ ! -z $authorized_host ];then
    537.             echo "$user authorization "$authorized_host" Password-less access"
    538.         fi
    539.         let authorized=authorized+$(cat $authorize_file 2>/dev/null | awk '{print $3}'|wc -l)
    540.     done


    541.     echo ""
    542.     echo "Whether to allow ROOT remote login"
    543.     echo "----------------------------------"
    544.     config=$(cat /etc/ssh/sshd_config | grep PermitRootLogin)
    545.     firstChar=${config:0:1}
    546.     if [ $firstChar == "#" ];then
    547.         PermitRootLogin="yes"  #The default is to allow ROOT remote login
    548.     else
    549.         PermitRootLogin=$(echo $config | awk '{print $2}')
    550.     fi
    551.     echo "PermitRootLogin $PermitRootLogin"


    552.     echo ""
    553.     echo "/etc/ssh/sshd_config"
    554.     echo "--------------------"
    555.     cat /etc/ssh/sshd_config | grep -v "^#" | sed '/^$/d'
    556.     # report information
    557.     report_SSHAuthorized="$authorized"    #SSH信任主机
    558.     report_SSHDProtocolVersion="$Protocol_Version"    #SSH协议版本
    559.     report_SSHDPermitRootLogin="$PermitRootLogin"    #允许root远程登录
    560. }

    561. function getNTPStatus(){
    562.     # The NTP service status, the current time, configuration, etc
    563.     echo ""
    564.     echo "############################ NTP Check #############################"
    565.     if [ -e /etc/ntp.conf ];then
    566.         echo "Service Status:$(getState ntpd)"
    567.         echo ""
    568.         echo "/etc/ntp.conf"
    569.         echo "-------------"
    570.         cat /etc/ntp.conf 2>/dev/null | grep -v "^#" | sed '/^$/d'
    571.     fi
    572.     # report information
    573.     report_NTP="$(getState ntpd)"

    574. }


    575. function getZabbixStatus(){
    576.     # Check Zabbix Serivce Status
    577.     echo ""
    578.     echo "######################### Zabbix Check ##############################"
    579.     netstat -nltp | grep -v grep | grep zabbix > /dev/null 2>&1
    580.     if [ $? -eq 0 ];then
    581.        echo "Service Status": Zabbix is running!
    582.     else
    583.        echo "Service Status": Zabbix not running!
    584.     fi
    585.     # report information
    586. }

    587. function uploadHostDailyCheckReport(){
    588.     json="{
    589.         "DateTime":"$report_DateTime",
    590.         "Hostname":"$report_Hostname",
    591.         "OSRelease":"$report_OSRelease",
    592.         "Kernel":"$report_Kernel",
    593.         "Language":"$report_Language",
    594.         "LastReboot":"$report_LastReboot",
    595.         "Uptime":"$report_Uptime",
    596.         "CPUs":"$report_CPUs",
    597.         "CPUType":"$report_CPUType",
    598.         "Arch":"$report_Arch",
    599.         "MemTotal":"$report_MemTotal",
    600.         "MemFree":"$report_MemFree",
    601.         "MemUsedPercent":"$report_MemUsedPercent",
    602.         "DiskTotal":"$report_DiskTotal",
    603.         "DiskFree":"$report_DiskFree",
    604.         "DiskUsedPercent":"$report_DiskUsedPercent",
    605.         "InodeTotal":"$report_InodeTotal",
    606.         "InodeFree":"$report_InodeFree",
    607.         "InodeUsedPercent":"$report_InodeUsedPercent",
    608.         "IP":"$report_IP",
    609.         "MAC":"$report_MAC",
    610.         "Gateway":"$report_Gateway",
    611.         "DNS":"$report_DNS",
    612.         "Listen":"$report_Listen",
    613.         "Selinux":"$report_Selinux",
    614.         "Firewall":"$report_Firewall",
    615.         "USERs":"$report_USERs",
    616.         "USEREmptyPassword":"$report_USEREmptyPassword",
    617.         "USERTheSameUID":"$report_USERTheSameUID",
    618.         "PasswordExpiry":"$report_PasswordExpiry",
    619.         "RootUser":"$report_RootUser",
    620.         "Sudoers":"$report_Sudoers",
    621.         "SSHAuthorized":"$report_SSHAuthorized",
    622.         "SSHDProtocolVersion":"$report_SSHDProtocolVersion",
    623.         "SSHDPermitRootLogin":"$report_SSHDPermitRootLogin",
    624.         "DefunctProsess":"$report_DefunctProsess",
    625.         "SelfInitiatedService":"$report_SelfInitiatedService",
    626.         "SelfInitiatedProgram":"$report_SelfInitiatedProgram",
    627.         "RuningService":"$report_RuningService",
    628.         "Crontab":"$report_Crontab",
    629.         "Syslog":"$report_Syslog",
    630.         "SNMP":"$report_SNMP",
    631.         "NTP":"$report_NTP",
    632.         "JDK":"$report_JDK"
    633.     }"
    634.     #echo "$json"
    635.     curl -l -H "Content-type: application/json" -X POST -d "$json" "$uploadHostDailyCheckReportApi" 2>/dev/null
    636. }

    637. function check(){
    638.     version
    639.     getSystemStatus
    640.     getCpuStatus
    641.     getMemStatus
    642.     getDiskStatus
    643.     getNetworkStatus
    644.     getListenStatus
    645.     getProcessStatus
    646.     getServiceStatus
    647.     getAutoStartStatus
    648.     getLoginStatus
    649.     getCronStatus
    650.     getUserStatus
    651.     getPasswordStatus
    652.     getSudoersStatus
    653.     getJDKStatus
    654.     getFirewallStatus
    655.     getSSHStatus
    656.     getSyslogStatus
    657.     getSNMPStatus
    658.     getNTPStatus
    659.     getZabbixStatus
    660.     getInstalledStatus
    661. }

    662. # Perform inspections and save the inspection results  #执行检查并保存检查结果
    663. check > $RESULTFILE
    664. echo "Check the result:$RESULTFILE"
    复制代码



    linux_check.sh

    26.37 KB, 下载次数: 2

    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    运维联盟俱乐部 ( 冀ICP备19036648号 )

    GMT+8, 2024-5-18 12:16 , Processed in 0.059044 second(s), 24 queries , Gzip On.

    Powered by Discuz! X3.4

    © 2001-2023 Discuz! Team.

    快速回复 返回顶部 返回列表