Qilan2 commited on
Commit
70b6d8f
·
verified ·
1 Parent(s): d7490bf

Create ipn.py

Browse files
Files changed (1) hide show
  1. ipn.py +83 -0
ipn.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import socket
4
+
5
+ def get_local_ip():
6
+ """获取本机内网IP地址"""
7
+ try:
8
+ # 创建一个 UDP 套接字
9
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
10
+ # 连接到一个外部地址(不会实际发送数据)
11
+ s.connect(("8.8.8.8", 80))
12
+ # 获取本地套接字的地址
13
+ local_ip = s.getsockname()[0]
14
+ s.close()
15
+ return local_ip
16
+ except Exception as e:
17
+ print(f"获取本机IP失败: {e}")
18
+ return None
19
+
20
+ def replace_ip_in_file(file_path, old_ip_pattern, new_ip):
21
+ """替换文件中的IP地址"""
22
+ try:
23
+ # 读取文件内容
24
+ with open(file_path, 'r', encoding='utf-8') as file:
25
+ content = file.read()
26
+
27
+ # 使用正则表达式替换IP地址
28
+ # 匹配格式:内网IP[10.108.78.191]
29
+ pattern = re.compile(r'内网IP\[' + re.escape(old_ip_pattern) + r'\]')
30
+ new_content = pattern.sub(f'内网IP[{new_ip}]', content)
31
+
32
+ # 如果内容有变化,则写回文件
33
+ if content != new_content:
34
+ with open(file_path, 'w', encoding='utf-8') as file:
35
+ file.write(new_content)
36
+ print(f"成功替换IP: {old_ip_pattern} -> {new_ip}")
37
+ return True
38
+ else:
39
+ print("未找到匹配的IP地址,文件未修改")
40
+ return False
41
+
42
+ except FileNotFoundError:
43
+ print(f"文件不存在: {file_path}")
44
+ return False
45
+ except Exception as e:
46
+ print(f"处理文件时出错: {e}")
47
+ return False
48
+
49
+ def main():
50
+ # 文件路径
51
+ file_path = "/data/SillyTavern/public/scripts/templates/welcomePanel.html"
52
+
53
+ # 获取本机内网IP
54
+ local_ip = get_local_ip()
55
+ if not local_ip:
56
+ print("无法获取本机IP地址")
57
+ return
58
+
59
+ print(f"本机内网IP: {local_ip}")
60
+
61
+ # 读取文件并查找需要替换的IP
62
+ try:
63
+ with open(file_path, 'r', encoding='utf-8') as file:
64
+ content = file.read()
65
+
66
+ # 查找类似 "内网IP[xxx.xxx.xxx.xxx]" 的模式
67
+ pattern = r'内网IP\[(\d+\.\d+\.\d+\.\d+)\]'
68
+ matches = re.findall(pattern, content)
69
+
70
+ if matches:
71
+ for old_ip in matches:
72
+ if old_ip != local_ip:
73
+ replace_ip_in_file(file_path, old_ip, local_ip)
74
+ else:
75
+ print(f"IP地址已经是本机IP ({local_ip}),无需替换")
76
+ else:
77
+ print("未找到需要替换的IP地址模式")
78
+
79
+ except Exception as e:
80
+ print(f"处理文件时出错: {e}")
81
+
82
+ if __name__ == "__main__":
83
+ main()