linux监控命令nc用法
一、nc命令检测端口的用法
# nc -v -w 10 %IP% -z %PORT%
-v 显示指令执行过程。
-w <超时秒数> 设置等待连线的时间。
-u 表示使用UDP协议
-z 使用0输入/输出模式,只在扫描通信端口时使用。
例1:扫描指定的8080端口
# nc -v -w 10 -z 192.168.0.100 8080
Connection to 192.168.0.100 8080 port [tcp/http] succeeded!
例2:扫描20到25的端口范围,并详细输出。
# nc -v -w 2 -z 192.168.0.100 20-25
nc: connect to 192.168.0.100 port 20 (tcp) failed: Connection refused
nc: connect to 192.168.0.100 port 21 (tcp) failed: Connection refused
Connection to 192.168.0.100 22 port [tcp/ssh] succeeded!
nc: connect to 192.168.0.100 port 23 (tcp) failed: Connection refused
nc: connect to 192.168.0.100 port 24 (tcp) failed: Connection refused
nc: connect to 192.168.0.100 port 25 (tcp) failed: Connection refused
例3:扫描1到65535的端口范围,只输出打开的端口(去掉-v参数即可)
# nc -w 1 -z 192.168.0.100 1-65535
Connection to 192.168.0.100 22 port [tcp/ssh] succeeded!
Connection to 192.168.0.100 80 port [tcp/http] succeeded!
Connection to 192.168.0.100 2121 port [tcp/scientia-ssdb] succeeded!
Connection to 192.168.0.100 4004 port [tcp/pxc-roid] succeeded!
Connection to 192.168.0.100 8081 port [tcp/tproxy] succeeded!
Connection to 192.168.0.100 11211 port [tcp/*] succeeded!
二、批量检测服务器指定端口开放情况:
1、假如我们要监控一堆指定的IP和端口,可新建一个文件(第1列服务器IP,第2列要监控的端口)。
# vim /scripts/ip-ports.txt
192.168.0.100 80
192.168.0.100 8081
192.168.0.101 8082
192.168.1.100 21
2、我们可以写这样一个脚本来批量检测端口是否开放:
# vim /scripts/ncports.sh
#!/bin/bash
#检测服务器端口是否开放,成功会返回0值显示ok,失败会返回1值显示fail
cat /scripts/ip-ports.txt | while read line
do
nc -w 10 -z $line > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo $line:ok
else
echo $line:fail
fi
done
3、执行脚本查看运行结果如下:
# chmod a+x /scripts/ncports.sh
# /scripts/ncports.sh
192.168.0.100 80:ok
192.168.0.100 8081:ok
192.168.0.101 8082:ok
192.168.1.100 21:fail
3、端口不通时发送邮件并消息弹窗告警的脚本如下:
# vim /scripts/ncports.sh
#!/bin/bash
#检测服务器端口是否开放,成功会返回0值,打不开会返回1值
cat /scripts/ip-ports.txt | while read line
do
nc -w 10 -z $line > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo $line:ok
else
echo $line:fail
echo ”服务器 $line 端口不通,请尽快处理!” | mail -s ”【机房监控】服务器$line端口不通” xxx@xxx.com
fi
done
4、加入任务计划每2分钟执行一次
# crontab -e
*/2 * * * * /scripts/ncports.sh > /dev/null 2>&1