python3 flask 实现对config.yaml文件的内容的增删改查,并重启服务

config.yaml配置文件内容

功能就是userpass下的用户名和密码做增删改查,并重启hy2服务

auth:
  type: userpass
  userpass:
    csdn: csdn

listen: :443
masquerade:
  proxy:
    rewriteHost: true
    url: https://www.bing.com/
  type: proxy
tls:
  cert: /root/hyst*****马赛克******eria2/csdn.crt
  key: /root/hyst*****马赛克******eria2/csdn.key

直接上代码

from flask import Flask, request, jsonify
import yaml
import subprocess
import os

app = Flask(__name__)
CONFIG_FILE = '/root/hyst*******马赛克******eria2/config.yaml'
API_KEY = '123456789'

def read_config():
    with open(CONFIG_FILE, 'r') as file:
        return yaml.safe_load(file)

def write_config(config):
    with open(CONFIG_FILE, 'w') as file:
        yaml.safe_dump(config, file)

def restart_service(service_name):
    try:
        subprocess.run(['sudo', 'systemctl', 'restart', service_name], check=True)
        return True
    except subprocess.CalledProcessError:
        return False

def check_service_status(service_name):
    try:
        result = subprocess.run(['sudo', 'systemctl', 'is-active', service_name], check=True, stdout=subprocess.PIPE)
        if result.stdout.decode('utf-8').strip() == 'active':
            return True
        else:
            return False
    except subprocess.CalledProcessError:
        return False

@app.route('/api', methods=['POST'])
def manage_user():
    # 验证API Key
    api_key = request.headers.get('Authorization')
    if api_key != API_KEY:
        return jsonify({'error': 'Unauthorized'}), 401

    # 解析请求数据
    data = request.json
    if not data or 'username' not in data or 'action' not in data:
        return jsonify({'error': 'Bad Request'}), 400
    
    username = data['username']
    action = data['action'].lower()

    # 读取配置文件
    config = read_config()
    userpass = config.get('auth', {}).get('userpass', {})

    service_name = 'hyst*******马赛克******eria2' # 服务名称
    need_restart = False

    if action == 'add':
        if 'password' not in data:
            return jsonify({'error': 'Missing password for add action'}), 400
        password = data['password']
        userpass[username] = password
        need_restart = True
    elif action == 'delete':
        if username in userpass:
            userpass.pop(username, None)
            need_restart = True
        else:
            return jsonify({'error': 'User not found'}), 404
    elif action == 'query':
        password = userpass.get(username)
        if password is not None:
            return jsonify({username: password})
        else:
            return jsonify({'error': 'User not found'}), 404
    else:
        return jsonify({'error': 'Invalid action'}), 400

    # 对于非查询动作,更新配置文件并重启服务
    if need_restart:
        config['auth']['userpass'] = userpass
        write_config(config)
        if restart_service(service_name):
            if check_service_status(service_name):
                return jsonify({'success': True, 'message': 'Service restarted and running'})
            else:
                return jsonify({'error': 'Service restarted but not running'}), 500
        else:
            return jsonify({'error': 'Failed to restart service'}), 500

    return jsonify({'success': True})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

add功能,带验证

del功能

查询功能

代码完成:chatgpt4

相关推荐
源码12152 分钟前
ASP.NET MVC宠物商城系统
后端·asp.net·宠物
FHYAAAX5 分钟前
【机器学习】任务十:从函数分析到机器学习应用与BP神经网络
开发语言·python
PyAIGCMaster14 分钟前
python环境中,敏感数据的存储与读取问题解决方案
服务器·前端·python
何曾参静谧43 分钟前
「Py」模块篇 之 PyAutoGUI库自动化图形用户界面库
运维·python·自动化
pumpkin845141 小时前
客户端发送http请求进行流量控制
python·网络协议·http
smj2302_796826521 小时前
用枚举算法解决LeetCode第3348题最小可整除数位乘积II
python·算法·leetcode
Ai 编码助手1 小时前
Go语言 实现将中文转化为拼音
开发语言·后端·golang
hummhumm1 小时前
第 12 章 - Go语言 方法
java·开发语言·javascript·后端·python·sql·golang
hummhumm1 小时前
第 8 章 - Go语言 数组与切片
java·开发语言·javascript·python·sql·golang·database
杜杜的man1 小时前
【go从零单排】Directories、Temporary Files and Directories目录和临时目录、临时文件
开发语言·后端·golang