shell编程实战-服务的监控脚本的编写

监控web和数据库

监测mysql数据库异常:

安装数据库并启动:

yum install mariadb* -y
systemctl start mariadb

首先采用端口监控的方式:

1.1在服务器本地监控端口的命令有:netstat ss lsof
1.netstat:

[root@localhost ~]# netstat -antlupe | grep 3306
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      27         151465     7676/mysqld
[root@localhost ~]# netstat -antlupe | grep 3306 | wc -l
1
[root@localhost ~]# netstat -antlupe | grep 3306 | awk -F "[ :]+" '{print $5}'
3306

2.ss:

[root@localhost ~]# ss -antlupe | grep mysql
tcp    LISTEN     0      50                     *:3306                  *:*      users:(("mysqld",7676,14)) uid:27 ino:151465 sk:ffff880024ab8780 <->
[root@localhost ~]# ss -antlupe | grep mysql | wc -l
1

3.lsof:

使用此命令时若报错需要先安装:

[root@localhost ~]# yum install lsof-4.87-4.el7.x86_64 -y

使用此命令监控:

[root@localhost ~]# lsof -i tcp:3306
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
mysqld  7676 mysql   14u  IPv4 151465      0t0  TCP *:mysql (LISTEN)
[root@localhost ~]# lsof -i tcp:3306 | wc -l
2

1.2 远程监控:

nmap远程监控命令:
若提示没有该命令需要安装:

yum install nmap-6.40-7.el7.x86_64 -y

监控:

[root@localhost ~]# nmap 172.25.254.63 -p 80

Starting Nmap 6.40 ( http://nmap.org ) at 2020-02-16 11:36 EST
Nmap scan report for 172.25.254.63
Host is up (0.00013s latency).
PORT   STATE SERVICE
80/tcp open  http
MAC Address: A8:1E:84:18:2A:23 (Unknown)

Nmap done: 1 IP address (1 host up) scanned in 13.43 seconds
[root@localhost ~]# nmap 172.25.254.63 -p 80 | grep open			#过滤open关键字
80/tcp open  http
[root@localhost ~]# nmap 172.25.254.63 -p 80 | grep open |wc -l
1

采用进程监控的方式
对服务器进程或者进程数进行监控(适合本地服务器)

扫描二维码关注公众号,回复: 9596275 查看本文章
[root@localhost ~]# ps -ef | grep mysql
mysql     8105     1  0 11:34 ?        00:00:00 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
mysql     8263  8105  0 11:34 ?        00:00:00 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/log/mariadb/mariadb.log --pid-file=/var/run/mariadb/mariadb.pid --socket=/var/lib/mysql/mysql.sock
root      8437  2285  0 11:46 pts/1    00:00:00 grep --color=auto mysql
[root@localhost ~]# ps -ef | grep mysql |wc -l
3
[root@localhost ~]# ps -ef | grep mysql |grep -v grep|wc -l					#将grep的进程过滤掉
2

开发监控Mysql数据库的脚本
编写脚本:

[root@localhost mnt]# cat check_mysql.sh 
#!/bin/bash
if [ "`netstat -antlupe | grep 3306 | awk -F "[ :]+" '{print $5}'`" = "3306" ];then
	echo "MySQL is running."
else
	echo "MySQL is stopping"
	/etc/init.d/mysqld start
fi

测试:

[root@localhost mnt]# systemctl start mariadb
[root@localhost mnt]# sh check_mysql.sh 
MySQL is running.
[root@localhost mnt]# systemctl stop mariadb
[root@localhost mnt]# sh check_mysql.sh 
MySQL is stopping
发布了94 篇原创文章 · 获赞 1 · 访问量 1764

猜你喜欢

转载自blog.csdn.net/qq_36417677/article/details/104431919