HostDailyCheck.sh

系統巡檢腳本:Version 2016.08.09

############################ 系統檢查 ############################
系統:GNU/Linux
發行版本:CentOS Linux release 7.2.1511 (Core)
內核:3.10.0-327.el7.x86_64
主機名:localhost.localdomain
SELinux:enabled
語言/編碼:en_US.UTF-8
當前時間:2016-08-10 01:16:38
最后啟動:2016-08-09 00:40
運行時間:1 day

############################ CPU檢查 #############################
物理CPU個數:1
邏輯CPU個數:1
每CPU核心數:1
CPU型號:Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz
CPU架構:x86_64

############################ 內存檢查 ############################
total used free shared buff/cache available
Mem: 1.9G 138M 343M 8.6M 1.5G 1.6G
Swap: 2.0G 0B 2.0G

############################ 磁盤檢查 ############################
Filesystem Type | Size Used Avail Use% | Inodes IUsed IFree IUse% | Mounted
/dev/mapper/centos-root xfs | 18G 1.6G 16G 9% | 18M 24K 18M 1% | /
devtmpfs devtmpfs | 983M 0 983M 0% | 246K 381 246K 1% | /dev
tmpfs tmpfs | 993M 0 993M 0% | 249K 1 249K 1% | /dev/shm
tmpfs tmpfs | 993M 0 993M 0% | 249K 485 248K 1% | /run
tmpfs tmpfs | 993M 0 993M 0% | 249K 13 249K 1% | /sys/fs/cgroup
tmpfs tmpfs | 993M 8.6M 985M 1% | 249K 1 249K 1% | /dev/shm
tmpfs tmpfs | 993M 8.6M 985M 1% | 249K 485 248K 1% | /run
tmpfs tmpfs | 993M 8.6M 985M 1% | 249K 13 249K 1% | /sys/fs/cgroup
tmpfs tmpfs | 993M 0 993M 0% | 249K 1 249K 1% | /dev/shm
tmpfs tmpfs | 993M 0 993M 0% | 249K 485 248K 1% | /run
tmpfs tmpfs | 993M 0 993M 0% | 249K 13 249K 1% | /sys/fs/cgroup
/dev/sda1 xfs | 497M 107M 391M 22% | 500K 329 500K 1% | /boot
tmpfs tmpfs | 199M 0 199M 0% | 249K 1 249K 1% | /run/user/0
/dev/loop0 iso9660 | 603M 603M 0 100% | 0 0 0 - | /var/ftp/pub

############################ 網絡檢查 ############################
eno16777736: 192.168.100.63/24 192.168.100.68/24

網關:192.168.100.2
DNS:192.168.100.2

############################ 監聽檢查 ############################
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
udp UNCONN 0 0 *:14034 :
udp UNCONN 0 0 :46966 :
udp UNCONN 0 0 :67 :
udp UNCONN 0 0 :68 :
udp UNCONN 0 0 :69 :
udp UNCONN 0 0 :::46966 :::

udp UNCONN 0 0 :::32833 :::

tcp LISTEN 0 128 :22 :
tcp LISTEN 0 100 127.0.0.1:25 :
tcp LISTEN 0 32 :::21 :::

tcp LISTEN 0 128 :::22 :::

tcp LISTEN 0 100 ::1:25 :::

############################ 進程檢查 ############################

內存占用TOP10

PID %MEM RSS COMMAND
10069 0.9 18612 /usr/sbin/dhcpd
1212 0.8 16396 /usr/bin/python
10036 0.7 15800 /sbin/dhclient
992 0.5 11992 /usr/lib/polkit-1/polkitd
962 0.4 8232 /usr/sbin/NetworkManager
1 0.3 7208 /usr/lib/systemd/systemd
969 0.2 5320 /usr/sbin/rsyslogd
10196 0.2 5076 sshd:
10175 0.2 5072 sshd:
810 0.2 4996 /usr/lib/systemd/systemd-journald

