Lupinus

Re:从零开始的go学习生活(`・ω・´)

0%

[Zabbix监控]

Zabbix基础入门

zabbix 快速入门安装

C/S架构的服务

  • 服务端:zabbix-server
  • 客户端:zabbix-agent

截屏2023-03-26 13.35.41

zabbix官网:https://www.zabbix.com/

image-20230323184827951

image-20230323184836414

image-20230323184918502

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
# 1.下载zabbix的yum源
[root@m01 ~]# rpm -Uvh https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm

# 2.安装zabbix的服务端和客户端
[root@m01 ~]# yum install -y zabbix-server-mysql zabbix-agent

# 3.下载zabbix前端web页面的yum源
[root@m01 ~]# yum install centos-release-scl -y

# 4.打开zabbix的yum源中的前端仓库
[root@m01 ~]# vim /etc/yum.repos.d/zabbix.repo
[zabbix-frontend]
name=Zabbix Official Repository frontend - $basearch
baseurl=http://repo.zabbix.com/zabbix/5.0/rhel/7/$basearch/frontend
enabled=0 // 改为 1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX-A14FE591

# 5.安装zabbix前端web页面
[root@m01 ~]# yum install zabbix-web-mysql-scl zabbix-nginx-conf-scl -y

# 6.初始化数据库
## 1)创建zabbix数据库
mysql> create database zabbix character set utf8 collate utf8_bin;

## 2)创建zabbix用户
mysql> grant all on zabbix.* to zabbix@'172.16.1.%' identified by '123';

## 3)将zabbix的建表语句SQL文件发送到主库上
[root@m01 ~]# scp /usr/share/doc/zabbix-server-mysql-5.0.26/create.sql.gz 172.16.1.53:/tmp

## 4)主库导入SQL文件
[root@db01 ~]# zcat /tmp/create.sql.gz |mysql -uzabbix -p123 -h172.16.1.53 zabbix

# 7.修改zabbix服务端配置文件
[root@m01 ~]# vim /etc/zabbix/zabbix_server.conf
DBHost=172.16.1.53
DBUser=zabbix
DBName=zabbix
DBPassword=123

# 8.修改zabbix的nginx配置文件
[root@m01 ~]# vim /etc/opt/rh/rh-nginx116/nginx/conf.d/zabbix.conf
server {
listen 80;
server_name zabbix.zls.com;
...
}

# 9.修改zabbix的php配置文件
[root@m01 ~]# vim /etc/opt/rh/rh-php72/php-fpm.d/zabbix.conf
[zabbix]
user = nginx
group = nginx
listen.acl_users = nginx
php_value[date.timezone] = Asia/Shanghai

# 9.1授权
[root@m01 ~]# chown -R root.nginx /var/opt/rh/rh-php72/lib/php/session/

# 10.启动
[root@m01 ~]# systemctl restart zabbix-server zabbix-agent rh-nginx116-nginx rh-php72-php-fpm

# 11.查看端口
[root@m01 ~]# netstat -lntup|grep 10050
tcp 0 0 0.0.0.0:10050 0.0.0.0:* LISTEN 102137/zabbix_agent
tcp6 0 0 :::10050 :::* LISTEN 102137/zabbix_agent
[root@m01 ~]# netstat -lntup|grep 10051
tcp 0 0 0.0.0.0:10051 0.0.0.0:* LISTEN 102333/zabbix_serve
tcp6 0 0 :::10051 :::* LISTEN 102333/zabbix_serve

# 12.授权
[root@m01 ~]# chown -R nginx.nginx /etc/zabbix/web

image-20230323184933463

image-20230323184942928

截屏2023-03-23 18.50.56

image-20230323185011860

汉化zabbix

image-20230323185123575

image-20230323185136620

解决汉字无法显示问题

image-20230323185145541

在windows中找到中文字体

C:\Windows\Fonts

1
2
3
4
5
6
7
8
9
10
# 进入zabbix字体路径
[root@m01 ~]# cd /usr/share/zabbix/assets/fonts/

# 备份zabbix默认字体
[root@m01 fonts]# mv graphfont.ttf graphfont.ttf.bak

# 上传电脑中的字体

# 改名
[root@m01 fonts]# mv FZSTK.TTF graphfont.ttf

image-20230323185202755

Zabbix监控入门

为什么做监控

企业中:

1.系统的监控:实际上是对系统不间断的实时监控
2.实时反馈系统当前状态:我们监控某个硬件、或者某个系统,都是需要能实时看到当前系统的状态,是正常、异常、或者故障。
3.保证服务可靠性安全性:我们监控的目的就是要保证系统、服务、业务正常运行
4.保证业务持续稳定运行:如果我们的监控做得很完善,即使出现故障,能第一时间接收到故障报警,在第一时间处理解决,从而保证业务持续性的稳定运行。(往往,第一时间知道业务宕机的都是用户)

监控软件

image-20230323185307403

image-20230323185319585

  • Zabbix 分布式监控系统

image-20230323185327755

image-20230323185403017

image-20230323185438919

面试问题

面试官:你们公司监控是如何做的?

监控软件我们使用的是zabbix,我们监控在不同的维度

  • 硬件层面 Dell R710 R720 R730

    • 如果不使用dell的idrac那就使用zabbix的IPMI接口监控硬件

      1)CPU温度,
      2)风扇转速,
      3)磁盘是否损坏,
      4)CMOS电池电量
      5)内存是否损坏

      …..

    • 云主机,不需要说硬件层,一般云主机都自带,硬件监控

  • 系统层面

    • 内存
      • 内存使用率
      • 缓冲区
      • 缓存区
    • CPU
      • CPU使用率
      • CPU的负载
      • CPU核心数线程
    • 磁盘
      • 磁盘使用率
      • 磁盘大小
      • 磁盘IO
  • 网络层面

    • 网卡接口
    • 网卡流量
    • 交换机
    • 路由器
  • 应用层面

    • nginx
      • 进程
      • 端口
      • 网站访问
    • MySQL
      • 进程
      • 端口
      • 主从复制
      • SQL读写速率
      • 是否可以登录
      • InnoDB
      • 缓存
      • 表空间
      • 慢查询
    • tomcat
      • JMX
        • 老年代
        • 新生代
        • 永久代
      • 垃圾回收
      • full-gc
      • 进程
      • 端口
      • 网站是否可以访问
    • redis
      • 进程
      • 端口
      • 连接状态
      • 主从复制 info
      • 集群状态
      • key,缓存
        • 缓存穿透
        • 缓存击穿
        • 缓存雪崩
    • NFS、GFS(集群式的NFS)、Ceph、FastDFS
      • 进程
      • 挂载情况
      • 数据同步
    • PHP
      • 进程
      • 端口(socket)
      • 网站访问情况
      • php info
      • ….
  • 业务层面

    • 代码
    • 接口

单机监控命令

CPU监控命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
## 负载
[root@zabbix-server ~]# w
18:50:38 up 2:03, 3 users, load average: 0.01, 0.06, 0.06

## CPU
[root@zabbix-server ~]# top -n 1

## 美化的top
[root@zabbix-server ~]# yum install -y htop
[root@zabbix-server ~]# htop

## glances
[root@zabbix-server ~]# yum install -y glances
[root@zabbix-server ~]# glances

image-20230323185534641

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
[root@zabbix-server ~]# uptime
18:59:32 up 2:12, 3 users, load average: 0.00, 0.06, 0.06

[root@zabbix-server ~]# lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 1
On-line CPU(s) list: 0
Thread(s) per core: 1
Core(s) per socket: 1
Socket(s): 1
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 158
Model name: Intel(R) Core(TM) i5-7400 CPU @ 3.00GHz
Stepping: 9
CPU MHz: 3000.001
CPU max MHz: 0.0000
CPU min MHz: 0.0000
BogoMIPS: 6000.00
Hypervisor vendor: VMware
Virtualization type: full
L1d cache: 32K
L1i cache: 32K
L2 cache: 256K
L3 cache: 6144K
NUMA node0 CPU(s): 0
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch epb fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid rdseed adx smap xsaveopt xsavec xgetbv1 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp


[root@zabbix-server ~]# cat /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 158
model name : Intel(R) Core(TM) i5-7400 CPU @ 3.00GHz
stepping : 9
microcode : 0x8e
cpu MHz : 3000.001
cache size : 6144 KB
physical id : 0
siblings : 1
core id : 0
cpu cores : 1
apicid : 0
initial apicid : 0
fpu : yes
fpu_exception : yes
cpuid level : 22
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch epb fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid rdseed adx smap xsaveopt xsavec xgetbv1 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp
bogomips : 6000.00
clflush size : 64
cache_alignment : 64
address sizes : 42 bits physical, 48 bits virtual
power management:

不管用什么命令监控,查看CPU,我们都必须了解,系统的用户态和内和态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st

us: 用户态 跟用户的操作有关35%
sy: 内和态 跟内核的处理有关65%
id: CPU空闲

当我们执行一个命令的时候,很快能出来结果,但是有多少人知道,这个很快,他都占用了哪些时间呢?
[root@zabbix-server ~]# time ls
anaconda-ks.cfg zabbix-server-mysql-4.0.0-2.el7.x86_64.rpm
zabbix-agent-4.0.0-2.el7.x86_64.rpm zabbix-web-mysql-4.0.0-2.el7.noarch.rpm

real 0m0.032s
user 0m0.002s
sys 0m0.005s

监控内存

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
1)free
[root@zabbix-server ~]# free -g
total used free shared buff/cache available
Mem: 0 0 0 0 0 0
Swap: 0 0 0
[root@zabbix-server ~]# free -m
total used free shared buff/cache available
Mem: 972 234 158 8 579 528
Swap: 1023 0 1023
[root@zabbix-server ~]# free -h
total used free shared buff/cache available
Mem: 972M 234M 158M 8.4M 579M 528M
Swap: 1.0G 264K 1.0G


2)top
3)glances
4)htop

5)lsmem
[root@zabbix-server ~]# lsmem
RANGE SIZE STATE REMOVABLE BLOCK
0x0000000000000000-0x000000003fffffff 1G online no 0-7

Memory block size: 128M
Total online memory: 1G
Total offline memory: 0B

6)cat /proc/meminfo
[root@zabbix-server ~]# cat /proc/meminfo
MemTotal: 995896 kB
MemFree: 159908 kB
MemAvailable: 541596 kB
Buffers: 116 kB
Cached: 489248 kB
SwapCached: 4 kB
Active: 418768 kB
Inactive: 227568 kB
Active(anon): 137052 kB
Inactive(anon): 28476 kB
Active(file): 281716 kB
Inactive(file): 199092 kB
Unevictable: 0 kB
Mlocked: 0 kB
SwapTotal: 1048572 kB
SwapFree: 1048308 kB
Dirty: 20 kB
Writeback: 0 kB
AnonPages: 157000 kB
Mapped: 33420 kB
Shmem: 8556 kB
Slab: 107040 kB
SReclaimable: 57164 kB
SUnreclaim: 49876 kB
KernelStack: 4752 kB
PageTables: 22648 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 1546520 kB
Committed_AS: 928904 kB
VmallocTotal: 34359738367 kB
VmallocUsed: 177304 kB
VmallocChunk: 34359310332 kB
HardwareCorrupted: 0 kB
AnonHugePages: 51200 kB
CmaTotal: 0 kB
CmaFree: 0 kB
HugePages_Total: 0
HugePages_Free: 0
HugePages_Rsvd: 0
HugePages_Surp: 0
Hugepagesize: 2048 kB
DirectMap4k: 57216 kB
DirectMap2M: 991232 kB
DirectMap1G: 0 kB

如何查看单个进程占用内存?

1
2
3
#进程占用内存公式
pmem = VmRSS / MemTotal * 100
process mem = 虚拟内存 / 总内存 * 100

python脚本获取进程使用内存情况

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
[root@zabbix-server ~]# cat mem.py 
#!/usr/bin/env python
# _*_ coding:UTF-8 _*_
# 收集程序所占用的物理内存大小,占所有物理内存的比例
# Python: 2.7.6

import sys
import os
from subprocess import Popen,PIPE

def get_pid(program):
'获取目标程序的PID列表'
p = Popen(['pidof',program],stdout=PIPE,stderr=PIPE)
pids,stderrput = p.communicate()
# pids = p.stdout.read() #这种方法也是可以的
# 这里也可以对stderrput来进行判断
if pids:
return pids.split()
else:
raise ValueError

def mem_calc(pids):
'计算PIDs占用的内存大小'
mem_total = 0
for pid in pids:
os.chdir('/proc/%s' % pid)
with open('status') as fd:
for line in fd:
if line.startswith('VmRSS'):
mem = line.strip().split()[1]
mem_total += int(mem)
break
return mem_total


def mem_percent(mem):
'计算程序内存占用物理内存的百分比'
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
total = line.strip().split()[1]
percent = (float(mem)/int(total)) * 100
return percent


def main():
try:
program = sys.argv[1]
pids = get_pid(program)
except IndexError as e:
sys.exit('%s need a Program name ' % __file__)
except ValueError as e:
sys.exit('%s not a Process Name or not Start' % program )
mem_total = mem_calc(pids)
percent = mem_percent(mem_total)
return program,mem_total,percent

if __name__ == '__main__':
program,mem_total,mem_percent=main()
print('进程名称:%s\n物理内存为:%s\n百分比为:%.2f%%'% (program,mem_total,mem_percent))


[root@zabbix-server ~]# python mem.py zabbix_agentd
进程名称:zabbix_agentd
物理内存为:12332
百分比为:1.24%

[root@zabbix-server ~]# python mem.py zabbix_server
进程名称:zabbix_server
物理内存为:115300
百分比为:11.58%

[root@zabbix-server ~]# python mem.py httpd
进程名称:httpd
物理内存为:212148
百分比为:21.30%

监控磁盘命令

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
1)df
[root@zabbix-server ~]# df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/sda3 9704960 38522 9666438 1% /
devtmpfs 121762 377 121385 1% /dev
tmpfs 124487 1 124486 1% /dev/shm
tmpfs 124487 746 123741 1% /run
tmpfs 124487 16 124471 1% /sys/fs/cgroup
/dev/sda1 256000 326 255674 1% /boot
tmpfs 124487 1 124486 1% /run/user/0
[root@zabbix-server ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda3 19G 1.6G 17G 9% /
devtmpfs 476M 0 476M 0% /dev
tmpfs 487M 0 487M 0% /dev/shm
tmpfs 487M 7.8M 479M 2% /run
tmpfs 487M 0 487M 0% /sys/fs/cgroup
/dev/sda1 497M 120M 378M 25% /boot
tmpfs 98M 0 98M 0% /run/user/0
[root@zabbix-server ~]# df -ih
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/sda3 9.3M 38K 9.3M 1% /
devtmpfs 119K 377 119K 1% /dev
tmpfs 122K 1 122K 1% /dev/shm
tmpfs 122K 746 121K 1% /run
tmpfs 122K 16 122K 1% /sys/fs/cgroup
/dev/sda1 250K 326 250K 1% /boot
tmpfs 122K 1 122K 1% /run/user/0

2)iotop查看进程对磁盘的使用情况,IO吞吐量情况
[root@zabbix-server ~]# iotop
Total DISK READ : 0.00 B/s | Total DISK WRITE : 0.00 B/s
Actual DISK READ: 0.00 B/s | Actual DISK WRITE: 0.00 B/s

3)查看磁盘的IO吞吐量
-d:指定多久出一次结果 单位是秒
-m:指定出几次结果
[root@zabbix-server ~]# iostat -dm 1 10
Linux 3.10.0-957.el7.x86_64 (zabbix-server) 08/23/2022 _x86_64_ (1 CPU)

Device: tps MB_read/s MB_wrtn/s MB_read MB_wrtn
scd0 0.00 0.00 0.00 1 0
sda 2.17 0.03 0.07 284 607

[root@zabbix-server ~]# yum install -y dstat
[root@zabbix-server ~]# dstat -cdngy

image-20230323185555823

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
5)glances
6)lsblk
[root@zabbix-server ~]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 20G 0 disk
├─sda1 8:1 0 500M 0 part /boot
├─sda2 8:2 0 1G 0 part [SWAP]
└─sda3 8:3 0 18.5G 0 part /
sr0 11:0 1 4.3G 0 rom

## 磁盘开机自动挂载
[root@zabbix-server ~]# vim /etc/fstab

## 创建一块新磁盘
[root@zabbix-server ~]# dd < /dev/zero > /disk1 bs=1024K count=5

## 格式化
[root@zabbix-server ~]# mkfs.ext4 -i 5120 /disk1

## 挂载
[root@zabbix-server ~]# mount -t ext4 -o loop /disk1 /opt/cipan1/

## 查看
[root@zabbix-server ~]# df -h
/dev/loop0 3.9M 53K 3.5M 2% /opt/cipan1

[root@zabbix-server ~]# vim /etc/fstab
UUID=b2503fb9-fc5e-47fc-b86a-d171a5fbf689 /opt/cipan1 ext4 defaults 0 0

## 查看一块磁盘的UUID
[root@zabbix-server ~]# blkid /dev/sda1
/dev/sda1: UUID="33bce62e-082b-4647-8b36-9335a0cc6600" TYPE="xfs"
[root@zabbix-server ~]# blkid /dev/sda3
/dev/sda3: UUID="9e1a4ad0-69bf-4b9e-9aa0-4820ec625963" TYPE="xfs"
[root@zabbix-server ~]# blkid /dev/loop0
/dev/loop0: UUID="b2503fb9-fc5e-47fc-b86a-d171a5fbf689" TYPE="ext4"

网络监控命令

1
2
3
4
5
6
7
8
1)glances
NETWORK Rx/s Tx/s
eth0 592b 15Kb
eth1 17Kb 13Kb
lo 0b 0b

2)iftop
[root@zabbix-server ~]# iftop

image-20230323185753652

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
3)nethogs
[root@zabbix-server ~]# yum install -y nethogs
[root@zabbix-server ~]# nethogs

4) ifconfig
[root@zabbix-server ~]# watch ifconfig

5)路由
[root@zabbix-server ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.0.0.2 0.0.0.0 UG 0 0 0 eth0
10.0.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 1002 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 1003 0 0 eth1
172.16.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1

TCP11种状态监控命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# netstat
# 查看当前服务器上的所有应用TCP状态
[root@zabbix-server ~]# netstat -an

[root@zabbix-server ~]# netstat -an|awk '/^tcp/ {print $NF}'|sort|uniq -c
26 ESTABLISHED
11 LISTEN
48 TIME_WAIT

[root@zabbix-server ~]# netstat -an|awk '/^tcp/ {++state[$NF]} END {for(key in state) print key," \t" ,state[key]}'
LISTEN 11
ESTABLISHED 25
FIN_WAIT2 1
TIME_WAIT 53

生产场景需求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#如何每1分钟监控当前系统的内存使用状态,如果可用低于100MB则发送邮件。同时打印当前还剩余多少内存
1.如何获取内存的状态信息 free -m
2.如何获取内存的可用状态 free -m|awk '/Mem/{print $NF}'
3.如何进行数字的比对,高于100MB不处理,低于100MB,发送邮件。
4.如何每分钟执行。

[root@web02 ~]# vim free.sh
#!/bin/bash

while true;do
free_av=$(free -m|awk '/^Mem/{print $NF}')
Hostname=$(hostname)_$(hostname -I|awk '{print $2}')
Date=$(date +%F)

if [ $free_av -lt 100 ];then
echo "$Date: ${Hostname},内存低于100MB,还有${free_av}MB内存可用"
fi
sleep 2
done

[root@web02 ~]# sh free.sh
2018-10-12: web02_,内存低于100MB,还有20MB内存可用
2018-10-12: web02_,内存低于100MB,还有6MB内存可用
2018-10-12: web02_,内存低于100MB,还有5MB内存可用

系统的oom

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
## 关闭swap
[root@zabbix-server ~]# swapoff -a
随着时间的推移,用户不断增多,服务消耗的内存越来越多,当系统内存不足的时候,可能会导致系统产生oom(out of memory)

1.当系统内存不足时就会大量使用swap(虚拟内存)
2.当系统大量使用swap的时候,系统会特别卡
注意:有时可能内存还有剩余300M或者500M,但是swap依然被使用

[root@web02 ~]# dd < /dev/zero > /dev/null bs=2000M

[root@web02 ~]# tail -f /var/log/messages
Out of memory: Kill process 29957 (dd) score 366 or sacrifice child
Killed process 29957 (dd) total-vm:2532680kB, anon-rss:1416508kB, filers:0kB

Aug 23 20:18:27 localhost kernel: Out of memory: Kill process 22208 (dd) score 599 or sacrifice child
Aug 23 20:18:27 localhost kernel: Killed process 22208 (dd) total-vm:722512kB, anon-rss:614508kB, file-rss:0kB, shmem-rss:0kB

使用脚本监控nginx

前面的课程中,我们学习了使用脚本+定时任务的方法自动备份并将检查结果,发到指定邮箱,那么这里,我也可以使用脚本+定时任务的方法,进行监控,并使用邮件报警

1
2
3
4
5
#!/bin/bash
nginx_process=`ps -ef|grep -c [n]ginx`
if [ $nginx_process -lt 2 ];then
echo "目前nginx进程数是:$nginx_process"|mail -s "完犊子nginx挂了" 133411023@qq.com
fi

Zabbix自定义监控项

快速监控一台主机

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
# 查看服务端的版本
[root@m01 fonts]# zabbix_server -V
zabbix_server (Zabbix) 5.0.26

# 安装对应版本的agent客户端
# 1.在其他机器上,安装zabbix的yum源
[root@db03 ~]# rpm -Uvh https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm

# 2.安装客户端
[root@db03 ~]# yum install -y zabbix-agent-5.0.26
[root@web01 ~]# rpm -ivh https://mirrors.aliyun.com/zabbix/zabbix/5.0/rhel/7/x86_64/zabbix-agent-5.0.26-1.el7.x86_64.rpm

# 3.修改配置文件
[root@web01 ~]# vim /etc/zabbix/zabbix_agentd.conf
Server=172.16.1.61
ServerActive=172.16.1.61
Hostname=web01

# 4.启动服务
[root@web01 ~]# systemctl start zabbix-agent

# 5.检查端口
[root@web01 ~]# netstat -lntup |grep 10050
tcp 0 0 0.0.0.0:10050 0.0.0.0:* LISTEN 7681/zabbix_agentd
tcp6 0 0 :::10050 :::* LISTEN 7681/zabbix_agentd

image-20230323190118340

image-20230323190030807

image-20230323190037922

添加基础模板

zabbix3.x 和 zabbix4.x

image-20230323190135411

image-20230323190145589

image-20230323190150631

image-20230323190156600

zabbix报错排查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#1.检查端口
[root@zabbix ~]# telnet 172.16.1.7 10050

#2.服务端是否能获取到客户端的监控数据
[root@zabbix ~]# yum install -y zabbix-get-5.0.32
-s:指定主机IP地址
-k:指定监控项名称
[root@zabbix ~]# zabbix_get -s 172.16.1.7 -k system.swap.size[,pfree]
100.000000
[root@zabbix ~]# zabbix_get -s 172.16.1.7 -k system.swap.size[,free]
1073737728

#3.查看nginx日志
[root@zabbix ~]# tail -f /var/opt/rh/rh-nginx116/log/nginx/error.log
[root@zabbix ~]# tail -f /var/opt/rh/rh-nginx116/log/nginx/access.log

#4.查看zabbix-server日志
[root@zabbix ~]# tail -f /var/log/zabbix/zabbix_server.log

#5.查看zabbix-agent日志
[root@zabbix ~]# tail -f /var/log/zabbix/zabbix_agentd.log

zabbix基础架构

1
2
3
4
5
6
7
8
9
zabbix-agent:获取本机上的数据(主动上交给server)
zabbix-server:获取所有agent上的数据,并保存到数据库中 create.sql.gz
- 1.systemctl stop zabbix-server
- 2.drop database zabbix;
- 3.creaete database zabbix charset utf8 collate utf8_bin;
- 4.zcat create.sql.gz| mysql -uzabbix -p123 zabbix
- 5.rm -f zabbix.conf.php
- 6.http://zabbix.zls.com/setup.php // 重新进入配置页面
zabbix-web:页面展示,从数据库中获取数据,展示到页面上

自定义zabbix监控

1
2
3
4
5
6
7
8
9
## 监控项添加流程
1.创建一个模板
2.给模板添加监控项
3.给监控项画图
4.给监控项添加触发器
5.给监控项的触发器添加告警动作
- 邮件
- 微信
- 钉钉

自定义监控项的格式

1
2
3
4
5
6
7
UserParameter=监控项的key名称,获取监控项值的命令或脚本
UserParameter=<key>,<shell command>

#获取登陆用户数量
UserParameter=user.count,who | wc -l

UserParameter=user.count,uptime|grep -Po "\d(?= user)"

添加配置文件

1
2
3
4
5
6
7
8
9
10
11
# 1.修改配置
[root@web01 ~]# vim /etc/zabbix/zabbix_agentd.conf
UserParameter=user.count,who | wc -l

# 2.重启zabbix-agent
[root@web01 ~]# systemctl restart zabbix-agent

# 3.在服务端获取一下该监控项的数据
[root@web01 ~]# yum install -y zabbix-get
[root@web01 ~]# zabbix_get -s 172.16.1.31 -k user.count
3

页面添加监控项

自己创建一个监控模板

image-20230323191705252

image-20230323191713120

给模板中添加监控项

image-20230323191753414

image-20230323191822357

image-20230323191829985将主机关联该模板

image-20230323191841956

image-20230323191914524

给监控项画图

image-20230323191849876

image-20230323191929486

image-20230323191950794

image-20230323191959992

查看监控数据

image-20230323192006404

给监控项添加触发器

常用触发器

1
2
3
4
5
6
7
8
and       #并且
or #或
last() #对比最后的值
avg() #平均值
diff() #对比上一次文件的内容
nodata() #收不到数据进行报警
(5m) #表示最近五分种得到值
(#5) #表示最近五次得到的值

image-20230323192200143

image-20230323192207041

image-20230323192213415

优化页面告警

1
2
3
主机名:{HOST.NAME}
IP地址:{HOST.IP}
Monitor Login User Count Problem 主机名:{HOST.NAME} IP地址:{HOST.IP}

给监控项的触发器添加告警动作

image-20230323192304091

image-20230323192309251

image-20230323192315802

image-20230323192339056

image-20230323192346364

添加邮件告警(报警媒介类型:发件人和告警方式)

image-20230323192417377

image-20230323192424927

配置收件人

image-20230323192447114

image-20230323192452878

image-20230323192501724

image-20230323192534890

添加报警媒介

image-20230323192541892

image-20230323192546666

告警消息添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
## 故障告警
标题:Problem: {EVENT.NAME}
内容:
Problem started at {EVENT.TIME} on {EVENT.DATE}
Problem name: {EVENT.NAME}
Host: {HOST.NAME}
Severity: {EVENT.SEVERITY}

Original problem ID: {EVENT.ID}
{TRIGGER.URL}

## 恢复告警
标题:Resolved: {EVENT.NAME}
内容:
Problem has been resolved at {EVENT.RECOVERY.TIME} on {EVENT.RECOVERY.DATE}
Problem name: {EVENT.NAME}
Host: {HOST.NAME}
Severity: {EVENT.SEVERITY}

Original problem ID: {EVENT.ID}
{TRIGGER.URL}

优化告警消息

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
## 故障告警
故障{TRIGGER.STATUS},服务器:{HOSTNAME1}发生: {TRIGGER.NAME}故障!

告警地址:{HOST.IP}

告警主机:{HOSTNAME1}

告警时间:{EVENT.DATE} {EVENT.TIME}

告警等级:{TRIGGER.SEVERITY}

告警信息: {TRIGGER.NAME}

告警项目:{TRIGGER.KEY1}

问题详情:{ITEM.NAME}:{ITEM.VALUE}

当前状态:{TRIGGER.STATUS}:{ITEM.VALUE1}

事件ID:{EVENT.ID}

## 恢复告警
恢复{TRIGGER.STATUS}, 服务器:{HOSTNAME1}: {TRIGGER.NAME}已恢复!

告警地址:{HOST.IP}

告警主机:{HOSTNAME1}

告警时间:{EVENT.DATE} {EVENT.TIME}

告警等级:{TRIGGER.SEVERITY}

告警信息: {TRIGGER.NAME}

告警项目:{TRIGGER.KEY1}

问题详情:{ITEM.NAME}:{ITEM.VALUE}

当前状态:{TRIGGER.STATUS}:{ITEM.VALUE1}

事件ID:{EVENT.ID}

image-20230323192604874

Zabbix深入自定义监控

zabbix多条件触发

监控内存可用的百分比

1
UserParameter=mem.available,free -m|awk 'NR==2{print $NF/$2*100}'

image-20230323192722785

image-20230323192728168

image-20230323192735423

目前属于单条件触发器,因为内存低于30%就报警了,在生产中,我们应该是当内存低于30%并且占用了swap空间,然后再报警。

1
2
3
UserParameter=swap.available,free -m|awk '/^Swap/{print $NF/$2*100}'

[root@sb_wzj web]# zabbix_get -s 172.16.1.7 -k swap.available

image-20230323192745514

image-20230323192822589

image-20230323192828454

1
2
3
4
5
6
7
8
and             #并且
or #或者
last() #比对最新的值
avg() #平均值
diff() #比对上一次文件的内容
nodata() #收不不到数据进行报警nodata(5m)
(5m) #表示最近5分钟得到值
(#5) #表示最近5次得到的值

zabbix 5.x以上告警

故障告警

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
<head>
<style type="text/css">
table .guzhang {color: red;}
</style>
</head>
<body>
<img src="https://blog.driverzeng.com/zenglaoshi/sos.png" alt="">
<table border="3" bordercolor="black" cellspacing="0px" cellpadding="4px" width="500px">
<tr class="guzhang" bgcolor="#0C1B3D" ><th colspan=2>
{TRIGGER.STATUS} 故障!!!故障!!!
<div>&#128514; &#128514; &#128514;</div>
</tr>
<tr >
<td bgcolor="#F9B602" width="20%">告警主机</td>
<td bgcolor="#F9B602">{HOSTNAME1}</td>
</tr>
<tr >
<td bgcolor="#F9B602">告警别名</td>
<td bgcolor="#F9B602">{HOST.NAME} </td>
<tr >
<tr >
<td bgcolor="#F9B602">告警地址</td>
<td bgcolor="#F9B602">{HOST.IP}</td>
</tr>
<tr>
<td bgcolor="#F9B602">告警时间</td>
<td bgcolor="#F9B602">{EVENT.DATE} {EVENT.TIME}</td>
</tr>

<tr>
<td bgcolor="#F9B602">告警等级</td>
<td bgcolor="#F9B602">{TRIGGER.SEVERITY}</td>
</tr>

<tr>
<td bgcolor="#F9B602">告警信息</td>
<td bgcolor="#F9B602">{TRIGGER.NAME}</td>
</tr>

<tr>
<td bgcolor="#F9B602">告警项目</td>
<td bgcolor="#F9B602">{TRIGGER.KEY1}</td>
</tr>
<tr >
<td class='guzhang2' bgcolor="#FF3333">问题详情</td>
<td class='guzhang3' bgcolor="#FF3333">{ITEM.NAME}:&nbsp;{ITEM.VALUE} &#128520; &#128520; &#128520;</td>
</tr>
<tr>
<td bgcolor="#F9B602">当前状态</td>
<td bgcolor="#F9B602">{TRIGGER.STATUS}:&nbsp;{ITEM.VALUE1}</td>
</tr>
<tr>
<td bgcolor="#F9B602">事件ID</td>
<td bgcolor="#F9B602">{EVENT.ID}</td>
</tr>
</table>
</body>

恢复告警

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
<head>
<style type="text/css">
table .guzhang {
color: red;
}
</style>
</head>
<body>
<img src="https://blog.driverzeng.com/zenglaoshi/huifu.png" alt="">
<table border="1" bordercolor="black" cellspacing="0px" cellpadding="4px" width="500px">
<tr bgcolor="#49c208"><th colspan=2>
{TRIGGER.STATUS} 哈哈哈哈哈哈,好了
<div>&#128512; &#128512; &#128512;</div>
</tr>

<tr >
<td bgcolor="lightgreen" width="20%">恢复主机</td>
<td bgcolor="yellow">{HOSTNAME1}</td>
</tr>
<tr>
<td bgcolor="lightgreen">恢复别名</td>
<td bgcolor="yellow">{HOST.NAME} </td>
<tr >
<td bgcolor="lightgreen">恢复地址</td>
<td bgcolor="yellow">{HOST.IP}</td>
</tr>
<tr>
<td bgcolor="lightgreen">恢复时间</td>
<td bgcolor="yellow">{EVENT.DATE} {EVENT.RECOVERY.TIME}</td>
</tr>

<tr>
<td bgcolor="lightgreen">恢复等级</td>
<td bgcolor="yellow">{TRIGGER.SEVERITY}</td>
</tr>

<tr>
<td bgcolor="lightgreen">恢复信息</td>
<td bgcolor="yellow">{TRIGGER.NAME}</td>
</tr>

<tr>
<td bgcolor="lightgreen">恢复项目</td>
<td bgcolor="yellow">{TRIGGER.KEY1}</td>
</tr>
<tr >
<td bgcolor="#49c208">恢复详情</td>
<td bgcolor="#49c208">{ITEM.NAME}:&nbsp;{ITEM.VALUE} &#9889; &#9889; &#9889;</td>
</tr>
<tr>
<td bgcolor="lightgreen">当前状态</td>
<td bgcolor="yellow">{TRIGGER.STATUS}:&nbsp;{ITEM.VALUE1}</td>
</tr>
<tr>
<td bgcolor="lightgreen">事件ID</td>
<td bgcolor="yellow">{EVENT.ID}</td>
</tr>
</table>
</body>

zabbix的自愈模式

有些时候,我们的服务宕机了,或者有些服务停掉了,那么我们可以先尝试让他启动,看是否能起的来,为了不影响用户的体验,先把服务起起来,然后再去排查,是什么原因故障的。

那么此时我们就需要用到zabbix的自愈模式,这个…叫起来很好听,说白了,就是在让zabbix-server通过远程执行命令的方式,在agent上执行命令,启动服务。

image-20230323192842454

image-20230323192858259

image-20230323192903808

1
2
3
#修改配置文件
[root@web01 zabbix_agentd.d]# vim /etc/zabbix/zabbix_agentd.conf
EnableRemoteCommands=1

zabbix告警升级机制

image-20230323192923043

image-20230323193013139

image-20230323193017533

image-20230323193022705

image-20230323193027831

image-20230323193115833

image-20230323193109471

计算方式:

  1. 开始于 ,这个是相对一但触发监控,则立即发送消息
  2. 1-2步骤是给运维组发送消息,每隔5分钟发送一次,总共2个步骤,所以发送2次
  3. 3-4步骤是给运维经理组发送消息,每隔5分钟发送一次,总共2个步骤,所以发送2次
  4. 4-5步骤是给运维总监组发送消息,每隔5分钟发送一次,总共2个步骤,所以发送2次
  5. 每次的开始时间是如何计算的呢,第一个立即开始:
    1-2,3-4,4-5动作时间间隔是5分钟,所以在触发告警发送时间计算是5m+5m+5m=15m

聚合图形

image-20230323193125905

image-20230323193149392

zabbix微信报警

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
# 1.安装python的pip
[root@sb_wzj web]# yum install python-pip -y

# 2.安装python requests库
[root@sb_wzj ~]# pip2.7 install requests==2.27 -i https://pypi.douban.com/simple/

# 3.进入zabbix存放告警脚本目录
[root@sb_wzj ~]# cd /usr/lib/zabbix/alertscripts/

# 4.编写微信告警脚本
[root@sb_wzj alertscripts]# vim weixin.py
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import requests
import json
import sys
import os

headers = {'Content-Type': 'application/json;charset=utf-8'}
api_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b3f00bb1-3198-4491-9429-a9fbe5444e23" #这个是企业微信机器人生成的webhook地址,修改为你的即可。

def msg(text):
json_text= {
"msgtype": "text",
"text": {
"content": text
},
}
print(requests.post(api_url,json.dumps(json_text),headers=headers).content)

if __name__ == '__main__':
text = sys.argv[1]
msg(text)

# 5.添加执行权限
[root@sb_wzj alertscripts]# chmod +x weixin.py

image-20230323193222292

zabbix 应用监控

监控nginx

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
# 1.创建zabbix存放脚本目录
[root@web01 ~]# mkdir -p /etc/zabbix/scripts

# 2.编写监控项脚本
[root@web01 ~]# vim /etc/zabbix/scripts/nginx_status.sh
#!/bin/bash
############################################################
# $Name: nginx_status.sh
# $Version: v1.0
# $Function: Nginx Status
# $Author: DriverZeng
# $organization: www.driverzeng.com
# $Create Date: 2016-06-23
# $Description: Monitor Nginx Service Status
############################################################

NGINX_PORT=80 #如果端口不同仅需要修改脚本即可,否则修改xml很麻烦
NGINX_COMMAND=$1

nginx_active(){
/usr/bin/curl -s "http://127.0.0.1:"$NGINX_PORT"/nginx_status/" |awk '/Active/ {print $NF}'
}

nginx_reading(){
/usr/bin/curl -s "http://127.0.0.1:"$NGINX_PORT"/nginx_status/" |awk '/Reading/ {print $2}'
}

nginx_writing(){
/usr/bin/curl -s "http://127.0.0.1:"$NGINX_PORT"/nginx_status/" |awk '/Writing/ {print $4}'
}

nginx_waiting(){
/usr/bin/curl -s "http://127.0.0.1:"$NGINX_PORT"/nginx_status/" |awk '/Waiting/ {print $6}'
}

nginx_accepts(){
/usr/bin/curl -s "http://127.0.0.1:"$NGINX_PORT"/nginx_status/" |awk 'NR==3 {print $1}'
}

nginx_handled(){
/usr/bin/curl -s "http://127.0.0.1:"$NGINX_PORT"/nginx_status/" |awk 'NR==3 {print $2}'
}

nginx_requests(){
/usr/bin/curl -s "http://127.0.0.1:"$NGINX_PORT"/nginx_status/" |awk 'NR==3 {print $3}'
}


case $NGINX_COMMAND in
active)
nginx_active;
;;
reading)
nginx_reading;
;;
writing)
nginx_writing;
;;
waiting)
nginx_waiting;
;;
accepts)
nginx_accepts;
;;
handled)
nginx_handled;
;;
requests)
nginx_requests;
;;
*)
echo $"USAGE:$0 {active|reading|writing|waiting|accepts|handled|requests}"
esac

# 3.给脚本添加执行权限
[root@web01 ~]# chmod +x /etc/zabbix/scripts/nginx_status.sh

# 4.修改客户端配置文件
[root@web01 ~]# vim /etc/zabbix/zabbix_agentd.d/nginx_status.conf
UserParameter=nginx_status[*],/bin/bash /etc/zabbix/scripts/nginx_status.sh "$1"

# 5.重启agent
[root@web01 ~]# systemctl restart zabbix-agent

# 6.检测
[root@sb_wzj ~]# zabbix_get -s 172.16.1.7 -k nginx_status[waiting]
0
[root@sb_wzj ~]# zabbix_get -s 172.16.1.7 -k nginx_status[requests]
19
[root@sb_wzj ~]# zabbix_get -s 172.16.1.7 -k nginx_status[accepts]
20

image-20230325230254488

image-20230325230300411

image-20230325230305451

image-20230325230322170

image-20230325230326837

image-20230325230332051

zabbix监控PHP

修改php配置

1
2
3
4
5
# 1.打开php状态模块
pm.status_path = /phpfpm_status

# 2.重启php
[root@web01 ~]# systemctl restart php-fpm

修改nginx配置

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
# 1.修改nginx配置文件
server {
listen 80;
server_name _;

location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}

location ~ ^/(phpfpm_status)$ {
include fastcgi_params;
fastcgi_pass unix:/dev/shm/php.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}

# 2.重启nginx
[root@web01 ~]# systemctl restart nginx

# 3.查看phpfpm状态页
[root@web01 ~]# curl http://127.0.0.1/phpfpm_status
pool: www
process manager: dynamic
start time: 26/Aug/2022:10:55:47 +0800
start since: 165
accepted conn: 1
listen queue: 0
max listen queue: 0
listen queue len: 0
idle processes: 4
active processes: 1
total processes: 5
max active processes: 1
max children reached: 0
slow requests: 0

#PHP-FPM状态解释:
pool #fpm池名称,大多数为www
process manager #进程管理方式dynamic或者static
start time #启动日志,如果reload了fpm,时间会更新
start since #运行时间
accepted conn #当前池接受的请求数
listen queue #请求等待队列,如果这个值不为0,那么需要增加FPM的进程数量
max listen queue #请求等待队列最高的数量
listen queue len #socket等待队列长度
idle processes #空闲进程数量
active processes #活跃进程数量
total processes #总进程数量
max active processes #最大的活跃进程数量(FPM启动开始计算)
max children reached #进程最大数量限制的次数,如果这个数量不为0,那说明你的最大进程数量过小,可以适当调整。
slow requests # 请求比较慢的数量

编写监控脚本

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
# 1.脚本内容
[root@web01 ~]# vim /etc/zabbix/scripts/phpfpm_status.sh
#!/bin/bash
############################################################
# $Name: phpfpm_status.sh
# $Version: v1.0
# $Function: Nginx Status
# $Author: DriverZeng
# $organization: www.driverzeng.com
# $Create Date: 2016-06-23
# $Description: Monitor Nginx Service Status
############################################################

PHPFPM_COMMAND=$1
PHPFPM_PORT=80 #根据监听不同端口进行调整

start_since(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^start since:/ {print $NF}'
}

accepted_conn(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^accepted conn:/ {print $NF}'
}

listen_queue(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^listen queue:/ {print $NF}'
}

max_listen_queue(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^max listen queue:/ {print $NF}'
}

listen_queue_len(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^listen queue len:/ {print $NF}'
}

idle_processes(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^idle processes:/ {print $NF}'
}

active_processes(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^active processes:/ {print $NF}'
}

total_processes(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^total processes:/ {print $NF}'
}

max_active_processes(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^max active processes:/ {print $NF}'
}

max_children_reached(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^max children reached:/ {print $NF}'
}

slow_requests(){
/usr/bin/curl -s "http://127.0.0.1:"$PHPFPM_PORT"/phpfpm_status" |awk '/^slow requests:/ {print $NF}'
}

case $PHPFPM_COMMAND in
start_since)
start_since;
;;
accepted_conn)
accepted_conn;
;;
listen_queue)
listen_queue;
;;
max_listen_queue)
max_listen_queue;
;;
listen_queue_len)
listen_queue_len;
;;
idle_processes)
idle_processes;
;;
active_processes)
active_processes;
;;
total_processes)
total_processes;
;;
max_active_processes)
max_active_processes;
;;
max_children_reached)
max_children_reached;
;;
slow_requests)
slow_requests;
;;
*)
echo $"USAGE:$0 {start_since|accepted_conn|listen_queue|max_listen_queue|listen_queue_len|idle_processes|active_processes|total_processes|max_active_processes|max_children_reached}"
esac

# 2.添加执行权限
[root@web01 ~]# chmod +x /etc/zabbix/scripts/phpfpm_status.sh

配置zabbix客户端加监控

1
2
3
4
5
6
7
8
9
10
11
[root@web01 ~]# cp /etc/zabbix/zabbix_agentd.d/{nginx_status.conf,phpfpm_status.conf}
[root@web01 ~]# vim /etc/zabbix/zabbix_agentd.d/phpfpm_status.conf
UserParameter=phpfpm_status[*],/bin/bash /etc/zabbix/scripts/phpfpm_status.sh "$1"
[root@web01 ~]# systemctl restart zabbix-agent

[root@sb_wzj ~]# zabbix_get -s 172.16.1.7 -k phpfpm_status[start_since]
891
[root@sb_wzj ~]# zabbix_get -s 172.16.1.7 -k phpfpm_status[accepted_conn]
3
[root@sb_wzj ~]# zabbix_get -s 172.16.1.7 -k phpfpm_status[listen_queue]
0

页面添加监控项

image-20230325230352104

image-20230325230358107

image-20230325230402509

image-20230325230406702

image-20230325230420363

image-20230325230424729

image-20230325230430584

zabbix监控MySQL

1
2
3
4
# 1.开启MySQL上的zabbix-agent
[root@db03 ~]# systemctl start zabbix-agent

# 2.添加主机

image-20230325230453056

image-20230325230501789

zabbix监控redis

1
2
3
4
5
# 1.安装redis
[root@db03 ~]# yum install -y redis

# 2.启动redis
[root@db03 ~]# systemctl start redis

image-20230325230531241

Zabbix监控MySQL

percona Monitoring Plugins是一个高质量的组件,为MySQL数据库添加企业级的监控和图表功能。但其脚本使用PHP实现,故而Zabbix-Agent需要安装PHP环境。

percona工具集

实践环境

服务器系统 角色 IP
CentOS 7.4 x86_64 Zabbix-Server 10.0.0.8
CentOS 7.4 x86_64 Zabbix-Agent 10.0.0.7

1.在Zabbix-Agent端安装percona Monitoring Plugins

1
2
[root@Agent ~]# yum install -y http://www.percona.com/downloads/percona-release/redhat/0.1-3/percona-release-0.1-3.noarch.rpm
[root@Agent ~]# yum install percona-zabbix-templates -y

2.查看percona安装后的目录结构

1
2
3
4
5
6
7
8
[root@Agent percona]# tree /var/lib/zabbix/percona
/var/lib/zabbix/percona
├── scripts #脚本文件路径
│ ├── get_mysql_stats_wrapper.sh
│ └── ss_get_mysql_stats.php
└── templates
├── userparameter_percona_mysql.conf #key文件位置
└── zabbix_agent_template_percona_mysql_server_ht_2.0.9-sver1.1.6.xml #模板文件位置

4.将自定义监控项配置文件复制至/etc/zabbix_agentd.conf.d目录下

1
[root@Agent ~]# cp /var/lib/zabbix/percona/templates/userparameter_percona_mysql.conf  /etc/zabbix/zabbix_agentd.d/percona_mysql.conf

5.重启zabbix-agent

1
[root@Agent ~]# systemctl restart zabbix-agent

6.修改脚本中的MySQL用户名和密码

1
2
3
4
[root@Agent scripts]# vim /var/lib/zabbix/percona/scripts/ss_get_mysql_stats.php
$mysql_user = 'root';
$mysql_pass = '123';
$mysql_port = 3306;

7.在Zabbix-Server端上使用Zabbix_get获取值(否则会失败)

1
2
3
4
5
6
7
8
[root@Server ~]# zabbix_get -s 10.0.0.7 -k MySQL.pool-read-requests
223003813

//如果获取不到值常见问题
1.看是否是MySQL密码错误
2.不要直接执行脚本来获取
3.删除/tmp/localhost-mysql_cacti_stats.txt文件
4.权限问题导致

8.在Zabbix页面模板选项中导入Percona模板, 模板存放在/var/lib/zabbix/percona/templates, 最后关联主机即可。

Zabbix监控Redis

Redis使用自带的INFO命令,进行状态监控。以一种易于解释且易于阅读的格式,返回关于Redis服务器的各种信息和统计数值。

实践环境

服务器系统 角色 IP
CentOS 7.4 x86_64 Zabbix-Server 10.0.0.8
CentOS 7.4 x86_64 Zabbix-Agent 10.0.0.7

1.编写Shell脚本

  • 脚本端口、连接redis服务地址根据具体情况进行修改
  • AUTH认证没有开启,将PASSWD修改为空即可。
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
[root@Agent ~]# mkdir -p  /etc/zabbix/scripts
[root@Agent ~]# vim /etc/zabbix/scripts/redis_status.sh
#!/bin/bash
############################################################
# $Name: redis_status.sh
# $Version: v1.0
# $Function: Redis Status
# $Author: DriverZeng
# $organization: www.driverzeng.com
# $Create Date: 2016-06-23
# $Description: Monitor Redis Service Status
############################################################

R_COMMAND="$1"
R_PORT="6379" #根据实际情况调整端口
R_SERVER="127.0.0.1" #根据具体情况调整IP地址
PASSWD="" #如果没有设置Redis密码,为空即可


redis_status(){
(echo -en "AUTH $PASSWD\r\nINFO\r\n";sleep 1;) | /usr/bin/nc "$R_SERVER" "$R_PORT" > /tmp/redis_"$R_PORT".tmp
REDIS_STAT_VALUE=$(grep "$R_COMMAND:" /tmp/redis_"$R_PORT".tmp | cut -d ':' -f2)
echo "$REDIS_STAT_VALUE"
}

case $R_COMMAND in
used_cpu_user_children)
redis_status "$R_PORT" "$R_COMMAND"
;;
used_cpu_sys)
redis_status "$R_PORT" "$R_COMMAND"
;;
total_commands_processed)
redis_status "$R_PORT" "$R_COMMAND"
;;
role)
redis_status "$R_PORT" "$R_COMMAND"
;;
lru_clock)
redis_status "$R_PORT" "$R_COMMAND"
;;
latest_fork_usec)
redis_status "$R_PORT" "$R_COMMAND"
;;
keyspace_misses)
redis_status "$R_PORT" "$R_COMMAND"
;;
keyspace_hits)
redis_status "$R_PORT" "$R_COMMAND"
;;
keys)
redis_status "$R_PORT" "$R_COMMAND"
;;
expires)
redis_status "$R_PORT" "$R_COMMAND"
;;
expired_keys)
redis_status "$R_PORT" "$R_COMMAND"
;;
evicted_keys)
redis_status "$R_PORT" "$R_COMMAND"
;;
connected_clients)
redis_status "$R_PORT" "$R_COMMAND"
;;
changes_since_last_save)
redis_status "$R_PORT" "$R_COMMAND"
;;
blocked_clients)
redis_status "$R_PORT" "$R_COMMAND"
;;
bgsave_in_progress)
redis_status "$R_PORT" "$R_COMMAND"
;;
bgrewriteaof_in_progress)
redis_status "$R_PORT" "$R_COMMAND"
;;
used_memory_peak)
redis_status "$R_PORT" "$R_COMMAND"
;;
used_memory)
redis_status "$R_PORT" "$R_COMMAND"
;;
used_cpu_user)
redis_status "$R_PORT" "$R_COMMAND"
;;
used_cpu_sys_children)
redis_status "$R_PORT" "$R_COMMAND"
;;
total_connections_received)
redis_status "$R_PORT" "$R_COMMAND"
;;
*)
echo $"USAGE:$0 {used_cpu_user_children|used_cpu_sys|total_commands_processed|role|lru_clock|latest_fork_usec|keyspace_misses|keyspace_hits|keys|expires|expired_keys|connected_clients|changes_since_last_save|blocked_clients|bgrewriteaof_in_progress|used_memory_peak|used_memory|used_cpu_user|used_cpu_sys_children|total_connections_received}"
esac

Redis状态参数解释:

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
server : Redis 服务器信息,包含以下域:
redis_version : Redis 服务器版本
redis_git_sha1 : Git SHA1
redis_git_dirty : Git dirty flag
os : Redis 服务器的宿主操作系统
arch_bits : 架构(32 或 64 位)
multiplexing_api : Redis 所使用的事件处理机制
gcc_version : 编译 Redis 时所使用的 GCC 版本
process_id : 服务器进程的 PID
run_id : Redis 服务器的随机标识符(用于 Sentinel 和集群)
tcp_port : TCP/IP 监听端口
uptime_in_seconds : 自 Redis 服务器启动以来,经过的秒数
uptime_in_days : 自 Redis 服务器启动以来,经过的天数
lru_clock : 以分钟为单位进行自增的时钟,用于 LRU 管理
clients : 已连接客户端信息,包含以下域:
connected_clients : 已连接客户端的数量(不包括通过从属服务器连接的客户端)
client_longest_output_list : 当前连接的客户端当中,最长的输出列表
client_longest_input_buf : 当前连接的客户端当中,最大输入缓存
blocked_clients : 正在等待阻塞命令(BLPOP、BRPOP、BRPOPLPUSH)的客户端的数量
memory : 内存信息,包含以下域:
used_memory : 由 Redis 分配器分配的内存总量,以字节(byte)为单位
used_memory_human : 以人类可读的格式返回 Redis 分配的内存总量
used_memory_rss : 从操作系统的角度,返回 Redis 已分配的内存总量(俗称常驻集大小)。这个值和 top 、 ps 等命令的输出一致。
used_memory_peak : Redis 的内存消耗峰值(以字节为单位)
used_memory_peak_human : 以人类可读的格式返回 Redis 的内存消耗峰值
used_memory_lua : Lua 引擎所使用的内存大小(以字节为单位)
mem_fragmentation_ratio : used_memory_rss 和 used_memory 之间的比率
persistence : RDB 和 AOF 的相关信息
stats : 一般统计信息
replication : 主/从复制信息
cpu : CPU 计算量统计信息
commandstats : Redis 命令统计信息
cluster : Redis 集群信息
keyspace : 数据库相关的统计信息
参数还可以是下面这两个:
all : 返回所有信息
default : 返回默认选择的信息
当不带参数直接调用 INFO 命令时,使用 default 作为默认参数。

3.添加脚本执行权限

1
[root@Agent ~]# chmod +x /etc/zabbix/scripts/redis_status.sh

4.Zabbix权限不足处理办法

1
[root@Agent ~]# rm -f /tmp/redis_6379.tmp

5.key的redis_status.conf的配置文件如下:

1
2
[root@Agent ~]# cat /etc/zabbix/zabbix_agentd.d/redis_status.conf
UserParameter=redis_status[*],/bin/bash /etc/zabbix/scripts/redis_status.sh "$1"

6.重启zabbix-agent

1
[root@Agent ~]# systemctl restart  zabbix-agent

7.在Zabbix-Server使用Zabbix_get获取值

1
2
[root@Server ~]# zabbix_get -s 10.0.0.7 -k redis_status[used_cpu_sys]
16.81

zabbix监控JVM(JAVA)

在Zabbix中,JMX监控数据的获取由专门的代理程序来实现,即Zabbix-Java-Gateway来负责数据的采集,Zabbix-Java-Gateway和JMX的Java程序之间通信获取数据.

JMX在zabbix中运行的流程

1
2
3
4
5
1.Zabbix-Server找Zabbix-Java-Gateway获取Java数据
2.Zabbix-Java-Gateway找Java程序获取数据
3.Java程序返回数据给Zabbix-Java-Gateway
4.Zabbix-Java-Gateway返回数据给Zabbix-Server
5.Zabbix-Server进行数据展示

JMX监控配置步骤

1
2
3
4
5
1.安装Zabbix-Java-Gateway。
2.配置zabbix_java_gateway.conf参数。
3.配置zabbix-server.conf参数。
4.Tomcat应用开启JMX协议。
5.ZabbixWeb配置JMX监控的Java应用。
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
zabbix-java-gateway
# 1.安装Java容器Tomcat
[root@web01 ~]# yum install -y tomcat

# 2.安装zabbix-java-gateway
[root@web01 ~]# rpm -ivh https://mirrors.aliyun.com/zabbix/zabbix/5.0/rhel/7/x86_64/zabbix-java-gateway-5.0.26-1.el7.x86_64.rpm?spm=a2c6h.25603864.0.0.2ed62e2fPf8hxu

# 3.修改java-gateway配置文件
[root@web01 ~]# vim /etc/zabbix/zabbix_java_gateway.conf

# 4.启动java-gateway
[root@web01 ~]# systemctl start zabbix-java-gateway.service
[root@web01 ~]# netstat -lntup|grep 10052
tcp6 0 0 :::10052 :::* LISTEN 85993/java

# 5.修改服务端配置
[root@sb_wzj ~]# vim /etc/zabbix/zabbix_server.conf
## java-gateway的地址
JavaGateway=172.16.1.7
## java-gateway的端口
JavaGatewayPort=10052
## java-gateway轮询
StartJavaPollers=5

# 6.重启服务端
[root@sb_wzj ~]# systemctl restart zabbix-server

# 7.修改tomcat启动脚本
[root@web01 ~]# vim /usr/libexec/tomcat/server
CATALINA_OPTS="$CATALINA_OPTS
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=12345
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=172.16.1.7"

image-20230325230723513

image-20230325230728525

image-20230325230743639

image-20230325230748084

image-20230325230752766

zabbix自定义监控阶段小结

zabbix监控基础架构回顾

image-20230325230801363

Zabbix监控方式:

  • agent:客户端监控
  • SNMP:监控网络设备(交换机)
  • IPMI:监控主机硬件设备(Dell R710 R720 R730 远程管理卡)
  • JMX:监控JAVA的JVM

Zabbix资源回顾(基于监控项基础的所有资源)

Zabbix Web检测

什么是静态网站、动态网站

静态网站:纯静态网站就是服务器的源代码和客户端的源代码一致。动态网站:比如: <?php phpinfo()?>每次用户访问的时候,内容都是在内存中动态生成的。动态网站支持登陆,支持用户交互,所以用户在请求动态网站时,会给客户端下发一个叫sessionID的内容,那么客户端则会将SessionID保存至浏览器的cookie中。

session和cookie的工作流程

1) 当用户首次访问动态网站时,是不会携带cookie信息,那么在服务端返回网页的时候,会给该客户端的浏览器分配一个唯一的sessionID,客户端会该sessionID存储至浏览器的Cookie中。

2) 当用户再次访问网站时,浏览器会在Header头信息添加Set-Cookie,Set-Cookie携带的则是该网站对应的sessionID信息,服务端接收后会进行校验

image-20230327193629589

使用命令模拟用户登录网站

1
2
3
4
5
6
7
8
[root@web01 ~]# curl -L -c cook -b cook 'http://zabbix.zls.com/index.php'
#-b:cookie字符串或文件读取位置,使用option来把上次的cookie信息追加到http request里面去。
#-c:操作结束后把cookie写入到这个文件中web01

[root@web01 ~]# curl -L -c cook -b cook -d 'name=Admin&password=zabbix&autologin=1&enter=Sign+in' 'http://zabbix.zls.com/index.php'
#-d: 以POST的请方式携带头部信息请求

[root@web01 ~]# curl -L -c cook -b cook 'http://zabbix.zls.com/queue.php'

zabbix监控web网站

我们使用Zabbix Web 监控来监控Zabbix的Web界面。我们想知道它是否可用、是否正常工作以及响应速度。所以我们必须使用用户名和密码登录。

image-20230327193643276

image-20230327193648143

在新的场景中,我们将场景命名为”监控zabbix服务器”,并为其创建一个新的应用 (application )。

image-20230327193812116

image-20230327193816674

image-20230327193821139

1
2
## zabbix5.0版本
regex:name="csrf-token" content="([0-9a-z]{16})"

image-20230327193829056

注意:一定要勾选跟随跳转

image-20230327193834210

image-20230327193841194

image-20230327193846541

Zabbix自动化监控

zabbix工作模式

  • 主动模式:自动注册
  • 被动模式:自动发现

自动发现

zabbix的服务端,扫描IP网段,该网段上,只要安装了zabbix agent并且配置了服务端的IP,zabbix-server会自动将发现的主机加入到资产中。

当网络发现正确设置后你可以:
1.加快Zabbix部署
2.简化管理
3.无需过多管理就能在快速变化的环境中使用Zabbix


Zabbix网络发现基于以下信息:
1.IP范围
2.可用的外部服务(FTP,SSH,WEB,POP3,IMAP,TCP等)
3.来自 zabbix agent 的信息(仅支持未加密模式)
4.来自 snmp agent 的信息


不支持:
1.发现网络拓扑

自动发现配置

1
2
3
4
5
6
7
8
9
# 1.安装zabbix客户端
rpm -ivh https://mirrors.aliyun.com/zabbix/zabbix/5.0/rhel/7/x86_64/zabbix-agent-5.0.26-1.el7.x86_64.rpm?spm=a2c6h.25603864.0.0.20ba2e2fnfcAbB

# 2.修改客户端配置文件
[root@db02 ~]# vim /etc/zabbix/zabbix_agentd.conf
Server=172.16.1.61
[root@db02 ~]# systemctl start zabbix-agent

# 3.配置自动发现的规则

image-20230327203220851

image-20230327203226763

将动作和自动发现关联

image-20230327203242215

image-20230327203250464

image-20230327203255583

image-20230327203300125

1
2
3
4
5
6
7
8
9
10
11
默认标题
自动发现主机IP:{DISCOVERY.DEVICE.IPADDRESS}

消息内容
客户端IP:{DISCOVERY.DEVICE.IPADDRESS}
客户端名称: {DISCOVERY.SERVICE.NAME}
客户端端口: {DISCOVERY.SERVICE.PORT}
客户端状态: {DISCOVERY.SERVICE.STATUS}

操作动作
添加主机,添加主机组,链接模板,发送邮件,等等

image-20230327203308430

image-20230327203312586

zabbix自动发现小结

1
2
3
4
1.网络发现速度太慢
2.轮询扫描网段
3.如果网段中存在不通的主机,会出现卡顿并且造成后续新增的服务器无法加入节点
4.会导致server性能变缓慢,影响server性能

zabbix自动注册(主动)

Zabbix agent可以自动注册到服务器进行监控。这种方式无需在服务器上手动配置它们。自动注册官方手册

1
2
3
4
5
6
7
8
[root@web01 ~]# vim /etc/zabbix/zabbix_agentd.conf
Server=172.16.1.61 ## 被动模式
ServerActive=172.16.1.61 ## 主动模式
Hostname=web01

Server=172.16.1.61 ## 被动模式
ServerActive=172.16.1.61 ## 主动模式
Hostname={{ ansible.fqdn }}

image-20230327203336168

image-20230327203340716

1
2
3
4
Zabbix自动注册
主机名:{HOST.HOST}
主机IP:{HOST.IP}
主机端口:{HOST.PORT}