|
|
import os |
|
|
import re |
|
|
import socket |
|
|
|
|
|
def get_local_ip(): |
|
|
"""获取本机内网IP地址""" |
|
|
try: |
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
|
|
|
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" |
|
|
|
|
|
|
|
|
local_ip = get_local_ip() |
|
|
if not local_ip: |
|
|
print("无法获取本机IP地址") |
|
|
return |
|
|
|
|
|
print(f"本机内网IP: {local_ip}") |
|
|
|
|
|
|
|
|
try: |
|
|
with open(file_path, 'r', encoding='utf-8') as file: |
|
|
content = file.read() |
|
|
|
|
|
|
|
|
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() |