import requests
from openpyxl import Workbook
# 建立一個工作簿
wb = Workbook()
# 新增一個工作表
ws = wb.active
# 讀取檔案中的域名
with open("domains.txt", "r") as f:
domains = f.readlines()
# 遍歷域名,獲取對應的IP地址
for domain in domains:
# 去除註釋和空格
domain = domain.strip().split("#")[0].strip()
# 檢查是否為域名
if domain:
try:
# 請求ip.cn獲取IP地址
response = requests.get(f"https://ip.cn/index.php?ip={domain}&language=cn", timeout=10)
# 解析網頁內容
html = response.text
# 提取IP地址
ip_address = ""
if "IP:" in html:
start_index = html.index("IP:") + 3
end_index = html.index(" ", start_index)
ip_address = html[start_index:end_index]
# 將域名和IP地址寫入工作表
ws.append([domain, ip_address])
except requests.exceptions.ConnectionError:
ws.append([domain, "Error: ConnectionError"])
except requests.exceptions.Timeout:
ws.append([domain, "Error: Timeout"])
except requests.exceptions.RequestException as e:
ws.append([domain, f"Error: {str(e)}"])
# 儲存工作簿為ods檔案
wb.save("domains_ip.ods")