config_ip.py
6.6 KB
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
import os
from flask import Flask, render_template, request, Response
from app import app
import time
import subprocess
import re
import json
from threading import Thread
netprofilepath = r'/prog/smartshelf/app/netprofile/'
#app = Flask(__name__)
@app.route('/ipconfig')
def ipconfig():
print("begin ip flask")
return render_template('ipconfig.html')
def Config_DHCP():
netconfigfile = ''
if os.path.exists('/etc/dhcpcd.conf'):
netprofile = netprofilepath+'dhcpcd.conf.bak'
netconfigfile = '/etc/dhcpcd.conf'
else:
netprofile = netprofilepath+'/NEOTEL.nmconnection.bak'
netconfigfile = '/etc/NetworkManager/system-connections/NEOTEL.nmconnection'
with open(netprofile, 'r') as f:
file_lines = f.readlines()
f.close()
with open(netconfigfile, 'w') as f:
# for line in file_lines:
f.writelines(file_lines)
f.flush()
f.close()
def Config_StaticIP(IPAddress, Router_IP):
netconfigfile = ''
if os.path.exists('/etc/dhcpcd.conf'):
netprofile = netprofilepath+'dhcpcd.conf.bak'
netconfigfile = '/etc/dhcpcd.conf'
with open(netprofile, 'r') as f:
file_lines = f.readlines()
f.close()
with open(netconfigfile, 'w') as f:
# for line in file_lines:
f.writelines(file_lines)
# f.write("static ip_address=" + str(request.args.get('new_ip')))
# interface eth0
#IPAddress = str(request.args.get('new_ip')
#Router_IP = str(request.args.get('new_ip')
f.write("interface eth0" + "\n")
if len(IPAddress) > 0:
f.write("static ip_address=" + IPAddress + "\n")
if len(Router_IP) > 0:
f.write("static routers=" + Router_IP + "\n")
# f.write("")
f.flush()
f.close()
else:
netprofile = netprofilepath+'/NEOTEL.nmconnection.bak'
netconfigfile = '/etc/NetworkManager/system-connections/NEOTEL.nmconnection'
with open(netprofile, 'r') as f:
file_lines = f.readlines()
f.close()
with open(netconfigfile, 'w') as f:
# for line in file_lines:
for line in file_lines:
f.write(line)
if line.startswith('[ipv4]') and len(IPAddress) > 0:
if len(Router_IP) > 0:
f.write('address1='+ IPAddress + ','+Router_IP+"\n")
else:
f.write('address1='+ IPAddress + "\n")
# f.write("static ip_address=" + str(request.args.get('new_ip')))
# interface eth0
#IPAddress = str(request.args.get('new_ip')
#Router_IP = str(request.args.get('new_ip')
f.flush()
f.close()
def reboot_after_delay():
# Wait for 5 seconds before rebooting
time.sleep(5)
os.system('sudo reboot')
def Reenable_NetworkService():
#os.system('sudo systemctl stop networking')
#os.system('sudo systemctl start networking')
#os.system('sudo systemctl stop dhcpcd.service')
#print("services stop")
#os.system('sudo ip addr flush dev eth0')
#os.system('sudo systemctl start dhcpcd.service')
# Wait for 3 seconds before rebooting
reboot_thread = Thread(target=reboot_after_delay)
reboot_thread.start()
return "Apply Successfully, System will reboot in 5 seconds"
#return "Raspberry Pi will reboot in 3 seconds"
#os.system('sudo reboot')
def netmask_to_length(netmask):
# Convert the netmask to a list of integers
netmask = [int(x) for x in netmask.split(".")]
# Count the number of set bits in the netmask
length = 0
for octet in netmask:
while octet > 0:
length += octet & 1
octet >>= 1
return length
@app.route('/ip_config',methods=['POST'])
def IP_Config():
dhcp_enabled = request.form.get('dhcp')
if dhcp_enabled:
Config_DHCP()
print("DHCP ENABLED")
else:
IP_ADDR = str(request.form.get('new_ip'))
print("input:",str(request.form.get('new_ip')))
Router_ADDR = str(request.form.get('router_ip'))
NET_MASK = str(request.form.get('new_mask'))
IP_ADDR +="/"+str(netmask_to_length(NET_MASK))
print(IP_ADDR)
print(Router_ADDR)
Config_StaticIP(IP_ADDR,Router_ADDR)
print(IP_ADDR,Router_ADDR)
print("IP CHANGED")
#Reenable_NetworkService()
#Response('Apply Successfully', status=200, mimetype='text/plain')
return Reenable_NetworkService()
#return #'Apply Successfully ' #{} with DHCP enabled: {}'.format(IP_ADDR, 'True' if dhcp_enabled else 'False')
#Config_StaticIP("192.168.1.59/24", "192.168.1.1")
#Reenable_NetworkService()
@app.route('/get_networkinfo',methods=['POST'])
def Get_NetworkInfo():
"""
获取eth0接口信息,返回JSON格式字符串
"""
result = {
"interface": "eth0",
"ip_address": None,
"netmask": None,
"gateway": None
}
# 获取eth0的IP和掩码
try:
ifconfig_output = subprocess.check_output(["ifconfig", "eth0"], stderr=subprocess.STDOUT)
# 提取IP地址
print("1")
print(ifconfig_output)
ifconfig_str = ifconfig_output.decode('utf-8')
ip_match = re.search(r'inet (?:addr:)?([\d.]+)', ifconfig_str)
print("c111")
if ip_match:
result["ip_address"] = ip_match.group(1)
# 提取子网掩码
print("a")
mask_match = re.search(r'(?:Mask:|netmask )([\d.]+)', ifconfig_str)
print("b")
if mask_match:
result["netmask"] = mask_match.group(1)
except subprocess.CalledProcessError:
# eth0接口不存在,直接返回null值
print("2")
return json.dumps(result, indent=2)
except Exception:
print("3")
# 其他异常,也返回null值
return json.dumps(result, indent=2)
# 获取网关信息
try:
print("4")
route_output = subprocess.check_output(["route", "-n"])
route_str = route_output.decode('utf-8')
print(route_output)
print("5")
for line in route_str.split('\n'):
if line.startswith('0.0.0.0'):
print("8")
parts = line.split()
if len(parts) >= 8 and parts[7] == 'eth0':
print("9")
result["gateway"] = parts[1]
break
except Exception:
# 获取网关失败,保持为None
pass
return json.dumps(result, indent=2)