CPU占用TOP10

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
10638 root 20 0 146272 2164 1352 R 6.2 0.1 0:00.01 top
1 root 20 0 44496 7208 2612 S 0.0 0.4 0:03.83 systemd
2 root 20 0 0 0 0 S 0.0 0.0 0:00.04 kthreadd
3 root 20 0 0 0 0 S 0.0 0.0 0:00.67 ksoftirqd/0
7 root rt 0 0 0 0 S 0.0 0.0 0:00.00 migration/0
8 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcu_bh
9 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcuob/0
10 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcuob/1
11 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcuob/2
12 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcuob/3

############################ 服務檢查 ############################

服務配置

auditd.service enabled
crond.service enabled
dbus-org.freedesktop.NetworkManager.service enabled
dbus-org.freedesktop.nm-dispatcher.service enabled
dhcpd.service enabled
getty@.service enabled
irqbalance.service enabled
lvm2-monitor.service enabled
microcode.service enabled
NetworkManager-dispatcher.service enabled
NetworkManager.service enabled
postfix.service enabled
rsyslog.service enabled
sshd.service enabled
systemd-readahead-collect.service enabled
systemd-readahead-drop.service enabled
systemd-readahead-replay.service enabled
tuned.service enabled
vsftpd.service enabled
xinetd.service enabled

正在運行的服務

auditd.service loaded active running Security Auditing Service
crond.service loaded active running Command Scheduler
dbus.service loaded active running D-Bus System Message Bus
dhcpd.service loaded active running DHCPv4 Server Daemon
getty@tty1.service loaded active running Getty on tty1
lvm2-lvmetad.service loaded active running LVM2 metadata daemon
NetworkManager.service loaded active running Network Manager
polkit.service loaded active running Authorization Manager
postfix.service loaded active running Postfix Mail Transport Agent
rsyslog.service loaded active running System Logging Service
sshd.service loaded active running OpenSSH server daemon
systemd-journald.service loaded active running Journal Service
systemd-logind.service loaded active running Login Service
systemd-udevd.service loaded active running udev Kernel Device Manager
tuned.service loaded active running Dynamic System Tuning Daemon
vsftpd.service loaded active running Vsftpd ftp daemon
wpa_supplicant.service loaded active running WPA Supplicant daemon
xinetd.service loaded active running Xinetd A Powerful Replacement For Inetd

############################ 自啟動檢查 ##########################
touch /var/lock/subsys/local

############################ 登錄檢查 ############################
root pts/0 192.168.100.1 Tue Aug 9 23:47 still logged in
root pts/1 192.168.100.1 Tue Aug 9 23:46 still logged in
root pts/0 192.168.100.1 Tue Aug 9 23:45 - 23:46 (00:00)
root pts/0 192.168.100.1 Tue Aug 9 16:46 - 23:45 (06:59)
root tty1 Tue Aug 9 00:40 still logged in
reboot system boot 3.10.0-327.el7.x Tue Aug 9 00:40 - 01:16 (1+00:35)

wtmp begins Tue Aug 9 00:40:43 2016

############################ 計劃任務檢查 ########################
-rw-r--r--. 1 root root 128 Jul 27 2015 /etc/cron.d/0hourly
-rwx------. 1 root root 180 Jul 31 2013 /etc/cron.daily/logrotate
-rwxr-xr-x. 1 root root 332 Dec 3 2015 /etc/cron.daily/0yum-daily.cron
-rwxr-xr-x. 1 root root 618 Mar 18 2014 /etc/cron.daily/man-db.cron
-rw-------. 1 root root 0 Jul 27 2015 /etc/cron.deny
-rwxr-xr-x. 1 root root 362 Dec 3 2015 /etc/cron.hourly/0yum-hourly.cron
-rwxr-xr-x. 1 root root 392 Jul 27 2015 /etc/cron.hourly/0anacron
-rw-r--r--. 1 root root 451 Jun 10 2014 /etc/crontab

