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

相关推荐
nbsaas-boot1 小时前
Java 正则表达式白皮书:语法详解、工程实践与常用表达式库
开发语言·python·mysql
仗剑_走天涯1 小时前
基于pytorch.nn模块实现线性模型
人工智能·pytorch·python·深度学习
chao_7891 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
Nejosi_念旧1 小时前
解读 Go 中的 constraints包
后端·golang·go
风无雨1 小时前
GO 启动 简单服务
开发语言·后端·golang
小明的小名叫小明1 小时前
Go从入门到精通(19)-协程(goroutine)与通道(channel)
后端·golang
斯普信专业组2 小时前
Go语言包管理完全指南:从基础到最佳实践
开发语言·后端·golang
一只叫煤球的猫3 小时前
【🤣离谱整活】我写了一篇程序员掉进 Java 异世界的短篇小说
java·后端·程序员
你的人类朋友4 小时前
🫏光速入门cURL
前端·后端·程序员
chao_7896 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找