易陆发现互联网技术论坛

 找回密码
 开始注册
查看: 580|回复: 2
收起左侧

python脚本巡检脚本

[复制链接]
发表于 2023-5-2 10:30:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?开始注册

x
#! /usr/bin/env python# -*- coding: utf-8 -*-# __author__ = "LongRui"# Email:# Date: 2023/5/02
' w3 m! i% `, u% Kimport paramiko
' R; T. h! H! o: g$ }* d, qdef sftp_exec_command(host,port,username,password,command):    ssh = paramiko.SSHClient()    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    ssh.connect(hostname=host, port=port, username=username, password=password)    stdin, stdout, stderr= ssh.exec_command(command)    list = []    for item in stdout.readlines():        list.append(item.strip())    return list    ssh.close()
4 `2 ^" K" e1 D' D8 odef sftp_down_file(host,port,username,password,server_path, local_path):    try:        t = paramiko.Transport((host, port))        t.connect(username=username, password=password)        sftp = paramiko.SFTPClient.from_transport(t)        sftp.get(server_path , local_path)        t.close()    except Exception as e:        print(e)if __name__ == '__main__':    hosts_file = open('./hosts/host.info', 'r')    for line in hosts_file.readlines():        if line[0:1] == '#': continue        line = line.strip('\n')        items = line.split()        port = 22        host = items[0]        username = items[1]        password = items[2]
0 `, F8 Z2 x, u        sftp_exec_command(host,port,username,password,"sh /root/xunjian.sh")        n = sftp_exec_command(host,port,username,password,"ls -t /root/log/ | head -1 ")
0 ~% ~# E2 D( W  \3 b        filename = "/root/log/%s" % (n[0])        print(filename)        sftp_down_file(host,port,username,password,filename, "D:/大数据数据/%s"%(n[0]))0 }+ a! ~2 q' q" ~) v4 T( x' P
4 g1 X# s; z. g& F. N/ [" R
执行后自动巡检python脚本) n7 ]% h3 y, a7 |( W
shell运维脚本#!/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/binsource /etc/profile[ $(id -u) -gt 0 ] && echo "请用root用户执行此脚本!" && exit 1centosVersion=$(awk '{print $(NF-1)}' /etc/redhat-release)VERSION="2017.08.22"#日志相关PROGPATH=`echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'`[ -f $PROGPATH ] && PROGPATH="."LOGPATH="$PROGPATH/log"[ -e $LOGPATH ] || mkdir $LOGPATHRESULTFILE="$LOGPATH/HostDailyCheck-$IPADDR-`date +%Y%m%d`.txt"#定义报表的全局变量report_DateTime=""    #日期 okreport_Hostname=""    #主机名 okreport_OSRelease=""    #发行版本 okreport_Kernel=""    #内核 okreport_Language=""    #语言/编码 okreport_LastReboot=""    #最近启动时间 okreport_Uptime=""    #运行时间(天) okreport_CPUs=""    #CPU数量 okreport_CPUType=""    #CPU类型 okreport_Arch=""    #CPU架构 okreport_MemTotal=""    #内存总容量(MB) okreport_MemFree=""    #内存剩余(MB) okreport_MemUsedPercent=""    #内存使用率% okreport_DiskTotal=""    #硬盘总容量(GB) okreport_DiskFree=""    #硬盘剩余(GB) okreport_DiskUsedPercent=""    #硬盘使用率% okreport_InodeTotal=""    #Inode总量 okreport_InodeFree=""    #Inode剩余 okreport_InodeUsedPercent=""    #Inode使用率 okreport_IP=""    #IP地址 okreport_MAC=""    #MAC地址 okreport_Gateway=""    #默认网关 okreport_DNS=""    #DNS okreport_Listen=""    #监听 okreport_Selinux=""    #Selinux okreport_Firewall=""    #防火墙 okreport_USERs=""    #用户 okreport_USEREmptyPassword=""   #空密码用户 okreport_USERTheSameUID=""      #相同ID的用户 ok report_PasswordExpiry=""    #密码过期(天) okreport_RootUser=""    #root用户 okreport_Sudoers=""    #sudo授权  okreport_SSHAuthorized=""    #SSH信任主机 okreport_SSHDProtocolVersion=""    #SSH协议版本 okreport_SSHDPermitRootLogin=""    #允许root远程登录 okreport_DefunctProsess=""    #僵尸进程数量 okreport_SelfInitiatedService=""    #自启动服务数量 okreport_SelfInitiatedProgram=""    #自启动程序数量 okreport_RuningService=""           #运行中服务数  okreport_Crontab=""    #计划任务数 okreport_Syslog=""    #日志服务 okreport_SNMP=""    #SNMP  OKreport_NTP=""    #NTP okreport_JDK=""    #JDK版本 okfunction 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 check(){    version    getSystemStatus    getCpuStatus    getMemStatus    getDiskStatus    getNetworkStatus    getListenStatus    getProcessStatus    getServiceStatus    getAutoStartStatus    getLoginStatus    getCronStatus    getUserStatus    getPasswordStatus    getSudoersStatus    getJDKStatus    getFirewallStatus    getSSHStatus    getSyslogStatus    getSNMPStatus    getNTPStatus    getInstalledStatus}#执行检查并保存检查结果check > $RESULTFILEecho "检查结果:$RESULTFILE"
  R, B, v3 o6 C, Y6 ?- r添加host.info信息192.168.18.30 root root192.168.18.28 root root192.168.18.27 root root192.168.18.29 root root执行python脚本生成文件
 楼主| 发表于 2023-5-2 10:30:07 | 显示全部楼层
添加host.info信息  ]% s; b, o  ?2 I
0 r$ h6 K4 s! y  @; d. L
192.168.2.30 root root
4 t) ~+ v, N- R
% q) I3 `) v+ K5 Z192.168.2.28 root root
' x/ m6 X4 ^9 v- O- @$ k( U
- |, l+ e# c, X/ B' N) p2 M3 J192.168.2.27 root root) L; T$ S1 K0 p9 c/ c
. C8 E% t4 d" T! [0 L1 @/ _+ |- |
192.168.2.29 root root1 ]' b- d" o8 d* Y

2 G) k% Q# N+ n- }; b# e$ Z执行python脚本生成文件
 楼主| 发表于 2023-5-2 10:30:08 | 显示全部楼层
#!/bin/bash#主机信息每日巡检
, j& a- G: f8 {, X$ {- c3 i. y# n9 iIPADDR=$(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/binsource /etc/profile/ U% d( m; U; r  r
[ $(id -u) -gt 0 ] && echo "请用root用户执行此脚本!" && exit 1centosVersion=$(awk '{print $(NF-1)}' /etc/redhat-release)VERSION="2017.08.22", J! P- e" a! K5 l
#日志相关PROGPATH=`echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'`[ -f $PROGPATH ] && PROGPATH="."LOGPATH="$PROGPATH/log"[ -e $LOGPATH ] || mkdir $LOGPATHRESULTFILE="$LOGPATH/HostDailyCheck-$IPADDR-`date +%Y%m%d`.txt"
4 u4 Q* n3 T" Y1 o: r1 C' w* k& b: C( l, g6 \* x8 x: @
#定义报表的全局变量report_DateTime=""    #日期 okreport_Hostname=""    #主机名 okreport_OSRelease=""    #发行版本 okreport_Kernel=""    #内核 okreport_Language=""    #语言/编码 okreport_LastReboot=""    #最近启动时间 okreport_Uptime=""    #运行时间(天) okreport_CPUs=""    #CPU数量 okreport_CPUType=""    #CPU类型 okreport_Arch=""    #CPU架构 okreport_MemTotal=""    #内存总容量(MB) okreport_MemFree=""    #内存剩余(MB) okreport_MemUsedPercent=""    #内存使用率% okreport_DiskTotal=""    #硬盘总容量(GB) okreport_DiskFree=""    #硬盘剩余(GB) okreport_DiskUsedPercent=""    #硬盘使用率% okreport_InodeTotal=""    #Inode总量 okreport_InodeFree=""    #Inode剩余 okreport_InodeUsedPercent=""    #Inode使用率 okreport_IP=""    #IP地址 okreport_MAC=""    #MAC地址 okreport_Gateway=""    #默认网关 okreport_DNS=""    #DNS okreport_Listen=""    #监听 okreport_Selinux=""    #Selinux okreport_Firewall=""    #防火墙 okreport_USERs=""    #用户 okreport_USEREmptyPassword=""   #空密码用户 okreport_USERTheSameUID=""      #相同ID的用户 ok report_PasswordExpiry=""    #密码过期(天) okreport_RootUser=""    #root用户 okreport_Sudoers=""    #sudo授权  okreport_SSHAuthorized=""    #SSH信任主机 okreport_SSHDProtocolVersion=""    #SSH协议版本 okreport_SSHDPermitRootLogin=""    #允许root远程登录 okreport_DefunctProsess=""    #僵尸进程数量 okreport_SelfInitiatedService=""    #自启动服务数量 okreport_SelfInitiatedProgram=""    #自启动程序数量 okreport_RuningService=""           #运行中服务数  okreport_Crontab=""    #计划任务数 okreport_Syslog=""    #日志服务 okreport_SNMP=""    #SNMP  OKreport_NTP=""    #NTP okreport_JDK=""    #JDK版本 okfunction version(){    echo ""    echo ""    echo "系统巡检脚本:Version $VERSION"}
( F( ]& O2 Y* V' Rfunction 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架构}
% {8 F4 B7 `) y, Kfunction 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}}")""%"   #内存使用率%}
+ N4 E8 u6 h/ ?7 W; g7 ]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使用率%7 I& ^, j2 n. R$ y* ^
}. x% `7 [/ E; _9 O! F) W
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"
7 R: ~/ g; e/ b; ~, ^' |8 b6 R! ?+ S}
3 s$ D- E+ n1 k. J% P1 cfunction 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"
1 ~& n/ U! {' I2 Q}4 o6 }. A  }0 g* f' m4 U8 r' A

4 `& _  E8 m! j/ P5 z( wfunction getAutoStartStatus(){    echo ""    echo ""    echo "############################ 自启动检查 ##########################"    conf=$(grep -v "^#" /etc/rc.d/rc.local| sed '/^$/d')    echo "$conf"    #报表信息    report_SelfInitiatedProgram="$(echo $conf | wc -l)"    #自启动程序数量}
1 t& u. u- @$ q' q8 {: Lfunction getLoginStatus(){    echo ""    echo ""    echo "############################ 登录检查 ############################"    last | head}
$ c! S  \; S5 sfunction 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}1 D) B0 f& T) u! E+ u$ Y3 [4 R7 e0 W
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)"}: y; L% n$ }+ G4 r# V$ H8 S
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 小时前"}! i! W' u; t6 B( u) _
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
  G9 U, v3 j) M0 y! Z) k}/ y! Z  e: ]- \, v, l& `8 E' {
function getUserStatus(){    echo ""    echo ""    echo "############################ 用户检查 ############################"    #/etc/passwd 最后修改时间    pwdfile="$(cat /etc/passwd)"    Modify=$(stat /etc/passwd | grep Modify | tr '.' ' ' | awk '{print $2,$3}')
% C/ E' _8 e, _9 X+ N( [    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/^,//')    #特权用户}
9 d. s2 v* R' W/ H- M4 G2 s% ]# p$ V* A* a
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/^,//')
- @, ]$ n$ a5 ]3 A' p    echo ""    echo "密码策略检查"    echo "------------"    grep -v "#" /etc/login.defs | grep -E "PASS_MAX_DAYS|PASS_MIN_DAYS|PASS_MIN_LEN|PASS_WARN_AGE"& [* d9 b4 @% M0 O* X4 N) d4 A" r
% h; E( S! @& B" F- X8 C
}% ~4 \# h+ l0 A1 z+ _
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)"}
5 s7 J/ _  `' T" }function getInstalledStatus(){    echo ""    echo ""    echo "############################ 软件检查 ############################"    rpm -qa --last | head | column -t }0 _: l0 x" [6 G. z# B
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)"}
: F! ^: n- B1 f: r' Vfunction 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"}
, E1 t; }  U7 h* d) b) ]2 e& Efunction 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)"}
( O) |( n& K8 H8 p  Q
/ D3 O% n1 s1 H3 H! G6 b
. c* e8 D' V6 `/ xfunction 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"}
7 U! p! i, X9 L9 v$ Lfunction 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)    done6 ]' i+ }! K) {
    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"- t  U9 r* T- _4 P2 Q5 H- G  w
    echo ""    echo "/etc/ssh/sshd_config"    echo "--------------------"    cat /etc/ssh/sshd_config | grep -v "^#" | sed '/^$/d'