############################ 用戶檢查 ############################
/etc/passwd 最后修改時間:2016-08-09 16:47:13 (0 天 8 小時前)

特權用戶

root

用戶列表

用戶名 UID GID HOME SHELL 最后一次登錄
root 0 0 /root /bin/bash 2016-08-09_23:47:00

空密碼用戶

相同ID的用戶

############################ 密碼檢查 ############################

密碼過期檢查

root 永不過期

密碼策略檢查

PASS_MAX_DAYS 99999
PASS_MIN_DAYS 0
PASS_MIN_LEN 5
PASS_WARN_AGE 7

############################ Sudoers檢查 #########################
root ALL=(ALL) ALL
%wheel ALL=(ALL) ALL

############################ JDK檢查 #############################
JAVA_HOME=""

############################ 防火墻檢查 ##########################
iptables: inactive

/etc/sysconfig/iptables

############################ SSH檢查 #############################
服務狀態:active
SSH協議版本:2

信任主機

是否允許ROOT遠程登錄

PermitRootLogin yes

/etc/ssh/sshd_config

HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
SyslogFacility AUTHPRIV
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication yes
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
UsePAM yes
X11Forwarding yes
UsePrivilegeSeparation sandbox # Default for new installations.
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
Subsystem sftp /usr/libexec/openssh/sftp-server

############################ syslog檢查 ##########################
服務狀態:active

/etc/rsyslog.conf

.info;mail.none;authpriv.none;cron.none /var/log/messages
authpriv.
/var/log/secure
mail.* -/var/log/maillog
cron.* /var/log/cron
.emerg :omusrmsg:
uucp,news.crit /var/log/spooler
local7.* /var/log/boot.log

############################ SNMP檢查 ############################
服務狀態:unknown

############################ NTP檢查 #############################

############################ 軟件檢查 ############################
telnet-0.17-59.el7.x86_64 Tue 09 Aug 2016 11:43:37 PM CST
syslinux-tftpboot-4.05-12.el7.x86_64 Tue 09 Aug 2016 05:26:19 PM CST
syslinux-4.05-12.el7.x86_64 Tue 09 Aug 2016 05:26:19 PM CST
mtools-4.0.18-5.el7.x86_64 Tue 09 Aug 2016 05:26:18 PM CST
ftp-0.17-66.el7.x86_64 Tue 09 Aug 2016 05:05:47 PM CST
tftp-server-5.2-12.el7.x86_64 Tue 09 Aug 2016 04:54:30 PM CST
tftp-5.2-12.el7.x86_64 Tue 09 Aug 2016 04:54:30 PM CST
xinetd-2.3.15-12.el7.x86_64 Tue 09 Aug 2016 04:54:24 PM CST
vsftpd-3.0.2-11.el7_2.x86_64 Tue 09 Aug 2016 04:50:36 PM CST
gpg-pubkey-f4a80eb5-53a7ff4b Tue 09 Aug 2016 04:47:13 PM CST

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290

腳本代碼

!/bin/bash

主機信息每日巡檢

version 2016.08.09

當前腳本適用于CentOS/RedHat 6.X、7.X

環境變量PATH沒設好,在cron里執行時有很多命令會找不到

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

[ $(id -u) -gt 0 ] && echo "請用root用戶執行此腳本!" && exit 1

uploadHostDailyCheckApi="http://10.0.0.1:8080/api/uploadHostDailyCheck"

uploadHostDailyCheckReportApi="http://10.0.0.1:8080/api/uploadHostDailyCheckReport"

centosVersion=$(awk '{print $(NF-1)}' /etc/redhat-release)
VERSION="2016.08.09"

日志相關

PROGPATH=echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'
[ -f $PROGPATH ] && PROGPATH="."
LOGPATH="$PROGPATH/log"
[ -e $LOGPATH ] || mkdir $LOGPATH
RESULTFILE="$LOGPATH/HostDailyCheck-hostname-date +%Y%m%d.txt"

定義報表的全局變量

