How to batch check ports using the “nc” command in Linux?
In Linux, you can use Shell scripts in conjunction with the nc command to batch test ports.
Here is a simple example script:
#!/bin/bash
# 定义需要检测的IP地址和端口范围
IP_ADDRESS="192.168.0.1"
PORT_RANGE="1-100"
# 循环遍历端口范围
for PORT in $(seq $PORT_RANGE); do
# 使用nc命令检测端口是否开放
nc -zvw 1 $IP_ADDRESS $PORT
# 检查nc命令的返回值,如果为0则端口开放,否则端口关闭
if [ $? -eq 0 ]; then
echo "端口 $PORT 开放"
else
echo "端口 $PORT 关闭"
fi
done
In the script, first define the IP address and port range that need to be checked. Then use the ‘seq’ command to generate a sequence of ports in the range. Next, use the ‘nc -zvw 1’ command to check if each port is open, with the ‘-z’ parameter indicating only port scanning, the ‘-v’ parameter displaying detailed output, and the ‘-w 1’ parameter setting a timeout of 1 second. Finally, based on the return value of the ‘nc’ command, determine if the port is open and output the result.
Save the script file, such as port_check.sh, and then execute sh port_check.sh in the terminal to batch check ports. Set IP_ADDRESS to the IP address you want to check, and PORT_RANGE to the range of ports you want to check.