Centos7 uses the NC detection port

1.1 Installing the NC Tool

yum install nc -y
Copy the code

1.2 Port Detection

  • TCP Port Detection

Usage:

Nc-w 1 IP address port < /dev/null && echo "TCP port OK"Copy the code

For example,

< /dev/null && echo "TCP port ok" TCP port ok: < /dev/null && echo "TCP port ok" Ncat: Connection refused.Copy the code
  • UDP Port Detection

Usage:

Nc-u -w 1 IP address port < /dev/null && echo "udp port OK"Copy the code

For example,

# nc-u -w 1 192.168.21.17 34567 < /dev/null && echo -e "udp port ok" udp port OKCopy the code

2. The NC tool detects ports in real time

If we need to perform port detection every second, use the following method

2.1 Writing shell Scripts

# 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 doneCopy the code

2.2 Background Running

  • Background script
screen -S nc-tcp /bin/bash /opt/scripts/tcp/detection.sh
Copy the code

Note: If we want to exit Screen but keep the process running in the background, we need to use Ctrl + A + D to exit

  • Verify that each second is executed
# 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 
Copy the code

2.3 Screen for other use

  • View background tasks
# screen -ls
There are screens on:
	17829.nc-tcp	(Detached)
Copy the code

Attached: Someone is operating, so you can only join

Detached: The background runs automatically. No one is involved at present. You can join and restore

  • Re-enter the Screen session
# screen -r nc-tcp
Copy the code
  • Closing screen Session
The shortcut key: Ctrl+ C will prompt: [screen is terminating], indicating that the screen session has been successfully terminated.Copy the code