report_DateTime="" #日期 ok
report_Hostname="" #主機名 ok
report_OSRelease="" #發行版本 ok
report_Kernel="" #內核 ok
report_Language="" #語言/編碼 ok
report_LastReboot="" #最近啟動時間 ok
report_Uptime="" #運行時間(天) ok
report_CPUs="" #CPU數量 ok
report_CPUType="" #CPU類型 ok
report_Arch="" #CPU架構 ok
report_MemTotal="" #內存總容量(MB) ok
report_MemFree="" #內存剩余(MB) ok
report_MemUsedPercent="" #內存使用率% ok
report_DiskTotal="" #硬盤總容量(GB) ok
report_DiskFree="" #硬盤剩余(GB) ok
report_DiskUsedPercent="" #硬盤使用率% ok
report_InodeTotal="" #Inode總量 ok
report_InodeFree="" #Inode剩余 ok
report_InodeUsedPercent="" #Inode使用率 ok
report_IP="" #IP地址 ok
report_MAC="" #MAC地址 ok
report_Gateway="" #默認網關 ok
report_DNS="" #DNS ok
report_Listen="" #監聽 ok
report_Selinux="" #Selinux ok
report_Firewall="" #防火墻 ok
report_USERs="" #用戶 ok
report_USEREmptyPassword="" #空密碼用戶 ok
report_USERTheSameUID="" #相同ID的用戶 ok
report_PasswordExpiry="" #密碼過期(天) ok
report_RootUser="" #root用戶 ok
report_Sudoers="" #sudo授權 ok
report_SSHAuthorized="" #SSH信任主機 ok
report_SSHDProtocolVersion="" #SSH協議版本 ok
report_SSHDPermitRootLogin="" #允許root遠程登錄 ok
report_DefunctProsess="" #僵尸進程數量 ok
report_SelfInitiatedService="" #自啟動服務數量 ok
report_SelfInitiatedProgram="" #自啟動程序數量 ok
report_RuningService="" #運行中服務數 ok
report_Crontab="" #計劃任務數 ok
report_Syslog="" #日志服務 ok
report_SNMP="" #SNMP OK
report_NTP="" #NTP ok
report_JDK="" #JDK版本 ok
function version(){
echo ""
echo ""
echo "系統巡檢腳本:Version $VERSION"
}

function getCpuStatus(){
echo ""
echo ""
echo "############################ CPU檢查 #############################"
Physical_CPUs=$(grep "physical id" /proc/cpuinfo| sort | uniq | wc -l)
Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l)
CPU_Kernels=$(grep "cores" /proc/cpuinfo|uniq| awk -F ': ' '{print $2}')
CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq)
CPU_Arch=$(uname -m)
echo "物理CPU個數:$Physical_CPUs"
echo "邏輯CPU個數:$Virt_CPUs"
echo "每CPU核心數:$CPU_Kernels"
echo " CPU型號:$CPU_Type"
echo " CPU架構:$CPU_Arch"
#報表信息
report_CPUs=$Virt_CPUs #CPU數量
report_CPUType=$CPU_Type #CPU類型
report_Arch=$CPU_Arch #CPU架構
}

function getMemStatus(){
echo ""
echo ""
echo "############################ 內存檢查 ############################"
if [[ $centosVersion < 7 ]];then
free -mo
else
free -h
fi
#報表信息
MemTotal=$(grep MemTotal /proc/meminfo| awk '{print $2}') #KB
MemFree=$(grep MemFree /proc/meminfo| awk '{print $2}') #KB
let MemUsed=MemTotal-MemFree
MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf "%.2f",$MemUsed100/$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",$2100/$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=$((606024));
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/(606024)))
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 > $RESULTFILE

echo "檢查結果:$RESULTFILE"

上傳檢查結果的文件

curl -F "filename=@$RESULTFILE" "$uploadHostDailyCheckApi" 2>/dev/null

上傳檢查結果的報表

