File size: 19,603 Bytes
960d693 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 |
import requests
import re
from datetime import datetime, timedelta
import psutil # 用于获取系统启动时间
import pytz # 用于处理时区
import os # 用于检查文件是否存在
import traceback # 用于获取详细错误信息
def get_current_ip():
"""获取当前公共 IP 地址"""
try:
response = requests.get("https://ipinfo.io/ip")
return response.text.strip()
except Exception as e:
print(f"获取IP地址时出错: {e}")
return None
# 添加英文到中文的国家名称映射
def get_country_name_in_chinese(english_name):
"""将英文国家名称转换为中文"""
country_map = {
"United States": "美国",
"United Kingdom": "英国",
"Russia": "俄罗斯",
"Japan": "日本",
"China": "中国",
"Germany": "德国",
"France": "法国",
"Italy": "意大利",
"Canada": "加拿大",
"Australia": "澳大利亚",
"Brazil": "巴西",
"India": "印度",
"Singapore": "新加坡",
"Netherlands": "荷兰",
"South Korea": "韩国",
"Hong Kong": "香港",
"Taiwan": "台湾",
"Spain": "西班牙",
"Sweden": "瑞典",
"Switzerland": "瑞士",
"Norway": "挪威",
"Denmark": "丹麦",
"Finland": "芬兰",
"Ireland": "爱尔兰",
"Belgium": "比利时",
"Poland": "波兰",
"Austria": "奥地利",
"Israel": "以色列",
"Ukraine": "乌克兰",
"Turkey": "土耳其",
"Thailand": "泰国",
"Vietnam": "越南",
"Malaysia": "马来西亚",
"Indonesia": "印度尼西亚",
"Philippines": "菲律宾",
"Mexico": "墨西哥",
"Argentina": "阿根廷",
"Chile": "智利",
"South Africa": "南非"
}
# 如果没有找到对应的中文名称,返回原始名称
return country_map.get(english_name, english_name)
def get_isp_name_in_chinese(english_name):
"""将常见ISP名称转换为中文"""
isp_map = {
"GOOGLE": "谷歌",
"GOOGLE-CLOUD-PLATFORM": "谷歌云平台",
"GOOGLE CLOUD": "谷歌云",
"GOOGLE LLC": "谷歌公司",
"MICROSOFT": "微软",
"MICROSOFT CORPORATION": "微软公司",
"AMAZON": "亚马逊",
"AMAZON.COM": "亚马逊",
"AMAZON WEB SERVICES": "亚马逊云服务",
"AWS": "亚马逊云服务",
"CLOUDFLARE": "Cloudflare",
"ALIBABA": "阿里巴巴",
"ALIYUN": "阿里云",
"TENCENT": "腾讯",
"TENCENT CLOUD": "腾讯云",
"BAIDU": "百度",
"ORACLE": "甲骨文",
"IBM": "IBM",
"DIGITAL OCEAN": "Digital Ocean",
"LINODE": "Linode",
"CHINA TELECOM": "中国电信",
"CHINA UNICOM": "中国联通",
"CHINA MOBILE": "中国移动",
"CHINANET": "中国电信",
"CHINA UNICOM CLOUD": "中国联通云",
"AT&T": "AT&T",
"VERIZON": "威瑞森",
"COMCAST": "康卡斯特",
"LEVEL3": "Level 3",
"COGENT": "Cogent",
"NTT": "NTT",
"SOFTLAYER": "SoftLayer",
"RACKSPACE": "Rackspace",
"HETZNER": "Hetzner"
}
# 如果没有找到对应的中文名称,返回原始名称
# 将英文名称转为大写进行匹配,增加匹配成功率
return isp_map.get(english_name.upper(), english_name)
def get_geo_info(ip_address):
"""根据 IP 地址获取地理位置信息"""
if not ip_address:
print("无法获取地理信息: IP地址为空")
return None
# 首先尝试使用可能返回中文的API
try:
print(f"尝试使用ip.taobao.com获取IP {ip_address} 的地理信息...")
url = f"http://ip.taobao.com/outGetIpInfo?ip={ip_address}&accessKey=alibaba-inc"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
try:
data = response.json()
if data.get('code') == 0:
data = data.get('data', {})
country = data.get('country', '未知')
isp = data.get('isp', '未知')
print(f"成功获取中文地理信息: {country}, {isp}")
return {
'ip': ip_address,
'country': country,
'isp': isp
}
except ValueError as e:
print(f"解析API响应JSON时出错: {e}")
else:
print(f"ip.taobao.com API请求失败,状态码: {response.status_code}")
except Exception as e:
print(f"使用ip.taobao.com获取地理信息时出错: {e}")
# 尝试使用ipapi.co API(英文,可靠)
try:
print(f"尝试使用ipapi.co获取IP {ip_address} 的地理信息...")
url = f"https://ipapi.co/{ip_address}/json/"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
try:
data = response.json()
english_country = data.get('country_name', '未知')
english_isp = data.get('org', '未知')
# 转换为中文
chinese_country = get_country_name_in_chinese(english_country)
chinese_isp = get_isp_name_in_chinese(english_isp)
print(f"成功获取并转换地理信息: {english_country} -> {chinese_country}, {english_isp} -> {chinese_isp}")
return {
'ip': ip_address,
'country': chinese_country,
'isp': chinese_isp
}
except ValueError as e:
print(f"解析API响应JSON时出错: {e}")
else:
print(f"ipapi.co API请求失败,状态码: {response.status_code}")
except Exception as e:
print(f"使用ipapi.co获取地理信息时出错: {e}")
# 如果API调用失败,尝试使用另一个备用API: ip-api.com
try:
print(f"尝试使用ip-api.com获取IP {ip_address} 的地理信息...")
# 指定lang=zh-CN获取中文结果
url = f"http://ip-api.com/json/{ip_address}?lang=zh-CN"
response = requests.get(url, timeout=10)
if response.status_code == 200:
try:
data = response.json()
if data.get('status') == 'success':
country = data.get('country', '未知')
isp = data.get('isp', '未知')
print(f"成功获取中文地理信息: {country}, {isp}")
return {
'ip': ip_address,
'country': country,
'isp': isp
}
except ValueError as e:
print(f"解析API响应JSON时出错: {e}")
else:
print(f"ip-api.com API请求失败,状态码: {response.status_code}")
except Exception as e:
print(f"使用ip-api.com获取地理信息时出错: {e}")
# 如果所有API都失败,则使用模拟数据
print("所有API请求失败,使用模拟数据")
# 根据IP地址的第一个数字粗略判断国家(仅作为备选方案)
first_octet = int(ip_address.split('.')[0])
if first_octet < 50:
country = "美国"
isp = "未知ISP"
elif first_octet < 100:
country = "欧洲"
isp = "未知ISP"
elif first_octet < 150:
country = "亚洲"
isp = "未知ISP"
else:
country = "其他地区"
isp = "未知ISP"
print(f"使用模拟数据: 国家[{country}], ISP[{isp}]")
return {
'ip': ip_address,
'country': country,
'isp': isp
}
def get_next_relay_time():
"""获取下一次接力时间(系统启动时间+12小时,转换为中国时区)"""
try:
# 获取系统启动时间
boot_time = datetime.fromtimestamp(psutil.boot_time())
# 设置为UTC时区
utc = pytz.UTC
boot_time = utc.localize(boot_time)
# 转换为中国时区
china_tz = pytz.timezone('Asia/Shanghai')
boot_time_china = boot_time.astimezone(china_tz)
# 加上12小时
next_time = boot_time_china + timedelta(hours=12)
return next_time.strftime("%Y-%m-%d %H:%M:%S")
except Exception as e:
print(f"计算接力时间时出错: {e}")
return None
def replace_info_in_file(file_path):
# 检查文件是否存在
if not os.path.exists(file_path):
print(f"错误: 文件不存在 - {file_path}")
return False
try:
# 获取当前 IP 地址和地理信息
print("正在获取IP地址...")
ip_address = get_current_ip()
if not ip_address:
print("无法获取IP地址,终止操作")
return False
print(f"成功获取IP: {ip_address}")
print("正在获取地理信息...")
geo_info = get_geo_info(ip_address)
if not geo_info:
print("无法获取地理信息,终止操作")
return False
print("正在计算下一次接力时间...")
next_relay_time = get_next_relay_time()
if not next_relay_time:
print("无法计算接力时间,终止操作")
return False
print("正在读取文件...")
# 读取文件内容
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 将文件内容输出到控制台,用于调试
print("文件原始内容片段:")
# print(content[:500] + "..." if len(content) > 500 else content)
# 接力时间模式匹配更灵活
print("尝试查找并替换接力时间...")
time_patterns = [
r'接力时间\[.*?\]',
r'接力时间\s*\[.*?\]',
r'接力时间[(\(].*?[)\)]'
]
time_replaced = False
for pattern in time_patterns:
try:
before_replace = content
content = re.sub(pattern, f'接力时间[{next_relay_time}]', content)
if before_replace != content:
time_replaced = True
print(f"成功使用模式 '{pattern}' 替换接力时间")
break
except Exception as e:
print(f"使用模式 '{pattern}' 替换时出错: {e}")
if not time_replaced:
print("使用模式匹配未能替换接力时间,尝试直接查找和替换...")
# 尝试查找包含"接力时间"的行并整行替换
lines = content.split('\n')
for i, line in enumerate(lines):
if "接力时间" in line:
# print(f"找到包含接力时间的行: {line}")
# lines[i] = f'接力时间[{next_relay_time}]'
# print(f"替换为: {lines[i]}")
# content = '\n'.join(lines)
# time_replaced = True
break
if not time_replaced:
print("警告: 无法替换接力时间")
# IP信息匹配更灵活
print("尝试查找并替换IP信息...")
# 首先尝试直接查找当前显示的IP
ip_pattern_raw = r'IP\[([\d\.]+)\]'
ip_matches = re.findall(ip_pattern_raw, content)
ip_replaced = False
if ip_matches:
current_ip = ip_matches[0]
print(f"找到当前显示的IP: {current_ip}")
# 尝试整行替换
lines = content.split('\n')
for i, line in enumerate(lines):
if current_ip in line:
print(f"找到包含当前IP的行: {line}")
# 替换IP
new_line = line.replace(f"IP[{current_ip}]", f"IP[{ip_address}]")
# 替换国家信息 - 处理可能的空格变体
country_patterns = [r'国家\[(.*?)\]', r'国家\s+\[(.*?)\]']
for pattern in country_patterns:
country_match = re.search(pattern, new_line)
if country_match:
# 保持原始空格格式
space = ' ' if '国家 [' in new_line else ''
new_line = re.sub(pattern, f'国家{space}[{geo_info["country"]}]', new_line)
break
# 替换ISP信息 - 同时处理ISP和IPS两种写法
isp_patterns = [r'ISP\[(.*?)\]', r'ISP\s+\[(.*?)\]', r'IPS\[(.*?)\]', r'IPS\s+\[(.*?)\]']
for pattern in isp_patterns:
isp_match = re.search(pattern, new_line)
if isp_match:
# 确定使用ISP还是IPS,并保持空格格式
isp_tag = 'IPS' if 'IPS' in new_line else 'ISP'
space = ' ' if f'{isp_tag} [' in new_line else ''
new_line = re.sub(pattern, f'{isp_tag}{space}[{geo_info["isp"]}]', new_line)
break
lines[i] = new_line
content = '\n'.join(lines)
ip_replaced = True
print(f"替换为新行: {new_line}")
break
if not ip_replaced:
print("警告: 无法替换IP信息")
# 尝试在文件中查找任何IP模式来帮助诊断
all_ips = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', content)
if all_ips:
print(f"文件中找到的所有IP: {all_ips[:5]}")
# 尝试找出任何可能的IP行格式
lines = content.split('\n')
for line in lines:
if re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', line):
print(f"包含IP的行: {line}")
# 直接搜索和尝试改变特定的HTML或文本内容
print("尝试直接搜索和替换特定内容...")
# 尝试查找并替换HTML中的特定元素
# 例如 <div>IP[...] 国家[...] ISP[...]</div>
html_pattern = r'<[^>]*>([^<]*IP\[[\d\.]+\][^<]*国家\s*\[[^\]]*\][^<]*(?:ISP|IPS)\s*\[[^\]]*\][^<]*)<[^>]*>'
html_matches = re.findall(html_pattern, content)
if html_matches:
print(f"找到HTML元素中的IP信息: {html_matches[0]}")
for match in html_matches:
replacement = match
# 替换IP
replacement = re.sub(r'IP\[[\d\.]+\]', f'IP[{ip_address}]', replacement)
# 替换国家
replacement = re.sub(r'国家\s*\[[^\]]*\]', f'国家[{geo_info["country"]}]', replacement)
# 替换ISP/IPS
if 'ISP' in replacement:
replacement = re.sub(r'ISP\s*\[[^\]]*\]', f'ISP[{geo_info["isp"]}]', replacement)
else:
replacement = re.sub(r'IPS\s*\[[^\]]*\]', f'IPS[{geo_info["isp"]}]', replacement)
content = content.replace(match, replacement)
print(f"替换HTML元素内容: {match} -> {replacement}")
print("正在写入更新后的内容...")
# 写回文件
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
print(f"成功更新信息:")
print(f"接力时间: {next_relay_time}")
print(f"IP信息: IP[{ip_address}] 国家[{geo_info['country']}] ISP[{geo_info['isp']}]")
# 添加直接编辑HTML的备选方式
print("尝试使用更直接的方式修改文件...")
try:
# 使用简单的字符串替换
with open(file_path, 'r', encoding='utf-8') as file:
html_content = file.read()
# 1. 查找任何IP地址并替换为新IP
old_ips = set(re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', html_content))
for old_ip in old_ips:
if old_ip != ip_address: # 避免替换已经是新IP的情况
print(f"直接替换IP: {old_ip} -> {ip_address}")
html_content = html_content.replace(old_ip, ip_address)
# 2. 直接替换国家名称
# 找出当前显示的国家名
country_matches = re.findall(r'国家\s*\[([^\]]+)\]', html_content)
if country_matches:
for country in country_matches:
if country != geo_info["country"]:
print(f"直接替换国家: {country} -> {geo_info['country']}")
html_content = html_content.replace(f"国家[{country}]", f"国家[{geo_info['country']}]")
html_content = html_content.replace(f"国家 [{country}]", f"国家 [{geo_info['country']}]")
# 3. 直接替换ISP名称
isp_matches = re.findall(r'ISP\s*\[([^\]]+)\]', html_content)
if isp_matches:
for isp in isp_matches:
if isp != geo_info["isp"]:
print(f"直接替换ISP: {isp} -> {geo_info['isp']}")
html_content = html_content.replace(f"ISP[{isp}]", f"ISP[{geo_info['isp']}]")
html_content = html_content.replace(f"ISP [{isp}]", f"ISP [{geo_info['isp']}]")
# IPS变体
ips_matches = re.findall(r'IPS\s*\[([^\]]+)\]', html_content)
if ips_matches:
for isp in ips_matches:
if isp != geo_info["isp"]:
print(f"直接替换IPS: {isp} -> {geo_info['isp']}")
html_content = html_content.replace(f"IPS[{isp}]", f"IPS[{geo_info['isp']}]")
html_content = html_content.replace(f"IPS [{isp}]", f"IPS [{geo_info['isp']}]")
# 写回文件
with open(file_path, 'w', encoding='utf-8') as file:
file.write(html_content)
print("完成直接字符串替换")
except Exception as e:
print(f"直接替换方法出错: {e}")
return True
except Exception as e:
print(f"发生错误: {str(e)}")
print("详细错误信息:")
traceback.print_exc()
return False
# 修改文件路径
file_path = '/data/SillyTavern/public/login.html'
print(f"准备修改文件: {file_path}")
success = replace_info_in_file(file_path)
if not success:
print("文件更新失败")
else:
print("文件更新成功") |