【Linux】 Centos7 nc探测端口命令并实时探测
文章目录
一. centos7 系统使用nc探测端口
1.1 安装nc工具
yum install nc -y1.2 端口探测
- TCP端口探测
使用方法:
nc -w 1 IP地址 端口 < /dev/null && echo "tcp port ok"举例
对方tcp端口可连接:
# nc -w 1 192.168.21.17 34567 < /dev/null && echo "tcp port ok"
tcp port ok
对方tcp端口不可连接:
# nc -w 1 192.168.21.17 34567 < /dev/null && echo "tcp port ok"
Ncat: Connection refused.- UDP端口探测
使用方法:
nc -u -w 1 IP地址 端口 < /dev/null && echo "udp port ok"举例
对方tcp端口可连接:
# nc -u -w 1 192.168.21.17 34567 < /dev/null && echo -e "udp port ok"
udp port ok二.nc工具实时探测端口
如果我们需要每秒执行一次端口检测,则使用以下方法
2.1 编写shell脚本
# vim /opt/scripts/tcp/detection.sh
#!/bin/bash
while [ true ]; do
/bin/sleep 1
ttime=`date "+%F %T"`
log=`nc -w 1 192.168.21.17 34567 < /dev/null && echo -e "\033[32m tcp port ok \033[0m"`
echo "$ttime $log" >> /opt/scripts/tcp/tcp.log
done2.2 后台运行
后台运行脚本
screen -S nc-tcp /bin/bash /opt/scripts/tcp/detection.sh注意:如果我们需要退出screen,但保持进程后台运行,需要使用Ctrl键+a+d 进行退出
确认每秒是否执行
# tail -f /opt/scripts/tcp/tcp.log 2021-07-02 14:46:54 tcp port ok 2021-07-02 14:46:55 tcp port ok 2021-07-02 14:46:56 tcp port ok 2021-07-02 14:46:57 tcp port ok 2021-07-02 14:46:58 tcp port ok 2021-07-02 14:46:59 tcp port ok2.3 screen其它使用
查看当前有哪些后台任务
# screen -ls There are screens on: 17829.nc-tcp (Detached)联系状态(Attached):有人在操作,只能加入
派遣状态(Detached):后台自动运行,当前无人参与,可以加入、还原
重新进入screen会话
# screen -r nc-tcp关闭screen会话
快捷键:Ctrl+c 会提示:[screen is terminating],表示已经成功退出screen会话。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论