File size: 2,691 Bytes
70b6d8f |
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 |
import os
import re
import socket
def get_local_ip():
"""获取本机内网IP地址"""
try:
# 创建一个 UDP 套接字
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 连接到一个外部地址(不会实际发送数据)
s.connect(("8.8.8.8", 80))
# 获取本地套接字的地址
local_ip = s.getsockname()[0]
s.close()
return local_ip
except Exception as e:
print(f"获取本机IP失败: {e}")
return None
def replace_ip_in_file(file_path, old_ip_pattern, new_ip):
"""替换文件中的IP地址"""
try:
# 读取文件内容
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 使用正则表达式替换IP地址
# 匹配格式:内网IP[10.108.78.191]
pattern = re.compile(r'内网IP\[' + re.escape(old_ip_pattern) + r'\]')
new_content = pattern.sub(f'内网IP[{new_ip}]', content)
# 如果内容有变化,则写回文件
if content != new_content:
with open(file_path, 'w', encoding='utf-8') as file:
file.write(new_content)
print(f"成功替换IP: {old_ip_pattern} -> {new_ip}")
return True
else:
print("未找到匹配的IP地址,文件未修改")
return False
except FileNotFoundError:
print(f"文件不存在: {file_path}")
return False
except Exception as e:
print(f"处理文件时出错: {e}")
return False
def main():
# 文件路径
file_path = "/data/SillyTavern/public/scripts/templates/welcomePanel.html"
# 获取本机内网IP
local_ip = get_local_ip()
if not local_ip:
print("无法获取本机IP地址")
return
print(f"本机内网IP: {local_ip}")
# 读取文件并查找需要替换的IP
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 查找类似 "内网IP[xxx.xxx.xxx.xxx]" 的模式
pattern = r'内网IP\[(\d+\.\d+\.\d+\.\d+)\]'
matches = re.findall(pattern, content)
if matches:
for old_ip in matches:
if old_ip != local_ip:
replace_ip_in_file(file_path, old_ip, local_ip)
else:
print(f"IP地址已经是本机IP ({local_ip}),无需替换")
else:
print("未找到需要替换的IP地址模式")
except Exception as e:
print(f"处理文件时出错: {e}")
if __name__ == "__main__":
main() |