1. Shell脚本内容
vim detect_port.sh
#!/bin/bash
# 功能:批量检测IP的各端口连通性
# 输入:82_port.txt(每行一个IP地址,数字82为服务器IP最后一个字段)
read -p "1)118.118.118.118
2)47.47.47.47
3)115.115.115.115
4)92.92.92.92
请输入检测的目标IP地址:" IP_address
server_IP=$IP_address
server_alias=`echo $server_IP | awk -F'.' '{ print $4}'`
# 检查文件是否存在
if [ ! -f "/root/port/${server_alias}_port.txt" ]; then
echo "错误:未找到端口列表文件"
exit 1
fi
# 结果输出文件
OUTPUT="${server_IP}_port_check_result.txt"
echo "$server_IP,端口状态" > $OUTPUT
# 循环处理每个端口
while read -r PORT; do
PORT=${PORT//[$'\t\r\n']} # 清除换行符
# 使用TCP连接检测
timeout 2 bash -c "echo >/dev/tcp/$server_IP/$PORT" &>/dev/null
if [ $? -eq 0 ]; then
#端口已连通用绿色标识
echo -e "\e[32m $server_IP $PORT 端口已连通\e[0m"
else
#端口不可达用红色标识
echo -e "\e[31m $server_IP $PORT 端口不可达\e[0m"
fi
# 记录结果
#echo "$PORT,$status" >> $OUTPUT
done < ${server_alias}_port.txt
2. 文档目录结构
[root@centos79-20251123 port]# pwd
/root/port
[root@centos79-20251123 port]# ll
total 64-w-r--r-- 1 root root 17 Sep 17 14:59 118_port.txt
-rw-r--r-- 1 root root 33 Sep 17 15:01 47_port.txt
-rw-r--r-- 1 root root 59 Sep 17 15:01 115_port.txt
-rw-r--r-- 1 root root 162 Sep 17 15:00 92_port.txt
-rw-r--r-- 1 root root 2010 Oct 21 08:42 detect_port.sh
[root@centos79-20251123 port]# cat 118_port.txt
10410
12413
15412
19510
19513
19514
61231
29373
19017
9519
9576
40510
20975
47475
1745

被折叠的 条评论
为什么被折叠?



