0
点赞
收藏
分享

微信扫一扫

数字化营销在公域场景中的无限可能

Linux 通过Shell脚本来实现读取txt文件中的IP地址,并使用telnet对其后的所有端口进行测试,判断是否可以连接。每个IP地址的端口测试时间限制为5秒。

IP文件 : ips.txt

192.168.1.1 22,80,443
192.168.1.2 21,25,110
192.168.1.3 8080

每一行包含一个IP地址和对应的端口列表,端口之间使用逗号隔开。

Shell脚本

#!/bin/bash

# 文件路径
file="ip_list.txt"

# 检查文件是否存在
if [ ! -f "$file" ]; then
    echo "文件 $file 不存在"
    exit 1
fi

# 读取文件并逐行处理
while IFS= read -r line
do
    # 提取当前行的第一个字段(IP地址)
    ip=$(echo $line | awk '{print $1}')
    # 提取当前行的其他字段(端口)
    ports=$(echo $line | awk '{print $2}')
    
    # 将端口列表按逗号分割
    IFS=',' read -r -a port_array <<< "$ports"

    echo "Testing IP: $ip"

    # 遍历每个端口进行测试
    for port in "${port_array[@]}"
    do
        echo "Testing port $port on $ip..."
        
        # 使用timeout命令限制telnet命令的执行时间不超过5秒
        # 尝试使用telnet连接到指定的IP和端口。如果连接成功,命令的退出状态为0,否则为非0
        timeout 5 bash -c "echo > /dev/tcp/$ip/$port" 2>/dev/null
        
        if [ $? -eq 0 ]; then
            echo "Port $port on $ip is open"
        else
            echo "Port $port on $ip is closed or filtered"
        fi
    done

    echo "*****************"
done < "$file"
举报

相关推荐

0 条评论