. m; U2 i! b* t$ _5 i    #报表信息    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)"}
2 S0 ?* d1 {* p0 E; ?- k; R( N( R; G2 P. C/ O8 `! [3 S
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}; }( j3 o2 I3 j7 m
function check(){    version    getSystemStatus    getCpuStatus    getMemStatus    getDiskStatus    getNetworkStatus    getListenStatus    getProcessStatus    getServiceStatus    getAutoStartStatus    getLoginStatus    getCronStatus    getUserStatus    getPasswordStatus    getSudoersStatus    getJDKStatus    getFirewallStatus    getSSHStatus    getSyslogStatus    getSNMPStatus    getNTPStatus    getInstalledStatus}* D5 E5 I- u2 a% S0 b; A; ^9 ?

# C( X" P7 a+ V: p8 }#执行检查并保存检查结果check > $RESULTFILE5 h5 v* n9 V3 k/ @- f" Q
echo "检查结果:$RESULTFILE"
, d' ]7 O/ U5 y) G8 y6 J9 Q' p1 X! }2 Z) N6 E. B
您需要登录后才可以回帖 登录 | 开始注册

本版积分规则

关闭

站长推荐上一条 /4 下一条

北京云银创陇科技有限公司以云计算运维,代码开发

QQ|返回首页|Archiver|小黑屋|易陆发现技术论坛 ( 蜀ICP备2026014127号-1 )点击这里给我发消息

GMT+8, 2026-4-8 20:19 , Processed in 0.059721 second(s), 22 queries .

Powered by Discuz! X3.4 Licensed

© 2012-2025 Discuz! Team.

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