您当前的位置: 首页 >  linux
  • 2浏览

    0关注

    212博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Linux】 Centos7 nc探测端口命令并实时探测

杰哥的技术杂货铺 发布时间:2021-07-02 15:16:23 ,浏览量:2

文章目录
  • 一. centos7 系统使用nc探测端口
    • 1.1 安装nc工具
    • 1.2 端口探测
  • 二.nc工具实时探测端口
    • 2.1 编写shell脚本
    • 2.2 后台运行
    • 2.3 screen其它使用

一. centos7 系统使用nc探测端口 1.1 安装nc工具
yum install nc -y
1.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
done
2.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 ok 
2.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会话。
关注
打赏
1666063422
查看更多评论
立即登录/注册

微信扫码登录

0.0417s