Linux
    Linux 系统日常巡检脚本,巡检内容包含了,磁盘,内存 cpu 进程 文件更改 用户登录等一系列的操作,直接用就行了。报告以邮件发送到邮箱 在log下生成巡检报告。

    1. #!/bin/bash
    2. # @Author: HanWei
    3. # @Date: 2020-03-16 09:56:57
    4. # @Last Modified by: HanWei
    5. # @Last Modified time: 2020-03-16 11:06:31
    6. # @E-mail: han_wei_95@163.com
    7. #!/bin/bash
    8. #主机信息每日巡检
    9. IPADDR=$(ifconfig eth0|grep 'inet addr'|awk -F '[ :]' '{print $13}')
    10. #环境变量PATH没设好,在cron里执行时有很多命令会找不到
    11. export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
    12. source /etc/profile
    13. [ $(id -u) -gt 0 ] && echo "请用root用户执行此脚本!" && exit 1
    14. centosVersion=$(awk '{print $(NF-1)}' /etc/redhat-release)
    15. VERSION="2020-03-16"
    16. #日志相关
    17. PROGPATH=`echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'`
    18. [ -f $PROGPATH ] && PROGPATH="."
    19. LOGPATH="$PROGPATH/log"
    20. [ -e $LOGPATH ] || mkdir $LOGPATH
    21. RESULTFILE="$LOGPATH/HostDailyCheck-$IPADDR-`date +%Y%m%d`.txt"
    22. #定义报表的全局变量
    23. report_DateTime="" #日期 ok
    24. report_Hostname="" #主机名 ok
    25. report_OSRelease="" #发行版本 ok
    26. report_Kernel="" #内核 ok
    27. report_Language="" #语言/编码 ok
    28. report_LastReboot="" #最近启动时间 ok
    29. report_Uptime="" #运行时间(天) ok
    30. report_CPUs="" #CPU数量 ok
    31. report_CPUType="" #CPU类型 ok
    32. report_Arch="" #CPU架构 ok
    33. report_MemTotal="" #内存总容量(MB) ok
    34. report_MemFree="" #内存剩余(MB) ok
    35. report_MemUsedPercent="" #内存使用率% ok
    36. report_DiskTotal="" #硬盘总容量(GB) ok
    37. report_DiskFree="" #硬盘剩余(GB) ok
    38. report_DiskUsedPercent="" #硬盘使用率% ok
    39. report_InodeTotal="" #Inode总量 ok
    40. report_InodeFree="" #Inode剩余 ok
    41. report_InodeUsedPercent="" #Inode使用率 ok
    42. report_IP="" #IP地址 ok
    43. report_MAC="" #MAC地址 ok
    44. report_Gateway="" #默认网关 ok
    45. report_DNS="" #DNS ok
    46. report_Listen="" #监听 ok
    47. report_Selinux="" #Selinux ok
    48. report_Firewall="" #防火墙 ok
    49. report_USERs="" #用户 ok
    50. report_USEREmptyPassword="" #空密码用户 ok
    51. report_USERTheSameUID="" #相同ID的用户 ok
    52. report_PasswordExpiry="" #密码过期(天) ok
    53. report_RootUser="" #root用户 ok
    54. report_Sudoers="" #sudo授权 ok
    55. report_SSHAuthorized="" #SSH信任主机 ok
    56. report_SSHDProtocolVersion="" #SSH协议版本 ok
    57. report_SSHDPermitRootLogin="" #允许root远程登录 ok
    58. report_DefunctProsess="" #僵尸进程数量 ok
    59. report_SelfInitiatedService="" #自启动服务数量 ok
    60. report_SelfInitiatedProgram="" #自启动程序数量 ok
    61. report_RuningService="" #运行中服务数 ok
    62. report_Crontab="" #计划任务数 ok
    63. report_Syslog="" #日志服务 ok
    64. report_SNMP="" #SNMP OK
    65. report_NTP="" #NTP ok
    66. report_JDK="" #JDK版本 ok
    67. function version(){
    68. echo ""
    69. echo ""
    70. echo "系统巡检脚本:Version $VERSION"
    71. }
    72. function getCpuStatus(){
    73. echo ""
    74. echo ""
    75. echo "############################ CPU检查 #############################"
    76. Physical_CPUs=$(grep "physical id" /proc/cpuinfo| sort | uniq | wc -l)
    77. Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l)
    78. CPU_Kernels=$(grep "cores" /proc/cpuinfo|uniq| awk -F ': ' '{print $2}')
    79. CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq)
    80. CPU_Arch=$(uname -m)
    81. echo "物理CPU个数:$Physical_CPUs"
    82. echo "逻辑CPU个数:$Virt_CPUs"
    83. echo "每CPU核心数:$CPU_Kernels"
    84. echo " CPU型号:$CPU_Type"
    85. echo " CPU架构:$CPU_Arch"
    86. #报表信息
    87. report_CPUs=$Virt_CPUs #CPU数量
    88. report_CPUType=$CPU_Type #CPU类型
    89. report_Arch=$CPU_Arch #CPU架构
    90. }
    91. function getMemStatus(){
    92. echo ""
    93. echo ""
    94. echo "############################ 内存检查 ############################"
    95. if [[ $centosVersion < 7 ]];then
    96. free -mo
    97. else
    98. free -h
    99. fi
    100. #报表信息
    101. MemTotal=$(grep MemTotal /proc/meminfo| awk '{print $2}') #KB
    102. MemFree=$(grep MemFree /proc/meminfo| awk '{print $2}') #KB
    103. let MemUsed=MemTotal-MemFree
    104. MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}")
    105. report_MemTotal="$((MemTotal/1024))""MB" #内存总容量(MB)
    106. report_MemFree="$((MemFree/1024))""MB" #内存剩余(MB)
    107. report_MemUsedPercent="$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}")""%" #内存使用率%
    108. }
    109. function getDiskStatus(){
    110. echo ""
    111. echo ""
    112. echo "############################ 磁盘检查 ############################"
    113. df -hiP | sed 's/Mounted on/Mounted/'> /tmp/inode
    114. df -hTP | sed 's/Mounted on/Mounted/'> /tmp/disk
    115. join /tmp/disk /tmp/inode | awk '{print $1,$2,"|",$3,$4,$5,$6,"|",$8,$9,$10,$11,"|",$12}'| column -t
    116. #报表信息
    117. diskdata=$(df -TP | sed '1d' | awk '$2!="tmpfs"{print}') #KB
    118. disktotal=$(echo "$diskdata" | awk '{total+=$3}END{print total}') #KB
    119. diskused=$(echo "$diskdata" | awk '{total+=$4}END{print total}') #KB
    120. diskfree=$((disktotal-diskused)) #KB
    121. diskusedpercent=$(echo $disktotal $diskused | awk '{if($1==0){printf 100}else{printf "%.2f",$2*100/$1}}')
    122. inodedata=$(df -iTP | sed '1d' | awk '$2!="tmpfs"{print}')
    123. inodetotal=$(echo "$inodedata" | awk '{total+=$3}END{print total}')
    124. inodeused=$(echo "$inodedata" | awk '{total+=$4}END{print total}')
    125. inodefree=$((inodetotal-inodeused))
    126. inodeusedpercent=$(echo $inodetotal $inodeused | awk '{if($1==0){printf 100}else{printf "%.2f",$2*100/$1}}')
    127. report_DiskTotal=$((disktotal/1024/1024))"GB" #硬盘总容量(GB)
    128. report_DiskFree=$((diskfree/1024/1024))"GB" #硬盘剩余(GB)
    129. report_DiskUsedPercent="$diskusedpercent""%" #硬盘使用率%
    130. report_InodeTotal=$((inodetotal/1000))"K" #Inode总量
    131. report_InodeFree=$((inodefree/1000))"K" #Inode剩余
    132. report_InodeUsedPercent="$inodeusedpercent""%" #Inode使用率%
    133. }
    134. function getSystemStatus(){
    135. echo ""
    136. echo ""
    137. echo "############################ 系统检查 ############################"
    138. if [ -e /etc/sysconfig/i18n ];then
    139. default_LANG="$(grep "LANG=" /etc/sysconfig/i18n | grep -v "^#" | awk -F '"' '{print $2}')"
    140. else
    141. default_LANG=$LANG
    142. fi
    143. export LANG="en_US.UTF-8"
    144. Release=$(cat /etc/redhat-release 2>/dev/null)
    145. Kernel=$(uname -r)
    146. OS=$(uname -o)
    147. Hostname=$(uname -n)
    148. SELinux=$(/usr/sbin/sestatus | grep "SELinux status: " | awk '{print $3}')
    149. LastReboot=$(who -b | awk '{print $3,$4}')
    150. uptime=$(uptime | sed 's/.*up \([^,]*\), .*/\1/')
    151. echo " 系统:$OS"
    152. echo " 发行版本:$Release"
    153. echo " 内核:$Kernel"
    154. echo " 主机名:$Hostname"
    155. echo " SELinux:$SELinux"
    156. echo "语言/编码:$default_LANG"
    157. echo " 当前时间:$(date +'%F %T')"
    158. echo " 最后启动:$LastReboot"
    159. echo " 运行时间:$uptime"
    160. #报表信息
    161. report_DateTime=$(date +"%F %T") #日期
    162. report_Hostname="$Hostname" #主机名
    163. report_OSRelease="$Release" #发行版本
    164. report_Kernel="$Kernel" #内核
    165. report_Language="$default_LANG" #语言/编码
    166. report_LastReboot="$LastReboot" #最近启动时间
    167. report_Uptime="$uptime" #运行时间(天)
    168. report_Selinux="$SELinux"
    169. export LANG="$default_LANG"
    170. }
    171. function getServiceStatus(){
    172. echo ""
    173. echo ""
    174. echo "############################ 服务检查 ############################"
    175. echo ""
    176. if [[ $centosVersion > 7 ]];then
    177. conf=$(systemctl list-unit-files --type=service --state=enabled --no-pager | grep "enabled")
    178. process=$(systemctl list-units --type=service --state=running --no-pager | grep ".service")
    179. #报表信息
    180. report_SelfInitiatedService="$(echo "$conf" | wc -l)" #自启动服务数量
    181. report_RuningService="$(echo "$process" | wc -l)" #运行中服务数量
    182. else
    183. conf=$(/sbin/chkconfig | grep -E ":on|:启用")
    184. process=$(/sbin/service --status-all 2>/dev/null | grep -E "is running|正在运行")
    185. #报表信息
    186. report_SelfInitiatedService="$(echo "$conf" | wc -l)" #自启动服务数量
    187. report_RuningService="$(echo "$process" | wc -l)" #运行中服务数量
    188. fi
    189. echo "服务配置"
    190. echo "--------"
    191. echo "$conf" | column -t
    192. echo ""
    193. echo "正在运行的服务"
    194. echo "--------------"
    195. echo "$process"
    196. }
    197. function getAutoStartStatus(){
    198. echo ""
    199. echo ""
    200. echo "############################ 自启动检查 ##########################"
    201. conf=$(grep -v "^#" /etc/rc.d/rc.local| sed '/^$/d')
    202. echo "$conf"
    203. #报表信息
    204. report_SelfInitiatedProgram="$(echo $conf | wc -l)" #自启动程序数量
    205. }
    206. function getLoginStatus(){
    207. echo ""
    208. echo ""
    209. echo "############################ 登录检查 ############################"
    210. last | head
    211. }
    212. function getNetworkStatus(){
    213. echo ""
    214. echo ""
    215. echo "############################ 网络检查 ############################"
    216. if [[ $centosVersion < 7 ]];then
    217. /sbin/ifconfig -a | grep -v packets | grep -v collisions | grep -v inet6
    218. else
    219. #ip a
    220. 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
    221. fi
    222. GATEWAY=$(ip route | grep default | awk '{print $3}')
    223. DNS=$(grep nameserver /etc/resolv.conf| grep -v "#" | awk '{print $2}' | tr '\n' ',' | sed 's/,$//')
    224. echo ""
    225. echo "网关:$GATEWAY "
    226. echo " DNS:$DNS"
    227. #报表信息
    228. IP=$(ip -f inet addr | grep -v 127.0.0.1 | grep inet | awk '{print $NF,$2}' | tr '\n' ',' | sed 's/,$//')
    229. MAC=$(ip link | grep -v "LOOPBACK\|loopback" | awk '{print $2}' | sed 'N;s/\n//' | tr '\n' ',' | sed 's/,$//')
    230. report_IP="$IP" #IP地址
    231. report_MAC=$MAC #MAC地址
    232. report_Gateway="$GATEWAY" #默认网关
    233. report_DNS="$DNS" #DNS
    234. }
    235. function getListenStatus(){
    236. echo ""
    237. echo ""
    238. echo "############################ 监听检查 ############################"
    239. TCPListen=$(ss -ntul | column -t)
    240. echo "$TCPListen"
    241. #报表信息
    242. report_Listen="$(echo "$TCPListen"| sed '1d' | awk '/tcp/ {print $5}' | awk -F: '{print $NF}' | sort | uniq | wc -l)"
    243. }
    244. function getCronStatus(){
    245. echo ""
    246. echo ""
    247. echo "############################ 计划任务检查 ########################"
    248. Crontab=0
    249. for shell in $(grep -v "/sbin/nologin" /etc/shells);do
    250. for user in $(grep "$shell" /etc/passwd| awk -F: '{print $1}');do
    251. crontab -l -u $user >/dev/null 2>&1
    252. status=$?
    253. if [ $status -eq 0 ];then
    254. echo "$user"
    255. echo "--------"
    256. crontab -l -u $user
    257. let Crontab=Crontab+$(crontab -l -u $user | wc -l)
    258. echo ""
    259. fi
    260. done
    261. done
    262. #计划任务
    263. find /etc/cron* -type f | xargs -i ls -l {} | column -t
    264. let Crontab=Crontab+$(find /etc/cron* -type f | wc -l)
    265. #报表信息
    266. report_Crontab="$Crontab" #计划任务数
    267. }
    268. function getHowLongAgo(){
    269. # 计算一个时间戳离现在有多久了
    270. datetime="$*"
    271. [ -z "$datetime" ] && echo "错误的参数:getHowLongAgo() $*"
    272. Timestamp=$(date +%s -d "$datetime") #转化为时间戳
    273. Now_Timestamp=$(date +%s)
    274. Difference_Timestamp=$(($Now_Timestamp-$Timestamp))
    275. days=0;hours=0;minutes=0;
    276. sec_in_day=$((60*60*24));
    277. sec_in_hour=$((60*60));
    278. sec_in_minute=60
    279. while (( $(($Difference_Timestamp-$sec_in_day)) > 1 ))
    280. do
    281. let Difference_Timestamp=Difference_Timestamp-sec_in_day
    282. let days++
    283. done
    284. while (( $(($Difference_Timestamp-$sec_in_hour)) > 1 ))
    285. do
    286. let Difference_Timestamp=Difference_Timestamp-sec_in_hour
    287. let hours++
    288. done
    289. echo "$days 天 $hours 小时前"
    290. }
    291. function getUserLastLogin(){
    292. # 获取用户最近一次登录的时间,含年份
    293. # 很遗憾last命令不支持显示年份,只有"last -t YYYYMMDDHHMMSS"表示某个时间之间的登录,我
    294. # 们只能用最笨的方法了,对比今天之前和今年元旦之前(或者去年之前和前年之前……)某个用户
    295. # 登录次数,如果登录统计次数有变化,则说明最近一次登录是今年。
    296. username=$1
    297. : ${username:="`whoami`"}
    298. thisYear=$(date +%Y)
    299. oldesYear=$(last | tail -n1 | awk '{print $NF}')
    300. while(( $thisYear >= $oldesYear));do
    301. loginBeforeToday=$(last $username | grep $username | wc -l)
    302. loginBeforeNewYearsDayOfThisYear=$(last $username -t $thisYear"0101000000" | grep $username | wc -l)
    303. if [ $loginBeforeToday -eq 0 ];then
    304. echo "从未登录过"
    305. break
    306. elif [ $loginBeforeToday -gt $loginBeforeNewYearsDayOfThisYear ];then
    307. lastDateTime=$(last -i $username | head -n1 | awk '{for(i=4;i<(NF-2);i++)printf"%s ",$i}')" $thisYear" #格式如: Sat Nov 2 20:33 2015
    308. lastDateTime=$(date "+%Y-%m-%d %H:%M:%S" -d "$lastDateTime")
    309. echo "$lastDateTime"
    310. break
    311. else
    312. thisYear=$((thisYear-1))
    313. fi
    314. done
    315. }
    316. function getUserStatus(){
    317. echo ""
    318. echo ""
    319. echo "############################ 用户检查 ############################"
    320. #/etc/passwd 最后修改时间
    321. pwdfile="$(cat /etc/passwd)"
    322. Modify=$(stat /etc/passwd | grep Modify | tr '.' ' ' | awk '{print $2,$3}')
    323. echo "/etc/passwd 最后修改时间:$Modify ($(getHowLongAgo $Modify))"
    324. echo ""
    325. echo "特权用户"
    326. echo "--------"
    327. RootUser=""
    328. for user in $(echo "$pwdfile" | awk -F: '{print $1}');do
    329. if [ $(id -u $user) -eq 0 ];then
    330. echo "$user"
    331. RootUser="$RootUser,$user"
    332. fi
    333. done
    334. echo ""
    335. echo "用户列表"
    336. echo "--------"
    337. USERs=0
    338. echo "$(
    339. echo "用户名 UID GID HOME SHELL 最后一次登录"
    340. for shell in $(grep -v "/sbin/nologin" /etc/shells);do
    341. for username in $(grep "$shell" /etc/passwd| awk -F: '{print $1}');do
    342. userLastLogin="$(getUserLastLogin $username)"
    343. echo "$pwdfile" | grep -w "$username" |grep -w "$shell"| awk -F: -v lastlogin="$(echo "$userLastLogin" | tr ' ' '_')" '{print $1,$3,$4,$6,$7,lastlogin}'
    344. done
    345. let USERs=USERs+$(echo "$pwdfile" | grep "$shell"| wc -l)
    346. done
    347. )" | column -t
    348. echo ""
    349. echo "空密码用户"
    350. echo "----------"
    351. USEREmptyPassword=""
    352. for shell in $(grep -v "/sbin/nologin" /etc/shells);do
    353. for user in $(echo "$pwdfile" | grep "$shell" | cut -d: -f1);do
    354. r=$(awk -F: '$2=="!!"{print $1}' /etc/shadow | grep -w $user)
    355. if [ ! -z $r ];then
    356. echo $r
    357. USEREmptyPassword="$USEREmptyPassword,"$r
    358. fi
    359. done
    360. done
    361. echo ""
    362. echo "相同ID的用户"
    363. echo "------------"
    364. USERTheSameUID=""
    365. UIDs=$(cut -d: -f3 /etc/passwd | sort | uniq -c | awk '$1>1{print $2}')
    366. for uid in $UIDs;do
    367. echo -n "$uid";
    368. USERTheSameUID="$uid"
    369. r=$(awk -F: 'ORS="";$3=='"$uid"'{print ":",$1}' /etc/passwd)
    370. echo "$r"
    371. echo ""
    372. USERTheSameUID="$USERTheSameUID $r,"
    373. done
    374. #报表信息
    375. report_USERs="$USERs" #用户
    376. report_USEREmptyPassword=$(echo $USEREmptyPassword | sed 's/^,//')
    377. report_USERTheSameUID=$(echo $USERTheSameUID | sed 's/,$//')
    378. report_RootUser=$(echo $RootUser | sed 's/^,//') #特权用户
    379. }
    380. function getPasswordStatus {
    381. echo ""
    382. echo ""
    383. echo "############################ 密码检查 ############################"
    384. pwdfile="$(cat /etc/passwd)"
    385. echo ""
    386. echo "密码过期检查"
    387. echo "------------"
    388. result=""
    389. for shell in $(grep -v "/sbin/nologin" /etc/shells);do
    390. for user in $(echo "$pwdfile" | grep "$shell" | cut -d: -f1);do
    391. get_expiry_date=$(/usr/bin/chage -l $user | grep 'Password expires' | cut -d: -f2)
    392. if [[ $get_expiry_date = ' never' || $get_expiry_date = 'never' ]];then
    393. printf "%-15s 永不过期\n" $user
    394. result="$result,$user:never"
    395. else
    396. password_expiry_date=$(date -d "$get_expiry_date" "+%s")
    397. current_date=$(date "+%s")
    398. diff=$(($password_expiry_date-$current_date))
    399. let DAYS=$(($diff/(60*60*24)))
    400. printf "%-15s %s天后过期\n" $user $DAYS
    401. result="$result,$user:$DAYS days"
    402. fi
    403. done
    404. done
    405. report_PasswordExpiry=$(echo $result | sed 's/^,//')
    406. echo ""
    407. echo "密码策略检查"
    408. echo "------------"
    409. grep -v "#" /etc/login.defs | grep -E "PASS_MAX_DAYS|PASS_MIN_DAYS|PASS_MIN_LEN|PASS_WARN_AGE"
    410. }
    411. function getSudoersStatus(){
    412. echo ""
    413. echo ""
    414. echo "############################ Sudoers检查 #########################"
    415. conf=$(grep -v "^#" /etc/sudoers| grep -v "^Defaults" | sed '/^$/d')
    416. echo "$conf"
    417. echo ""
    418. #报表信息
    419. report_Sudoers="$(echo $conf | wc -l)"
    420. }
    421. function getInstalledStatus(){
    422. echo ""
    423. echo ""
    424. echo "############################ 软件检查 ############################"
    425. rpm -qa --last | head | column -t
    426. }
    427. function getProcessStatus(){
    428. echo ""
    429. echo ""
    430. echo "############################ 进程检查 ############################"
    431. if [ $(ps -ef | grep defunct | grep -v grep | wc -l) -ge 1 ];then
    432. echo ""
    433. echo "僵尸进程";
    434. echo "--------"
    435. ps -ef | head -n1
    436. ps -ef | grep defunct | grep -v grep
    437. fi
    438. echo ""
    439. echo "内存占用TOP10"
    440. echo "-------------"
    441. echo -e "PID %MEM RSS COMMAND
    442. $(ps aux | awk '{print $2, $4, $6, $11}' | sort -k3rn | head -n 10 )"| column -t
    443. echo ""
    444. echo "CPU占用TOP10"
    445. echo "------------"
    446. top b -n1 | head -17 | tail -11
    447. #报表信息
    448. report_DefunctProsess="$(ps -ef | grep defunct | grep -v grep|wc -l)"
    449. }
    450. function getJDKStatus(){
    451. echo ""
    452. echo ""
    453. echo "############################ JDK检查 #############################"
    454. java -version 2>/dev/null
    455. if [ $? -eq 0 ];then
    456. java -version 2>&1
    457. fi
    458. echo "JAVA_HOME=\"$JAVA_HOME\""
    459. #报表信息
    460. report_JDK="$(java -version 2>&1 | grep version | awk '{print $1,$3}' | tr -d '"')"
    461. }
    462. function getSyslogStatus(){
    463. echo ""
    464. echo ""
    465. echo "############################ syslog检查 ##########################"
    466. echo "服务状态:$(getState rsyslog)"
    467. echo ""
    468. echo "/etc/rsyslog.conf"
    469. echo "-----------------"
    470. cat /etc/rsyslog.conf 2>/dev/null | grep -v "^#" | grep -v "^\\$" | sed '/^$/d' | column -t
    471. #报表信息
    472. report_Syslog="$(getState rsyslog)"
    473. }
    474. function getFirewallStatus(){
    475. echo ""
    476. echo ""
    477. echo "############################ 防火墙检查 ##########################"
    478. #防火墙状态,策略等
    479. if [[ $centosVersion < 7 ]];then
    480. /etc/init.d/iptables status >/dev/null 2>&1
    481. status=$?
    482. if [ $status -eq 0 ];then
    483. s="active"
    484. elif [ $status -eq 3 ];then
    485. s="inactive"
    486. elif [ $status -eq 4 ];then
    487. s="permission denied"
    488. else
    489. s="unknown"
    490. fi
    491. else
    492. s="$(getState iptables)"
    493. fi
    494. echo "iptables: $s"
    495. echo ""
    496. echo "/etc/sysconfig/iptables"
    497. echo "-----------------------"
    498. cat /etc/sysconfig/iptables 2>/dev/null
    499. #报表信息
    500. report_Firewall="$s"
    501. }
    502. function getSNMPStatus(){
    503. #SNMP服务状态,配置等
    504. echo ""
    505. echo ""
    506. echo "############################ SNMP检查 ############################"
    507. status="$(getState snmpd)"
    508. echo "服务状态:$status"
    509. echo ""
    510. if [ -e /etc/snmp/snmpd.conf ];then
    511. echo "/etc/snmp/snmpd.conf"
    512. echo "--------------------"
    513. cat /etc/snmp/snmpd.conf 2>/dev/null | grep -v "^#" | sed '/^$/d'
    514. fi
    515. #报表信息
    516. report_SNMP="$(getState snmpd)"
    517. }
    518. function getState(){
    519. if [[ $centosVersion < 7 ]];then
    520. if [ -e "/etc/init.d/$1" ];then
    521. if [ `/etc/init.d/$1 status 2>/dev/null | grep -E "is running|正在运行" | wc -l` -ge 1 ];then
    522. r="active"
    523. else
    524. r="inactive"
    525. fi
    526. else
    527. r="unknown"
    528. fi
    529. else
    530. #CentOS 7+
    531. r="$(systemctl is-active $1 2>&1)"
    532. fi
    533. echo "$r"
    534. }
    535. function getSSHStatus(){
    536. #SSHD服务状态,配置,受信任主机等
    537. echo ""
    538. echo ""
    539. echo "############################ SSH检查 #############################"
    540. #检查受信任主机
    541. pwdfile="$(cat /etc/passwd)"
    542. echo "服务状态:$(getState sshd)"
    543. Protocol_Version=$(cat /etc/ssh/sshd_config | grep Protocol | awk '{print $2}')
    544. echo "SSH协议版本:$Protocol_Version"
    545. echo ""
    546. echo "信任主机"
    547. echo "--------"
    548. authorized=0
    549. for user in $(echo "$pwdfile" | grep /bin/bash | awk -F: '{print $1}');do
    550. authorize_file=$(echo "$pwdfile" | grep -w $user | awk -F: '{printf $6"/.ssh/authorized_keys"}')
    551. authorized_host=$(cat $authorize_file 2>/dev/null | awk '{print $3}' | tr '\n' ',' | sed 's/,$//')
    552. if [ ! -z $authorized_host ];then
    553. echo "$user 授权 \"$authorized_host\" 无密码访问"
    554. fi
    555. let authorized=authorized+$(cat $authorize_file 2>/dev/null | awk '{print $3}'|wc -l)
    556. done
    557. echo ""
    558. echo "是否允许ROOT远程登录"
    559. echo "--------------------"
    560. config=$(cat /etc/ssh/sshd_config | grep PermitRootLogin)
    561. firstChar=${config:0:1}
    562. if [ $firstChar == "#" ];then
    563. PermitRootLogin="yes" #默认是允许ROOT远程登录的
    564. else
    565. PermitRootLogin=$(echo $config | awk '{print $2}')
    566. fi
    567. echo "PermitRootLogin $PermitRootLogin"
    568. echo ""
    569. echo "/etc/ssh/sshd_config"
    570. echo "--------------------"
    571. cat /etc/ssh/sshd_config | grep -v "^#" | sed '/^$/d'
    572. #报表信息
    573. report_SSHAuthorized="$authorized" #SSH信任主机
    574. report_SSHDProtocolVersion="$Protocol_Version" #SSH协议版本
    575. report_SSHDPermitRootLogin="$PermitRootLogin" #允许root远程登录
    576. }
    577. function getNTPStatus(){
    578. #NTP服务状态,当前时间,配置等
    579. echo ""
    580. echo ""
    581. echo "############################ NTP检查 #############################"
    582. if [ -e /etc/ntp.conf ];then
    583. echo "服务状态:$(getState ntpd)"
    584. echo ""
    585. echo "/etc/ntp.conf"
    586. echo "-------------"
    587. cat /etc/ntp.conf 2>/dev/null | grep -v "^#" | sed '/^$/d'
    588. fi
    589. #报表信息
    590. report_NTP="$(getState ntpd)"
    591. }
    592. function uploadHostDailyCheckReport(){
    593. json="{
    594. \"DateTime\":\"$report_DateTime\",
    595. \"Hostname\":\"$report_Hostname\",
    596. \"OSRelease\":\"$report_OSRelease\",
    597. \"Kernel\":\"$report_Kernel\",
    598. \"Language\":\"$report_Language\",
    599. \"LastReboot\":\"$report_LastReboot\",
    600. \"Uptime\":\"$report_Uptime\",
    601. \"CPUs\":\"$report_CPUs\",
    602. \"CPUType\":\"$report_CPUType\",
    603. \"Arch\":\"$report_Arch\",
    604. \"MemTotal\":\"$report_MemTotal\",
    605. \"MemFree\":\"$report_MemFree\",
    606. \"MemUsedPercent\":\"$report_MemUsedPercent\",
    607. \"DiskTotal\":\"$report_DiskTotal\",
    608. \"DiskFree\":\"$report_DiskFree\",
    609. \"DiskUsedPercent\":\"$report_DiskUsedPercent\",
    610. \"InodeTotal\":\"$report_InodeTotal\",
    611. \"InodeFree\":\"$report_InodeFree\",
    612. \"InodeUsedPercent\":\"$report_InodeUsedPercent\",
    613. \"IP\":\"$report_IP\",
    614. \"MAC\":\"$report_MAC\",
    615. \"Gateway\":\"$report_Gateway\",
    616. \"DNS\":\"$report_DNS\",
    617. \"Listen\":\"$report_Listen\",
    618. \"Selinux\":\"$report_Selinux\",
    619. \"Firewall\":\"$report_Firewall\",
    620. \"USERs\":\"$report_USERs\",
    621. \"USEREmptyPassword\":\"$report_USEREmptyPassword\",
    622. \"USERTheSameUID\":\"$report_USERTheSameUID\",
    623. \"PasswordExpiry\":\"$report_PasswordExpiry\",
    624. \"RootUser\":\"$report_RootUser\",
    625. \"Sudoers\":\"$report_Sudoers\",
    626. \"SSHAuthorized\":\"$report_SSHAuthorized\",
    627. \"SSHDProtocolVersion\":\"$report_SSHDProtocolVersion\",
    628. \"SSHDPermitRootLogin\":\"$report_SSHDPermitRootLogin\",
    629. \"DefunctProsess\":\"$report_DefunctProsess\",
    630. \"SelfInitiatedService\":\"$report_SelfInitiatedService\",
    631. \"SelfInitiatedProgram\":\"$report_SelfInitiatedProgram\",
    632. \"RuningService\":\"$report_RuningService\",
    633. \"Crontab\":\"$report_Crontab\",
    634. \"Syslog\":\"$report_Syslog\",
    635. \"SNMP\":\"$report_SNMP\",
    636. \"NTP\":\"$report_NTP\",
    637. \"JDK\":\"$report_JDK\"
    638. }"
    639. #echo "$json"
    640. curl -l -H "Content-type: application/json" -X POST -d "$json" "$uploadHostDailyCheckReportApi" 2>/dev/null
    641. }
    642. function getchage_file_24h()
    643. {
    644. echo "############################ 文件检查 #############################"
    645. check2=$(find / -name '*.sh' -mtime -1)
    646. check21=$(find / -name '*.asp' -mtime -1)
    647. check22=$(find / -name '*.php' -mtime -1)
    648. check23=$(find / -name '*.aspx' -mtime -1)
    649. check24=$(find / -name '*.jsp' -mtime -1)
    650. check25=$(find / -name '*.html' -mtime -1)
    651. check26=$(find / -name '*.htm' -mtime -1)
    652. check9=$(find / -name core -exec ls -l {} \;)
    653. check10=$(cat /etc/crontab)
    654. check12=$(ls -alt /usr/bin | head -10)
    655. cat <<EOF
    656. ############################查看所有被修改过的文件返回最近24小时内的############################
    657. ${check2}
    658. ${check21}
    659. ${check22}
    660. ${check23}
    661. ${check24}
    662. ${check25}
    663. ${check26}
    664. ${line}
    665. ############################检查定时文件的完整性############################
    666. ${check10}
    667. ${line}
    668. ############################查看系统命令是否被替换############################
    669. ${check12}
    670. ${line}
    671. EOF
    672. }
    673. function check(){
    674. version
    675. getSystemStatus
    676. getCpuStatus
    677. getMemStatus
    678. getDiskStatus
    679. getNetworkStatus
    680. getListenStatus
    681. getProcessStatus
    682. getServiceStatus
    683. getAutoStartStatus
    684. getLoginStatus
    685. getCronStatus
    686. getUserStatus
    687. getPasswordStatus
    688. getSudoersStatus
    689. getJDKStatus
    690. getFirewallStatus
    691. getSSHStatus
    692. getSyslogStatus
    693. getSNMPStatus
    694. getNTPStatus
    695. getInstalledStatus
    696. getchage_file_24h
    697. }
    698. #执行检查并保存检查结果
    699. check > $RESULTFILE
    700. echo "检查结果:$RESULTFILE"
    701. echo -e "`date "+%Y-%m-%d %H:%M:%S"` 阿里云PHP企业平台巡检报告" | mail -a $RESULTFILE -s "阿里云PHP企业平台巡检报告" h@163.com