使用Python脚本检测IP地址
-
安装所需的库:
- 打开终端,运行以下命令安装
requests和ipaddress库:pip install requests ipaddress
- 打开终端,运行以下命令安装
-
编写检测脚本:
- 创建一个Python脚本,读取IP地址列表,并逐一检测每个IP。
import requests from ipaddress import IPv4Address # 读取IP地址列表 ips = ['192.168.1.1', '172.217.14.206', '8.8.8.8'] # 检测每个IP for ip_str in ips: try: # 使用requests检测HTTP响应 response = requests.get(f"http://{ip_str}", timeout=5, headers={'User-Agent': 'Mozilla/5.'}) print(f"{ip_str} 可达,状态码:{response.status_code}") except requests.exceptions.RequestException as e: try: ip_obj = IPv4Address(ip_str) print(f"{ip_str} 是有效IP地址,但可能不可达或防火墙阻止了连接。") except ValueError: print(f"{ip_str} 不是一个有效的IPv4地址。") -
运行脚本:
- 保存上述代码为
ip_detector.py,然后运行:python3 ip_detector.py
- 保存上述代码为
使用ipinfo命令检测IP地址
-
安装
ipinfo:- 在终端中运行:
pip install ipinfo
- 在终端中运行:
-
检测IP地址:
- 在终端中运行:
ipinfo 192.168.1.1
- 或者检测自己的公网IP:
ipinfo 0...
- 在终端中运行:
使用curl命令检测IP地址
-
检测特定IP:
curl -I http://192.168.1.1
-
检测自己的IP:
curl -I http://myip.ipinfo.net
使用traceroute检测IP地址
-
检测特定IP:
traceroute 192.168.1.1
-
检测自己的IP:
traceroute 0...
使用whois命令获取IP信息
- 检测IP地址和信息:
whois 192.168.1.1
requests库:适合编写自动化脚本,检测多个IP地址,处理异常情况。ipinfo命令:简单易用,适合快速获取IP信息。curl命令:适合从终端检测IP地址,返回HTTP响应头信息。traceroute命令:适合检测网络路径,检查IP是否在网络中。whois命令:获取IP地址的详细信息,包括地理位置和注册信息。
根据具体需求选择合适的工具,可以通过脚本批量处理多个IP地址,或者使用命令行工具进行简单检测。









