HOST=localhost
USER=backup
PASS=123.com
BACKUP_DIR=/data/db_backup
DB_LIST=
(
m
y
s
q
l
−
h
(mysql -h
(mysql−hHOST -u
U
S
E
R
−
p
USER -p
USER−pPASS -s -e “show databases;” 2>/dev/null |egrep -v “Database|information_schema|mysql|performance_schema|sys”)
for DB in
D
B
_
L
I
S
T
;
d
o
B
A
C
K
U
P
_
D
B
_
D
I
R
=
DB\_LIST; do BACKUP\_DB\_DIR=
DB_LIST;doBACKUP_DB_DIR=BACKUP_DIR/KaTeX parse error: Expected group after '_' at position 5: {DB}_̲{DATE}
[ ! -d $BACKUP_DB_DIR ] && mkdir -p KaTeX parse error: Expected 'EOF', got '&' at position 17: …ACKUP\_DB\_DIR &̲>/dev/null …(mysql -h
H
O
S
T
−
u
HOST -u
HOST−uUSER -p$PASS -s -e “use $DB;show tables;” 2>/dev/null)
for TABLE in
T
A
B
L
E
_
L
I
S
T
;
d
o
B
A
C
K
U
P
_
N
A
M
E
=
TABLE\_LIST; do BACKUP\_NAME=
TABLE_LIST;doBACKUP_NAME=BACKUP_DB_DIR/
T
A
B
L
E
.
s
q
l
i
f
!
m
y
s
q
l
d
u
m
p
−
h
{TABLE}.sql if ! mysqldump -h
TABLE.sqlif!mysqldump−hHOST -u
U
S
E
R
−
p
USER -p
USER−pPASS $DB $TABLE >
B
A
C
K
U
P
_
N
A
M
E
2
>
/
d
e
v
/
n
u
l
l
;
t
h
e
n
e
c
h
o
"
BACKUP\_NAME 2>/dev/null; then echo "
BACKUP_NAME2>/dev/null;thenecho"BACKUP_NAME 备份失败!"
fi
done
done
## 5、Nginx 访问访问日志按天切割
#!/bin/bash
LOG_DIR=/usr/local/nginx/logs
YESTERDAY_TIME=
(
d
a
t
e
−
d
"
y
e
s
t
e
r
d
a
y
"
+
L
O
G
_
M
O
N
T
H
_
D
I
R
=
(date -d "yesterday" +%F) LOG\_MONTH\_DIR=
(date−d"yesterday"+LOG_MONTH_DIR=LOG_DIR/$(date +“%Y-%m”)
LOG_FILE_LIST=“default.access.log”
for LOG_FILE in $LOG_FILE_LIST; do
[ ! -d $LOG_MONTH_DIR ] && mkdir -p $LOG_MONTH_DIR
mv
L
O
G
_
D
I
R
/
LOG\_DIR/
LOG_DIR/LOG_FILE
L
O
G
_
M
O
N
T
H
_
D
I
R
/
LOG\_MONTH\_DIR/
LOG_MONTH_DIR/{LOG_FILE}_${YESTERDAY_TIME}
done
kill -USR1 $(cat /var/run/nginx.pid)
## 6、Nginx 访问日志分析脚本
#!/bin/bash
日志格式: $remote_addr - r e m o t e _ u s e r [ remote\_user [ remote_user[time_local] “$request” $status b o d y _ b y t e s _ s e n t " body\_bytes\_sent " body_bytes_sent"http_referer" “ h t t p _ u s e r _ a g e n t " " http\_user\_agent" " http_user_agent""http_x_forwarded_for”
LOG_FILE=$1
echo “统计访问最多的10个IP”
awk ‘{a[$1]++}END{print “UV:”,length(a);for(v in a)print v,a[v]}’ $LOG_FILE |sort -k2 -nr |head -10
echo “----------------------”
echo “统计时间段访问最多的IP”
awk ‘$4>=“[01/Dec/2018:13:20:25” && $4<=“[27/Nov/2018:16:20:49”{a[$1]++}END{for(v in a)print v,a[v]}’ $LOG_FILE |sort -k2 -nr|head -10
echo “----------------------”
echo “统计访问最多的10个页面”
awk ‘{a[$7]++}END{print “PV:”,length(a);for(v in a){if(a[v]>10)print v,a[v]}}’ $LOG_FILE |sort -k2 -nr
echo “----------------------”
echo “统计访问页面状态码数量”
awk ‘{a[$7" "$9]++}END{for(v in a){if(a[v]>5)print v,a[v]}}’
## 7、查看网卡实时流量脚本
#!/bin/bash
NIC=
1
e
c
h
o
−
e
"
I
n
−
−
−
−
−
−
O
u
t
"
w
h
i
l
e
t
r
u
e
;
d
o
O
L
D
_
I
N
=
1 echo -e " In ------ Out" while true; do OLD\_IN=
1echo−e"In−−−−−−Out"whiletrue;doOLD_IN=(awk ‘
0
"
′
0~"'
0 "′NIC’“{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲' /proc/net/dev…(awk ‘
0
"
′
0~"'
0 "′NIC’”{print KaTeX parse error: Expected 'EOF', got '}' at position 3: 10}̲' /proc/net/dev…(awk ‘
0
"
′
0~"'
0 "′NIC’“{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲' /proc/net/dev…(awk ‘
0
"
′
0~"'
0 "′NIC’”{print KaTeX parse error: Expected 'EOF', got '}' at position 3: 10}̲' /proc/net/dev…(printf “%.1f%s” "
(
(
(
(((
(((NEW_IN-
O
L
D
_
I
N
)
/
1024
)
)
"
"
K
B
/
s
"
)
O
U
T
=
OLD\_IN)/1024))" "KB/s") OUT=
OLD_IN)/1024))""KB/s")OUT=(printf “%.1f%s” “
(
(
(
(((
(((NEW_OUT-
O
L
D
_
O
U
T
)
/
1024
)
)
"
"
K
B
/
s
"
)
e
c
h
o
"
OLD\_OUT)/1024))" "KB/s") echo "
OLD_OUT)/1024))""KB/s")echo"IN $OUT”
sleep 1
done
## 8、服务器系统配置初始化脚本
#/bin/bash
设置时区并同步时间
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
if ! crontab -l |grep ntpdate &>/dev/null ; then
(echo “* 1 * * * ntpdate time.windows.com >/dev/null 2>&1”;crontab -l) |crontab
fi
禁用selinux
sed -i ‘/SELINUX/{s/permissive/disabled/}’ /etc/selinux/config
关闭防火墙
if egrep “7.[0-9]” /etc/redhat-release &>/dev/null; then
systemctl stop firewalld
systemctl disable firewalld
elif egrep “6.[0-9]” /etc/redhat-release &>/dev/null; then
service iptables stop
chkconfig iptables off
fi
历史命令显示操作时间
if ! grep HISTTIMEFORMAT /etc/bashrc; then
echo ‘export HISTTIMEFORMAT="%F %T whoami
"’ >> /etc/bashrc
fi
SSH超时时间
if ! grep “TMOUT=600” /etc/profile &>/dev/null; then
echo “export TMOUT=600” >> /etc/profile
fi
禁止root远程登录
sed -i ‘s/#PermitRootLogin yes/PermitRootLogin no/’ /etc/ssh/sshd_config
禁止定时任务向发送邮件
sed -i ‘s/^MAILTO=root/MAILTO=“”/’ /etc/crontab
设置最大打开文件数
if ! grep “* soft nofile 65535” /etc/security/limits.conf &>/dev/null; then
cat >> /etc/security/limits.conf << EOF
* soft nofile 65535
* hard nofile 65535
EOF
fi
系统内核优化
cat >> /etc/sysctl.conf << EOF
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_tw_buckets = 20480
net.ipv4.tcp_max_syn_backlog = 20480
net.core.netdev_max_backlog = 262144
net.ipv4.tcp_fin_timeout = 20
EOF
减少SWAP使用
echo “0” > /proc/sys/vm/swappiness
安装系统性能分析工具及其他
yum install gcc make autoconf vim sysstat net-tools iostat if
## 9、监控 100 台服务器磁盘利用率脚本
#!/bin/bash
HOST_INFO=host.info
for IP in $(awk ‘/[#]/{print $1}’
H
O
S
T
_
I
N
F
O
)
;
d
o
U
S
E
R
=
HOST\_INFO); do USER=
HOST_INFO);doUSER=(awk -v ip=$IP ‘ip==$1{print $2}’
H
O
S
T
_
I
N
F
O
)
P
O
R
T
=
HOST\_INFO) PORT=
HOST_INFO)PORT=(awk -v ip=$IP ‘ip==$1{print $3}’ $HOST_INFO)
TMP_FILE=/tmp/disk.tmp
ssh -p $PORT
U
S
E
R
@
USER@
USER@IP ‘df -h’ >
T
M
P
_
F
I
L
E
U
S
E
_
R
A
T
E
_
L
I
S
T
=
TMP\_FILE USE\_RATE\_LIST=
TMP_FILEUSE_RATE_LIST=(awk ‘BEGIN{OFS=“=”}/^/dev/{print $NF,int($5)}’ $TMP_FILE)
for USE_RATE in
U
S
E
_
R
A
T
E
_
L
I
S
T
;
d
o
P
A
R
T
_
N
A
M
E
=
USE\_RATE\_LIST; do PART\_NAME=
USE_RATE_LIST;doPART_NAME={USE_RATE%=*}
USE_RATE=${USE_RATE#*=}
if [ $USE_RATE -ge 80 ]; then
echo “Warning: $PART_NAME Partition usage $USE_RATE%!”
fi
done
done
## 10、linux的CPU占用脚本、内存占用脚本
直接去这篇博客啦
[linux的CPU占用脚本、内存占用脚本和硬盘IO测试代码]( )
## 11、Linux 系统日常巡检脚本
* 这是一个比较正式的脚本,内容有点多,感兴趣的可以研究研究【代码多是因为功能多,别被代码数量吓着了,拆开看其实都不算难】,益处多多。
这个脚本估计也是转发好多次了,全都没有缩进的,直接用是不现实的,需要了解其中代码加上缩进按需使用的话,这个脚本是真不错,而且其中写脚本的思路,也可以多借鉴借鉴,很标准很强大。
* 脚本说明
+ Linux 系统日常巡检脚本,巡检内容包含了,磁盘,内存 cpu 进程 文件更改 用户登录等一系列的操作 直接用就行了。
+ 报告以邮件发送到邮箱 在log下生成巡检报告。
#!/bin/bash
@Author: HanWei
@Date: 2020-03-16 09:56:57
@Last Modified by: HanWei
@Last Modified time: 2020-03-16 11:06:31
@E-mail: han_wei_95@163.com
#!/bin/bash
#主机信息每日巡检
IPADDR=$(ifconfig eth0|grep ‘inet addr’|awk -F ‘[ :]’ ‘{print $13}’)
#环境变量PATH没设好,在cron里执行时有很多命令会找不到
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
source /etc/profile
[ KaTeX parse error: Expected 'EOF', got '&' at position 17: …id -u) -gt 0 ] &̲& echo "请用root用…(awk ‘{print $(NF-1)}’ /etc/redhat-release)
VERSION=“2020-03-16”
#日志相关
PROGPATH=echo $0 | sed -e 's,[\\/][^\\/][^\\/]\*$,,'
[ -f KaTeX parse error: Expected 'EOF', got '&' at position 12: PROGPATH ] &̲& PROGPATH="." …PROGPATH/log"
[ -e $LOGPATH ] || mkdir
L
O
G
P
A
T
H
R
E
S
U
L
T
F
I
L
E
=
"
LOGPATH RESULTFILE="
LOGPATHRESULTFILE="LOGPATH/HostDailyCheck-$IPADDR-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=
(
g
r
e
p
"
p
h
y
s
i
c
a
l
i
d
"
/
p
r
o
c
/
c
p
u
i
n
f
o
∣
s
o
r
t
∣
u
n
i
q
∣
w
c
−
l
)
V
i
r
t
_
C
P
U
s
=
(grep "physical id" /proc/cpuinfo| sort | uniq | wc -l) Virt\_CPUs=
(grep"physicalid"/proc/cpuinfo∣sort∣uniq∣wc−l)Virt_CPUs=(grep “processor” /proc/cpuinfo | wc -l)
CPU_Kernels=$(grep “cores” /proc/cpuinfo|uniq| awk -F ': ’ '{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲') CPU\_Type=(grep “model name” /proc/cpuinfo | awk -F ': ’ '{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲' | sort | uniq…(uname -m)
echo “物理CPU个数:
P
h
y
s
i
c
a
l
_
C
P
U
s
"
e
c
h
o
"
逻辑
C
P
U
个数
:
Physical\_CPUs" echo "逻辑CPU个数:
Physical_CPUs"echo"逻辑CPU个数:Virt_CPUs”
echo “每CPU核心数:
C
P
U
_
K
e
r
n
e
l
s
"
e
c
h
o
"
C
P
U
型号
:
CPU\_Kernels" echo " CPU型号:
CPU_Kernels"echo"CPU型号:CPU_Type”
echo " CPU架构:KaTeX parse error: Expected 'EOF', got '#' at position 12: CPU\_Arch" #̲报表信息 report\_CP…Virt_CPUs #CPU数量
report_CPUType=KaTeX parse error: Expected 'EOF', got '#' at position 11: CPU\_Type #̲CPU类型 report\_A…CPU_Arch #CPU架构
}
function getMemStatus(){
echo “”
echo “”
echo “############################ 内存检查 ############################”
if [[ KaTeX parse error: Expected 'EOF', got '#' at position 52: …lse free -h fi #̲报表信息 MemTotal=(grep MemTotal /proc/meminfo| awk '{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲') #KB MemFree=(grep MemFree /proc/meminfo| awk '{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲') #KB let MemU…(awk “BEGIN {if(KaTeX parse error: Expected group as argument to '\"' at end of input: …rintf \"%.2f\",MemUsed*100/KaTeX parse error: Expected 'EOF', got '}' at position 9: MemTotal}̲}") report\_Mem…((MemTotal/1024))”“MB” #内存总容量(MB)
report_MemFree=“KaTeX parse error: Expected 'EOF', got '#' at position 23: …ee/1024))""MB" #̲内存剩余(MB) report…(awk “BEGIN {if(KaTeX parse error: Expected group as argument to '\"' at end of input: …rintf \"%.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,“|”,KaTeX parse error: Expected 'EOF', got '}' at position 3: 12}̲'| column -t #报…(df -TP | sed ‘1d’ | awk 'KaTeX parse error: Expected 'EOF', got '#' at position 21: …mpfs"{print}') #̲KB disktotal=(echo “$diskdata” | awk '{total+=KaTeX parse error: Expected 'EOF', got '}' at position 2: 3}̲END{print total…(echo “$diskdata” | awk '{total+=KaTeX parse error: Expected 'EOF', got '}' at position 2: 4}̲END{print total…((disktotal-diskused)) #KB
diskusedpercent=$(echo $disktotal $diskused | awk '{if($10){printf 100}else{printf “%.2f”,$2*100/KaTeX parse error: Expected 'EOF', got '}' at position 2: 1}̲}') inodedata=(df -iTP | sed ‘1d’ | awk '
2
!
=
"
t
m
p
f
s
"
p
r
i
n
t
′
)
i
n
o
d
e
t
o
t
a
l
=
2!="tmpfs"{print}') inodetotal=
2!="tmpfs"print′)inodetotal=(echo “$inodedata” | awk '{total+=KaTeX parse error: Expected 'EOF', got '}' at position 2: 3}̲END{print total…(echo “$inodedata” | awk '{total+=KaTeX parse error: Expected 'EOF', got '}' at position 2: 4}̲END{print total…((inodetotal-inodeused))
inodeusedpercent=$(echo $inodetotal $inodeused | awk '{if($10){printf 100}else{printf “%.2f”,$2*100/KaTeX parse error: Expected 'EOF', got '}' at position 2: 1}̲}') report\_Dis…((disktotal/1024/1024))“GB” #硬盘总容量(GB)
report_DiskFree=KaTeX parse error: Expected 'EOF', got '#' at position 28: …024/1024))"GB" #̲硬盘剩余(GB) report…diskusedpercent"“%” #硬盘使用率%
report_InodeTotal=KaTeX parse error: Expected 'EOF', got '#' at position 24: …otal/1000))"K" #̲Inode总量 report\…((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 KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲')" else defaul…LANG
fi
export LANG=“en_US.UTF-8”
Release=
(
c
a
t
/
e
t
c
/
r
e
d
h
a
t
−
r
e
l
e
a
s
e
2
>
/
d
e
v
/
n
u
l
l
)
K
e
r
n
e
l
=
(cat /etc/redhat-release 2>/dev/null) Kernel=
(cat/etc/redhat−release2>/dev/null)Kernel=(uname -r)
OS=
(
u
n
a
m
e
−
o
)
H
o
s
t
n
a
m
e
=
(uname -o) Hostname=
(uname−o)Hostname=(uname -n)
SELinux=$(/usr/sbin/sestatus | grep “SELinux status: " | awk '{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 3}̲') LastReboot=(who -b | awk '{print $3,KaTeX parse error: Expected 'EOF', got '}' at position 2: 4}̲') uptime=(uptime | sed ‘s/.*up ([^,]*), .*/\1/’)
echo " 系统:
O
S
"
e
c
h
o
"
发行版本:
OS" echo " 发行版本:
OS"echo"发行版本:Release”
echo " 内核:
K
e
r
n
e
l
"
e
c
h
o
"
主机名:
Kernel" echo " 主机名:
Kernel"echo"主机名:Hostname"
echo " SELinux:
S
E
L
i
n
u
x
"
e
c
h
o
"
语言
/
编码:
SELinux" echo "语言/编码:
SELinux"echo"语言/编码:default_LANG"
echo " 当前时间:
(
d
a
t
e
+
′
e
c
h
o
"
最后启动:
(date +'%F %T')" echo " 最后启动:
(date+′echo"最后启动:LastReboot"
echo " 运行时间:KaTeX parse error: Expected 'EOF', got '#' at position 9: uptime" #̲报表信息 report\_Da…(date +“%F %T”) #日期
report_Hostname=“KaTeX parse error: Expected 'EOF', got '#' at position 11: Hostname" #̲主机名 report\_OSR…Release” #发行版本
report_Kernel=“KaTeX parse error: Expected 'EOF', got '#' at position 9: Kernel" #̲内核 report\_Lang…default_LANG” #语言/编码
report_LastReboot=“KaTeX parse error: Expected 'EOF', got '#' at position 13: LastReboot" #̲最近启动时间 report\_…uptime” #运行时间(天)
report_Selinux=“
S
E
L
i
n
u
x
"
e
x
p
o
r
t
L
A
N
G
=
"
SELinux" export LANG="
SELinux"exportLANG="default_LANG”
}
function getServiceStatus(){
echo “”
echo “”
echo “############################ 服务检查 ############################”
echo “”
if [[
c
e
n
t
o
s
V
e
r
s
i
o
n
>
7
]
]
;
t
h
e
n
c
o
n
f
=
centosVersion > 7 ]];then conf=
centosVersion>7]];thenconf=(systemctl list-unit-files --type=service --state=enabled --no-pager | grep “enabled”)
process=KaTeX parse error: Expected 'EOF', got '#' at position 84: …ep ".service") #̲报表信息 report\_Se…(echo "KaTeX parse error: Expected 'EOF', got '#' at position 17: …onf" | wc -l)" #̲自启动服务数量 report\…(echo "KaTeX parse error: Expected 'EOF', got '#' at position 20: …ess" | wc -l)" #̲运行中服务数量 else co…(/sbin/chkconfig | grep -E “:on|:启用”)
process=KaTeX parse error: Expected 'EOF', got '#' at position 70: …running|正在运行") #̲报表信息 report\_Se…(echo "KaTeX parse error: Expected 'EOF', got '#' at position 17: …onf" | wc -l)" #̲自启动服务数量 report\…(echo “KaTeX parse error: Expected 'EOF', got '#' at position 20: …ess" | wc -l)" #̲运行中服务数量 fi echo…conf” | column -t
echo “”
echo “正在运行的服务”
echo “--------------”
echo “$process”
}
function getAutoStartStatus(){
echo “”
echo “”
echo “############################ 自启动检查 ##########################”
conf=KaTeX parse error: Expected group after '^' at position 11: (grep -v "^̲#" /etc/rc.d/rc…/d’)
echo “KaTeX parse error: Expected 'EOF', got '#' at position 7: conf" #̲报表信息 report\_Se…(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 KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲' | tr '\n' ' '…(ip route | grep default | awk '{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 3}̲') DNS=(grep nameserver /etc/resolv.conf| grep -v “#” | awk ‘{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲' | tr '\n' ','…//’)
echo “”
echo “网关:
G
A
T
E
W
A
Y
"
e
c
h
o
"
D
N
S
:
GATEWAY " echo " DNS:
GATEWAY"echo"DNS:DNS”
#报表信息
IP=$(ip -f inet addr | grep -v 127.0.0.1 | grep inet | awk ‘{print $NF,KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲' | tr '\n' ','…//’)
MAC=$(ip link | grep -v “LOOPBACK|loopback” | awk ‘{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲' | sed 'N;s/\n…//’)
report_IP="KaTeX parse error: Expected 'EOF', got '#' at position 5: IP" #̲IP地址 report\_MA…MAC #MAC地址
report_Gateway=“KaTeX parse error: Expected 'EOF', got '#' at position 10: GATEWAY" #̲默认网关 report\_DN…DNS” #DNS
}
function getListenStatus(){
echo “”
echo “”
echo “############################ 监听检查 ############################”
TCPListen=
(
s
s
−
n
t
u
l
∣
c
o
l
u
m
n
−
t
)
e
c
h
o
"
(ss -ntul | column -t) echo "
(ss−ntul∣column−t)echo"TCPListen"
#报表信息
report_Listen=“
(
e
c
h
o
"
(echo "
(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
(
g
r
e
p
"
(grep "
(grep"shell" /etc/passwd| awk -F: ‘{print $1}’);do
crontab -l -u KaTeX parse error: Expected 'EOF', got '&' at position 19: …r >/dev/null 2>&̲1 status=?
if [
s
t
a
t
u
s
−
e
q
0
]
;
t
h
e
n
e
c
h
o
"
status -eq 0 ];then echo "
status−eq0];thenecho"user"
echo “--------”
crontab -l -u
u
s
e
r
l
e
t
C
r
o
n
t
a
b
=
C
r
o
n
t
a
b
+
user let Crontab=Crontab+
userletCrontab=Crontab+(crontab -l -u KaTeX parse error: Expected 'EOF', got '#' at position 36: …" fi done done #̲计划任务 find /etc/…(find /etc/cron* -type f | wc -l)
#报表信息
report_Crontab=“$Crontab” #计划任务数
}
function getHowLongAgo(){
计算一个时间戳离现在有多久了
datetime=“KaTeX parse error: Undefined control sequence: \* at position 1: \̲*̲" [ -z "datetime” ] && echo "错误的参数:getHowLongAgo() KaTeX parse error: Undefined control sequence: \* at position 1: \̲*̲" Timestamp=(date +%s -d “KaTeX parse error: Expected 'EOF', got '#' at position 12: datetime") #̲转化为时间戳 Now\_Tim…(date +%s)
Difference_Timestamp=
(
(
((
((Now_Timestamp-
T
i
m
e
s
t
a
m
p
)
)
d
a
y
s
=
0
;
h
o
u
r
s
=
0
;
m
i
n
u
t
e
s
=
0
;
s
e
c
_
i
n
_
d
a
y
=
Timestamp)) days=0;hours=0;minutes=0; sec\_in\_day=
Timestamp))days=0;hours=0;minutes=0;sec_in_day=((60*60*24));
sec_in_hour=$((60*60));
sec_in_minute=60
while ((
(
(
((
((Difference_Timestamp-$sec_in_day)) > 1 ))
do
let Difference_Timestamp=Difference_Timestamp-sec_in_day
let days++
done
while ((
(
(
((
((Difference_Timestamp-
s
e
c
_
i
n
_
h
o
u
r
)
)
>
1
)
)
d
o
l
e
t
D
i
f
f
e
r
e
n
c
e
_
T
i
m
e
s
t
a
m
p
=
D
i
f
f
e
r
e
n
c
e
T
i
m
e
s
t
a
m
p
−
s
e
c
i
n
h
o
u
r
l
e
t
h
o
u
r
s
+
+
d
o
n
e
e
c
h
o
"
sec\_in\_hour)) > 1 )) do let Difference\_Timestamp=Difference_Timestamp-sec_in_hour let hours++ done echo "
sec_in_hour))>1))doletDifference_Timestamp=DifferenceTimestamp−secinhourlethours++doneecho"days 天 $hours 小时前”
}
function getUserLastLogin(){
获取用户最近一次登录的时间,含年份
很遗憾last命令不支持显示年份,只有"last -t YYYYMMDDHHMMSS"表示某个时间之间的登录,我
们只能用最笨的方法了,对比今天之前和今年元旦之前(或者去年之前和前年之前……)某个用户
登录次数,如果登录统计次数有变化,则说明最近一次登录是今年。
-
username=$1
-
u
s
e
r
n
a
m
e
:
=
"
‘
w
h
o
a
m
i
‘
"
t
h
i
s
Y
e
a
r
=
{username:="`whoami`"} thisYear=
username:="‘whoami‘"thisYear=(date +%Y)
oldesYear=$(last | tail -n1 | awk ‘{print $NF}’)
while(( $thisYear >= o l d e s Y e a r ) ) ; d o l o g i n B e f o r e T o d a y = oldesYear));do loginBeforeToday= oldesYear));dologinBeforeToday=(last $username | grep u s e r n a m e ∣ w c − l ) l o g i n B e f o r e N e w Y e a r s D a y O f T h i s Y e a r = username | wc -l) loginBeforeNewYearsDayOfThisYear= username∣wc−l)loginBeforeNewYearsDayOfThisYear=(last $username -t $thisYear"0101000000" | grep $username | wc -l)
if [ $loginBeforeToday -eq 0 ];then
echo “从未登录过”
break
elif [ $loginBeforeToday -gt l o g i n B e f o r e N e w Y e a r s D a y O f T h i s Y e a r ] ; t h e n l a s t D a t e T i m e = loginBeforeNewYearsDayOfThisYear ];then lastDateTime= loginBeforeNewYearsDayOfThisYear];thenlastDateTime=(last -i KaTeX parse error: Expected '}', got 'EOF' at end of input: …++)printf"%s ",i}')" KaTeX parse error: Expected 'EOF', got '#' at position 11: thisYear" #̲格式如: Sat Nov 2 …(date “+%Y-%m-%d %H:%M:%S” -d “ l a s t D a t e T i m e " ) e c h o " lastDateTime") echo " lastDateTime")echo"lastDateTime”
break
else
thisYear=$((thisYear-1))
fi
done
}
function getUserStatus(){
echo “”
echo “”
echo “############################ 用户检查 ############################”
#/etc/passwd 最后修改时间
pwdfile="
(
c
a
t
/
e
t
c
/
p
a
s
s
w
d
)
"
M
o
d
i
f
y
=
(cat /etc/passwd)" Modify=
(cat/etc/passwd)"Modify=(stat /etc/passwd | grep Modify | tr ‘.’ ’ ’ | awk ‘{print $2,$3}’)
echo “/etc/passwd 最后修改时间:
M
o
d
i
f
y
(
Modify (
Modify((getHowLongAgo $Modify))”
echo “”
echo “特权用户”
echo “--------”
RootUser=“”
for user in
(
e
c
h
o
"
(echo "
(echo"pwdfile" | awk -F: ‘{print $1}’);do
if [ $(id -u
u
s
e
r
)
−
e
q
0
]
;
t
h
e
n
e
c
h
o
"
user) -eq 0 ];then echo "
user)−eq0];thenecho"user"
RootUser=“
R
o
o
t
U
s
e
r
,
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
(
g
r
e
p
"
(grep "
(grep"shell” /etc/passwd| awk -F: ‘{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 1}̲');do userLastL…(getUserLastLogin
u
s
e
r
n
a
m
e
)
"
e
c
h
o
"
username)" echo "
username)"echo"pwdfile" | grep -w “
u
s
e
r
n
a
m
e
"
∣
g
r
e
p
−
w
"
username" |grep -w "
username"∣grep−w"shell”| awk -F: -v lastlogin=“
(
e
c
h
o
"
(echo "
(echo"userLastLogin” | tr ’ ’ ‘_’)" ‘{print $1,$3,$4,$6,KaTeX parse error: Expected 'EOF', got '}' at position 12: 7,lastlogin}̲' done let USER…(echo “
p
w
d
f
i
l
e
"
∣
g
r
e
p
"
pwdfile" | grep "
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
(
e
c
h
o
"
(echo "
(echo"pwdfile" | grep “
s
h
e
l
l
"
∣
c
u
t
−
d
:
−
f
1
)
;
d
o
r
=
shell" | cut -d: -f1);do r=
shell"∣cut−d:−f1);dor=(awk -F: '$2==”!!"{print $1}’ /etc/shadow | grep -w $user)
if [ ! -z $r ];then
echo
r
U
S
E
R
E
m
p
t
y
P
a
s
s
w
o
r
d
=
"
r USEREmptyPassword="
rUSEREmptyPassword="USEREmptyPassword,“
r
f
i
d
o
n
e
d
o
n
e
e
c
h
o
"
"
e
c
h
o
"
相同
I
D
的用户
"
e
c
h
o
"
−
−
−
−
−
−
−
−
−
−
−
−
"
U
S
E
R
T
h
e
S
a
m
e
U
I
D
=
"
"
U
I
D
s
=
r fi done done echo "" echo "相同ID的用户" echo "------------" USERTheSameUID="" UIDs=
rfidonedoneecho""echo"相同ID的用户"echo"−−−−−−−−−−−−"USERTheSameUID=""UIDs=(cut -d: -f3 /etc/passwd | sort | uniq -c | awk ‘$1>1{print $2}’)
for uid in
U
I
D
s
;
d
o
e
c
h
o
−
n
"
UIDs;do echo -n "
UIDs;doecho−n"uid”;
USERTheSameUID=“
u
i
d
"
r
=
uid" r=
uid"r=(awk -F: 'ORS=”“;
3
=
=
′
"
3=='"
3==′"uid”’{print “:”,KaTeX parse error: Expected 'EOF', got '}' at position 2: 1}̲' /etc/passwd) …r"
echo “”
USERTheSameUID=“$USERTheSameUID KaTeX parse error: Expected 'EOF', got '#' at position 10: r," done #̲报表信息 report\_US…USERs” #用户
report_USEREmptyPassword=$(echo
U
S
E
R
E
m
p
t
y
P
a
s
s
w
o
r
d
∣
s
e
d
′
s
/
,
/
/
′
)
r
e
p
o
r
t
_
U
S
E
R
T
h
e
S
a
m
e
U
I
D
=
USEREmptyPassword | sed 's/^,//') report\_USERTheSameUID=
USEREmptyPassword∣sed′s/,//′)report_USERTheSameUID=(echo
U
S
E
R
T
h
e
S
a
m
e
U
I
D
∣
s
e
d
′
s
/
,
USERTheSameUID | sed 's/,
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
(
e
c
h
o
"
(echo "
(echo"pwdfile" | grep "
s
h
e
l
l
"
∣
c
u
t
−
d
:
−
f
1
)
;
d
o
g
e
t
_
e
x
p
i
r
y
_
d
a
t
e
=
shell" | cut -d: -f1);do get\_expiry\_date=
shell"∣cut−d:−f1);doget_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”
u
s
e
r
r
e
s
u
l
t
=
"
user result="
userresult="result,
u
s
e
r
:
n
e
v
e
r
"
e
l
s
e
p
a
s
s
w
o
r
d
_
e
x
p
i
r
y
_
d
a
t
e
=
user:never" else password\_expiry\_date=
user:never"elsepassword_expiry_date=(date -d “
g
e
t
_
e
x
p
i
r
y
_
d
a
t
e
"
"
+
c
u
r
r
e
n
t
_
d
a
t
e
=
get\_expiry\_date" "+%s") current\_date=
get_expiry_date""+current_date=(date “+%s”)
diff=
(
(
((
((password_expiry_date-
c
u
r
r
e
n
t
_
d
a
t
e
)
)
l
e
t
D
A
Y
S
=
current\_date)) let DAYS=
current_date))letDAYS=(($diff/(60*60*24)))
printf “%-15s %s天后过期\n” $user
D
A
Y
S
r
e
s
u
l
t
=
"
DAYS result="
DAYSresult="result,
u
s
e
r
:
user:
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=KaTeX parse error: Expected group after '^' at position 11: (grep -v "^̲#" /etc/sudoers…/d’)
echo “KaTeX parse error: Expected 'EOF', got '#' at position 15: conf" echo "" #̲报表信息 report\_Su…(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, KaTeX parse error: Expected 'EOF', got '}' at position 3: 11}̲' | sort -k3rn …(ps -ef | grep defunct | grep -v grep|wc -l)”
}
function getJDKStatus(){
echo “”
echo “”
echo “############################ JDK检查 #############################”
java -version 2>/dev/null
if [ KaTeX parse error: Expected 'EOF', got '&' at position 32: …ava -version 2>&̲1 fi echo "JAVA…JAVA_HOME""
#报表信息
report_JDK=“$(java -version 2>&1 | grep version | awk '{print $1,KaTeX parse error: Expected 'EOF', got '}' at position 2: 3}̲' | tr -d '"')"…(getState rsyslog)”
echo “”
echo “/etc/rsyslog.conf”
echo “-----------------”
cat /etc/rsyslog.conf 2>/dev/null | grep -v “^#” | grep -v “^\KaTeX parse error: Expected group after '^' at position 11: " | sed '/^̲/d’ | column -t
#报表信息
report_Syslog=”$(getState rsyslog)"
}
function getFirewallStatus(){
echo “”
echo “”
echo “############################ 防火墙检查 ##########################”
#防火墙状态,策略等
if [[ KaTeX parse error: Expected 'EOF', got '&' at position 68: …s >/dev/null 2>&̲1 status=?
if [ $status -eq 0 ];then
s=“active”
elif [ $status -eq 3 ];then
s=“inactive”
elif [
s
t
a
t
u
s
−
e
q
4
]
;
t
h
e
n
s
=
"
p
e
r
m
i
s
s
i
o
n
d
e
n
i
e
d
"
e
l
s
e
s
=
"
u
n
k
n
o
w
n
"
f
i
e
l
s
e
s
=
"
status -eq 4 ];then s="permission denied" else s="unknown" fi else s="
status−eq4];thens="permissiondenied"elses="unknown"fielses="(getState iptables)"
fi
echo “iptables: KaTeX parse error: Expected 'EOF', got '#' at position 114: …es 2>/dev/null #̲报表信息 report\_Fi…s”
}
function getSNMPStatus(){
#SNMP服务状态,配置等
echo “”
echo “”
echo “############################ SNMP检查 ############################”