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

朱雀 2023-07-07 08:07 71阅读 0赞

监控web和数据库

监测mysql数据库异常:

安装数据库并启动:

  1. yum install mariadb* -y
  2. systemctl start mariadb

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

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

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

2.ss:

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

3.lsof:

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

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

使用此命令监控:

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

1.2 远程监控:

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

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

监控:

  1. [root@localhost ~]# nmap 172.25.254.63 -p 80
  2. Starting Nmap 6.40 ( http://nmap.org ) at 2020-02-16 11:36 EST
  3. Nmap scan report for 172.25.254.63
  4. Host is up (0.00013s latency).
  5. PORT STATE SERVICE
  6. 80/tcp open http
  7. MAC Address: A8:1E:84:18:2A:23 (Unknown)
  8. Nmap done: 1 IP address (1 host up) scanned in 13.43 seconds
  9. [root@localhost ~]# nmap 172.25.254.63 -p 80 | grep open #过滤open关键字
  10. 80/tcp open http
  11. [root@localhost ~]# nmap 172.25.254.63 -p 80 | grep open |wc -l
  12. 1

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

  1. [root@localhost ~]# ps -ef | grep mysql
  2. mysql 8105 1 0 11:34 ? 00:00:00 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
  3. 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
  4. root 8437 2285 0 11:46 pts/1 00:00:00 grep --color=auto mysql
  5. [root@localhost ~]# ps -ef | grep mysql |wc -l
  6. 3
  7. [root@localhost ~]# ps -ef | grep mysql |grep -v grep|wc -l #将grep的进程过滤掉
  8. 2

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

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

测试:

  1. [root@localhost mnt]# systemctl start mariadb
  2. [root@localhost mnt]# sh check_mysql.sh
  3. MySQL is running.
  4. [root@localhost mnt]# systemctl stop mariadb
  5. [root@localhost mnt]# sh check_mysql.sh
  6. MySQL is stopping

发表评论

表情:
评论列表 (有 0 条评论,71人围观)

还没有评论,来说两句吧...

相关阅读