设置方法
https://www.raspberrypi.org/documentation/configuration/wireless/access-point-routed.md
from flask import Flask
from flask import request
import os
app = Flask(__name__)
#通过修改dhcpcd.conf启用热点
@app.route('/setap', methods=['post', 'get'])
def setap():
conf_file = '/etc/dhcpcd.conf'
try:
# Sanitize/validate params above
with open(conf_file, 'r') as file:
data = file.readlines()
# Find if config exists
ethFound = next((x for x in data if 'interface wlan0' in x), None)
if ethFound:
ethIndex = data.index(ethFound)
if data[ethIndex].startswith('#'):
data[ethIndex]=data[ethIndex].replace('#', '')
data[ethIndex+1] = 'static ip_address=192.168.4.1/24\n'
data[ethIndex+2] = 'nohook wpa_supplicant\n'
#data[ethIndex+3] = f'static domain_name_servers={dns}'
with open(conf_file, 'w') as file:
file.writelines( data )
os.system("sudo systemctl enable hostapd")
os.system("sudo reboot")
return "1"
except Exception as ex:
print(ex)
return "-1"
#通过修改dhcpcd.conf设置 eth0的固定ip
@app.route('/seteth0staticip(', methods=['post', 'get'])
def change_eth0_static_ip():
ip_address, routers, dns=request.args.get("ip_address"),request.args.get("routers"),request.args.get("dns")
conf_file = '/etc/dhcpcd.conf'
try:
# Sanitize/validate params above
with open(conf_file, 'r') as file:
data = file.readlines()
# Find if config exists
ethFound = next((x for x in data if 'interface eth0' in x), None)
if ethFound:
ethIndex = data.index(ethFound)
if data[ethIndex].startswith('#'):
data[ethIndex]=data[ethIndex].replace('#', '')
# If config is found, use index to edit the lines you need ( the next 3)
if ethIndex:
data[ethIndex+1] = f'static ip_address={ip_address}/24'
data[ethIndex+2] = f'static routers={routers}'
data[ethIndex+3] = f'static domain_name_servers={dns}'
with open(conf_file, 'w') as file:
file.writelines( data )
except Exception as ex:
logging.exception("IP changing error: %s", ex)
finally:
pass
#禁用热点启用wifi
@app.route('/setwifi', methods=['post', 'get'])
def setwifi():
conf_file = '/etc/dhcpcd.conf'
try:
# Sanitize/validate params above
with open(conf_file, 'r') as file:
data = file.readlines()
# Find if config exists
ethFound = next((x for x in data if 'interface wlan0' in x), None)
if ethFound:
ethIndex = data.index(ethFound)
if not data[ethIndex].startswith('#'):
data[ethIndex]=data[ethIndex].replace('#', '')
data[ethIndex]="#"+data[ethIndex]
data[ethIndex+1]=data[ethIndex+1].replace('#', '')
data[ethIndex+1] = "#"+data[ethIndex+1]
data[ethIndex+2]=data[ethIndex+2].replace('#', '')
data[ethIndex+2] = "#"+data[ethIndex+2]
with open(conf_file, 'w') as file:
file.writelines( data )
os.system("sudo systemctl disable hostapd")
os.system("sudo reboot")
return "1"
except Exception as ex:
print(ex)
return "-1"
if __name__ =='__main__':
try:
app.run(host='0.0.0.0',port=5004)
except KeyboardInterrupt as e:
pass
except Exception as e:
pass