Linux 系统日常巡检脚本

Linux 系统日常巡检脚本,巡检内容包含了,磁盘,内存 cpu 进程 文件更改 用户登录等一系列的操作 直接用就行了。

报告以邮件发送到邮箱 在log下生成巡检报告。

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