uploadHostDailyCheckReport 1>/dev/null```

系統巡檢腳本:Version 2016.08.09

############################ 系統檢查 ############################
系統:GNU/Linux
發行版本:CentOS Linux release 7.2.1511 (Core)
內核:3.10.0-327.el7.x86_64
主機名:localhost.localdomain
SELinux:enabled
語言/編碼:en_US.UTF-8
當前時間:2016-08-10 01:16:38
最后啟動:2016-08-09 00:40
運行時間:1 day

############################ CPU檢查 #############################
物理CPU個數:1
邏輯CPU個數:1
每CPU核心數:1
CPU型號:Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz
CPU架構:x86_64

############################ 內存檢查 ############################
total used free shared buff/cache available
Mem: 1.9G 138M 343M 8.6M 1.5G 1.6G
Swap: 2.0G 0B 2.0G

############################ 磁盤檢查 ############################
Filesystem Type | Size Used Avail Use% | Inodes IUsed IFree IUse% | Mounted
/dev/mapper/centos-root xfs | 18G 1.6G 16G 9% | 18M 24K 18M 1% | /
devtmpfs devtmpfs | 983M 0 983M 0% | 246K 381 246K 1% | /dev
tmpfs tmpfs | 993M 0 993M 0% | 249K 1 249K 1% | /dev/shm
tmpfs tmpfs | 993M 0 993M 0% | 249K 485 248K 1% | /run
tmpfs tmpfs | 993M 0 993M 0% | 249K 13 249K 1% | /sys/fs/cgroup
tmpfs tmpfs | 993M 8.6M 985M 1% | 249K 1 249K 1% | /dev/shm
tmpfs tmpfs | 993M 8.6M 985M 1% | 249K 485 248K 1% | /run
tmpfs tmpfs | 993M 8.6M 985M 1% | 249K 13 249K 1% | /sys/fs/cgroup
tmpfs tmpfs | 993M 0 993M 0% | 249K 1 249K 1% | /dev/shm
tmpfs tmpfs | 993M 0 993M 0% | 249K 485 248K 1% | /run
tmpfs tmpfs | 993M 0 993M 0% | 249K 13 249K 1% | /sys/fs/cgroup
/dev/sda1 xfs | 497M 107M 391M 22% | 500K 329 500K 1% | /boot
tmpfs tmpfs | 199M 0 199M 0% | 249K 1 249K 1% | /run/user/0
/dev/loop0 iso9660 | 603M 603M 0 100% | 0 0 0 - | /var/ftp/pub

############################ 網絡檢查 ############################
eno16777736: 192.168.100.63/24 192.168.100.68/24

網關:192.168.100.2
DNS:192.168.100.2

############################ 監聽檢查 ############################
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
udp UNCONN 0 0 *:14034 :
udp UNCONN 0 0 :46966 :
udp UNCONN 0 0 :67 :
udp UNCONN 0 0 :68 :
udp UNCONN 0 0 :69 :
udp UNCONN 0 0 :::46966 :::

udp UNCONN 0 0 :::32833 :::

tcp LISTEN 0 128 :22 :
tcp LISTEN 0 100 127.0.0.1:25 :
tcp LISTEN 0 32 :::21 :::

tcp LISTEN 0 128 :::22 :::

tcp LISTEN 0 100 ::1:25 :::

############################ 進程檢查 ############################

內存占用TOP10

PID %MEM RSS COMMAND
10069 0.9 18612 /usr/sbin/dhcpd
1212 0.8 16396 /usr/bin/python
10036 0.7 15800 /sbin/dhclient
992 0.5 11992 /usr/lib/polkit-1/polkitd
962 0.4 8232 /usr/sbin/NetworkManager
1 0.3 7208 /usr/lib/systemd/systemd
969 0.2 5320 /usr/sbin/rsyslogd
10196 0.2 5076 sshd:
10175 0.2 5072 sshd:
810 0.2 4996 /usr/lib/systemd/systemd-journald

CPU占用TOP10

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
10638 root 20 0 146272 2164 1352 R 6.2 0.1 0:00.01 top
1 root 20 0 44496 7208 2612 S 0.0 0.4 0:03.83 systemd
2 root 20 0 0 0 0 S 0.0 0.0 0:00.04 kthreadd
3 root 20 0 0 0 0 S 0.0 0.0 0:00.67 ksoftirqd/0
7 root rt 0 0 0 0 S 0.0 0.0 0:00.00 migration/0
8 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcu_bh
9 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcuob/0
10 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcuob/1
11 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcuob/2
12 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcuob/3

############################ 服務檢查 ############################

服務配置

auditd.service enabled
crond.service enabled
dbus-org.freedesktop.NetworkManager.service enabled
dbus-org.freedesktop.nm-dispatcher.service enabled
dhcpd.service enabled
getty@.service enabled
irqbalance.service enabled
lvm2-monitor.service enabled
microcode.service enabled
NetworkManager-dispatcher.service enabled
NetworkManager.service enabled
postfix.service enabled
rsyslog.service enabled
sshd.service enabled
systemd-readahead-collect.service enabled
systemd-readahead-drop.service enabled
systemd-readahead-replay.service enabled
tuned.service enabled
vsftpd.service enabled
xinetd.service enabled

正在運行的服務

auditd.service loaded active running Security Auditing Service
crond.service loaded active running Command Scheduler
dbus.service loaded active running D-Bus System Message Bus
dhcpd.service loaded active running DHCPv4 Server Daemon
getty@tty1.service loaded active running Getty on tty1
lvm2-lvmetad.service loaded active running LVM2 metadata daemon
NetworkManager.service loaded active running Network Manager
polkit.service loaded active running Authorization Manager
postfix.service loaded active running Postfix Mail Transport Agent
rsyslog.service loaded active running System Logging Service
sshd.service loaded active running OpenSSH server daemon
systemd-journald.service loaded active running Journal Service
systemd-logind.service loaded active running Login Service
systemd-udevd.service loaded active running udev Kernel Device Manager
tuned.service loaded active running Dynamic System Tuning Daemon
vsftpd.service loaded active running Vsftpd ftp daemon
wpa_supplicant.service loaded active running WPA Supplicant daemon
xinetd.service loaded active running Xinetd A Powerful Replacement For Inetd

############################ 自啟動檢查 ##########################
touch /var/lock/subsys/local

############################ 登錄檢查 ############################
root pts/0 192.168.100.1 Tue Aug 9 23:47 still logged in
root pts/1 192.168.100.1 Tue Aug 9 23:46 still logged in
root pts/0 192.168.100.1 Tue Aug 9 23:45 - 23:46 (00:00)
root pts/0 192.168.100.1 Tue Aug 9 16:46 - 23:45 (06:59)
root tty1 Tue Aug 9 00:40 still logged in
reboot system boot 3.10.0-327.el7.x Tue Aug 9 00:40 - 01:16 (1+00:35)

wtmp begins Tue Aug 9 00:40:43 2016

############################ 計劃任務檢查 ########################
-rw-r--r--. 1 root root 128 Jul 27 2015 /etc/cron.d/0hourly
-rwx------. 1 root root 180 Jul 31 2013 /etc/cron.daily/logrotate
-rwxr-xr-x. 1 root root 332 Dec 3 2015 /etc/cron.daily/0yum-daily.cron
-rwxr-xr-x. 1 root root 618 Mar 18 2014 /etc/cron.daily/man-db.cron
-rw-------. 1 root root 0 Jul 27 2015 /etc/cron.deny
-rwxr-xr-x. 1 root root 362 Dec 3 2015 /etc/cron.hourly/0yum-hourly.cron
-rwxr-xr-x. 1 root root 392 Jul 27 2015 /etc/cron.hourly/0anacron
-rw-r--r--. 1 root root 451 Jun 10 2014 /etc/crontab

############################ 用戶檢查 ############################
/etc/passwd 最后修改時間:2016-08-09 16:47:13 (0 天 8 小時前)

特權用戶

root

用戶列表

用戶名 UID GID HOME SHELL 最后一次登錄
root 0 0 /root /bin/bash 2016-08-09_23:47:00

空密碼用戶

相同ID的用戶

############################ 密碼檢查 ############################

密碼過期檢查

root 永不過期

密碼策略檢查

PASS_MAX_DAYS 99999
PASS_MIN_DAYS 0
PASS_MIN_LEN 5
PASS_WARN_AGE 7

############################ Sudoers檢查 #########################
root ALL=(ALL) ALL
%wheel ALL=(ALL) ALL

############################ JDK檢查 #############################
JAVA_HOME=""

############################ 防火墻檢查 ##########################
iptables: inactive

/etc/sysconfig/iptables

############################ SSH檢查 #############################
服務狀態:active
SSH協議版本:2

信任主機

是否允許ROOT遠程登錄

PermitRootLogin yes

/etc/ssh/sshd_config

HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
SyslogFacility AUTHPRIV
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication yes
ChallengeResponseAuthentication no
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
UsePAM yes
X11Forwarding yes
UsePrivilegeSeparation sandbox # Default for new installations.
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
Subsystem sftp /usr/libexec/openssh/sftp-server

############################ syslog檢查 ##########################
服務狀態:active

/etc/rsyslog.conf

.info;mail.none;authpriv.none;cron.none /var/log/messages
authpriv.
/var/log/secure
mail.* -/var/log/maillog
cron.* /var/log/cron
.emerg :omusrmsg:
uucp,news.crit /var/log/spooler
local7.* /var/log/boot.log

############################ SNMP檢查 ############################
服務狀態:unknown

############################ NTP檢查 #############################

############################ 軟件檢查 ############################
telnet-0.17-59.el7.x86_64 Tue 09 Aug 2016 11:43:37 PM CST
syslinux-tftpboot-4.05-12.el7.x86_64 Tue 09 Aug 2016 05:26:19 PM CST
syslinux-4.05-12.el7.x86_64 Tue 09 Aug 2016 05:26:19 PM CST
mtools-4.0.18-5.el7.x86_64 Tue 09 Aug 2016 05:26:18 PM CST
ftp-0.17-66.el7.x86_64 Tue 09 Aug 2016 05:05:47 PM CST
tftp-server-5.2-12.el7.x86_64 Tue 09 Aug 2016 04:54:30 PM CST
tftp-5.2-12.el7.x86_64 Tue 09 Aug 2016 04:54:30 PM CST
xinetd-2.3.15-12.el7.x86_64 Tue 09 Aug 2016 04:54:24 PM CST
vsftpd-3.0.2-11.el7_2.x86_64 Tue 09 Aug 2016 04:50:36 PM CST
gpg-pubkey-f4a80eb5-53a7ff4b Tue 09 Aug 2016 04:47:13 PM CST


## <a name="t4"></a>腳本代碼

!/bin/bash

主機信息每日巡檢

version 2016.08.09

當前腳本適用于CentOS/RedHat 6.X、7.X

環境變量PATH沒設好,在cron里執行時有很多命令會找不到

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

[ $(id -u) -gt 0 ] && echo "請用root用戶執行此腳本!" && exit 1

uploadHostDailyCheckApi="http://10.0.0.1:8080/api/uploadHostDailyCheck"

uploadHostDailyCheckReportApi="http://10.0.0.1:8080/api/uploadHostDailyCheckReport"

centosVersion=$(awk '{print $(NF-1)}' /etc/redhat-release)
VERSION="2016.08.09"

日志相關

PROGPATH=echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'
[ -f $PROGPATH ] && PROGPATH="."
LOGPATH="$PROGPATH/log"
[ -e $LOGPATH ] || mkdir $LOGPATH
RESULTFILE="$LOGPATH/HostDailyCheck-hostname-date +%Y%m%d.txt"

定義報表的全局變量

report_DateTime="" #日期 ok
report_Hostname="" #主機名 ok
report_OSRelease="" #發行版本 ok
report_Kernel="" #內核 ok
report_Language="" #語言/編碼 ok
report_LastReboot="" #最近啟動時間 ok
report_Uptime="" #運行時間(天) ok
report_CPUs="" #CPU數量 ok
report_CPUType="" #CPU類型 ok
report_Arch="" #CPU架構 ok
report_MemTotal="" #內存總容量(MB) ok
report_MemFree="" #內存剩余(MB) ok
report_MemUsedPercent="" #內存使用率% ok
report_DiskTotal="" #硬盤總容量(GB) ok
report_DiskFree="" #硬盤剩余(GB) ok
report_DiskUsedPercent="" #硬盤使用率% ok
report_InodeTotal="" #Inode總量 ok
report_InodeFree="" #Inode剩余 ok
report_InodeUsedPercent="" #Inode使用率 ok
report_IP="" #IP地址 ok
report_MAC="" #MAC地址 ok
report_Gateway="" #默認網關 ok
report_DNS="" #DNS ok
report_Listen="" #監聽 ok
report_Selinux="" #Selinux ok
report_Firewall="" #防火墻 ok
report_USERs="" #用戶 ok
report_USEREmptyPassword="" #空密碼用戶 ok
report_USERTheSameUID="" #相同ID的用戶 ok
report_PasswordExpiry="" #密碼過期(天) ok
report_RootUser="" #root用戶 ok
report_Sudoers="" #sudo授權 ok
report_SSHAuthorized="" #SSH信任主機 ok
report_SSHDProtocolVersion="" #SSH協議版本 ok
report_SSHDPermitRootLogin="" #允許root遠程登錄 ok
report_DefunctProsess="" #僵尸進程數量 ok
report_SelfInitiatedService="" #自啟動服務數量 ok
report_SelfInitiatedProgram="" #自啟動程序數量 ok
report_RuningService="" #運行中服務數 ok
report_Crontab="" #計劃任務數 ok
report_Syslog="" #日志服務 ok
report_SNMP="" #SNMP OK
report_NTP="" #NTP ok
report_JDK="" #JDK版本 ok
function version(){
echo ""
echo ""
echo "系統巡檢腳本:Version $VERSION"
}

function getCpuStatus(){
echo ""
echo ""
echo "############################ CPU檢查 #############################"
Physical_CPUs=$(grep "physical id" /proc/cpuinfo| sort | uniq | wc -l)
Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l)
CPU_Kernels=$(grep "cores" /proc/cpuinfo|uniq| awk -F ': ' '{print $2}')
CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq)
CPU_Arch=$(uname -m)
echo "物理CPU個數:$Physical_CPUs"
echo "邏輯CPU個數:$Virt_CPUs"
echo "每CPU核心數:$CPU_Kernels"
echo " CPU型號:$CPU_Type"
echo " CPU架構:$CPU_Arch"
#報表信息
report_CPUs=$Virt_CPUs #CPU數量
report_CPUType=$CPU_Type #CPU類型
report_Arch=$CPU_Arch #CPU架構
}

function getMemStatus(){
echo ""
echo ""
echo "############################ 內存檢查 ############################"
if [[ $centosVersion < 7 ]];then
free -mo
else
free -h
fi
#報表信息
MemTotal=$(grep MemTotal /proc/meminfo| awk '{print $2}') #KB
MemFree=$(grep MemFree /proc/meminfo| awk '{print $2}') #KB
let MemUsed=MemTotal-MemFree
MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf "%.2f",$MemUsed100/$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",$2100/$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=$((606024));
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/(606024)))
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 > $RESULTFILE

echo "檢查結果:$RESULTFILE"

上傳檢查結果的文件

curl -F "filename=@$RESULTFILE" "$uploadHostDailyCheckApi" 2>/dev/null

上傳檢查結果的報表

uploadHostDailyCheckReport 1>/dev/null

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容