1.端口监控
**netstat ss lsof**
[root@localhost ~]# netstat -antlupe |grep 3306
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 27 115506 11097/mysqld
[root@localhost ~]# netstat -antlupe |grep 3306 |awk -F '[ :]+' '{print $5}'
3306
[root@localhost ~]#
对端口进程进行判断时,尽量先通过grep过滤端口和进程标记特殊字符串,然后结合 wc -l (统计输出的行数) 将结果转成行数再进行比较,这样相对简单有效
[root@localhost ~]# netstat -antlupe |grep mysql |wc -l
1
[root@localhost ~]# ss -antlupe |grep mysql |wc -l
1
[root@localhost ~]#
ss命令类似于netstat命令,参数选项可通用
[root@localhost ~]# yum install lsof -y
Loaded plugins: langpacks
Package lsof-4.87-4.el7.x86_64 already installed and latest version
Nothing to do
[root@localhost ~]# lsof -i tcp:3306 |wc -l
2
[root@localhost ~]#
2.远程监控本地端口
**telnet nmap**
[root@localhost ~]# yum install telnt nmap -y
[root@localhost ~]# nmap 172.25.254.10 -p 3306
Starting Nmap 6.40 ( http://nmap.org ) at 2020-02-16 03:35 EST
Nmap scan report for 172.25.254.10
Host is up (0.000056s latency).
PORT STATE SERVICE
3306/tcp open mysql
Nmap done: 1 IP address (1 host up) scanned in 14.03 seconds
[root@localhost ~]# nmap 172.25.254.10 -p 3306 |grep open
3306/tcp open mysql
[root@localhost ~]# nmap 172.25.254.10 -p 3306 |grep open |wc -l
1
[root@localhost ~]#
[root@localhost ~]# telnet 172.25.254.10 3306 2>/dev/null
Trying 172.25.254.10...
Connected to 172.25.254.10.
Escape character is '^]'.
HHost '172.25.254.10' is not allowed to connect to this MariaDB server[root@localhost ~]#
[root@localhost ~]# echo -e "\n" |telnet 172.25.254.10 3306 2>/dev/null |grep Connected |wc -l
1
[root@localhost ~]# |telnet 172.25.254.10 3306 2>/dev/null |grep Connected |wc -l
-bash: syntax error near unexpected token `|'
[root@localhost ~]# telnet 172.25.254.10 3306 2>/dev/null |grep Connected |wc -l
1
[root@localhost ~]# telnet 172.25.254.10 3306
Trying 172.25.254.10...
Connected to 172.25.254.10.
Escape character is '^]'.
HHost '172.25.254.10' is not allowed to connect to this MariaDB serverConnection closed by foreign host.
[root@localhost ~]#
3.对服务进程或者进程数进行监控
[root@localhost ~]# ps -ef |grep mysql
mysql 10939 1 0 03:09 ? 00:00:00 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
mysql 11097 10939 0 03:09 ? 00:00:01 /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 16073 2153 0 03:44 pts/1 00:00:00 grep --color=auto mysql
[root@localhost ~]# ps -ef |grep mysql |grep -v grep |wc -l
2
[root@localhost ~]# pgrep mysql #进程号
10939
11097
[root@localhost ~]# echo $?
0
[root@localhost ~]#
4.脚本示例
#!/bin/bash
if [ "`netstat -antlupe |grep 3306 |awk -F '[ :]+' '{print $5}'`" = "3306" ];then
echo "mysql is running"
else
echo "mysql is stopped"
fi