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


     config.yaml配置文件内容

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

    1. auth:
    2. type: userpass
    3. userpass:
    4. csdn: csdn
    5. listen: :443
    6. masquerade:
    7. proxy:
    8. rewriteHost: true
    9. url: https://www.bing.com/
    10. type: proxy
    11. tls:
    12. cert: /root/hyst*****马赛克******eria2/csdn.crt
    13. key: /root/hyst*****马赛克******eria2/csdn.key

    直接上代码

    1. from flask import Flask, request, jsonify
    2. import yaml
    3. import subprocess
    4. import os
    5. app = Flask(__name__)
    6. CONFIG_FILE = '/root/hyst*******马赛克******eria2/config.yaml'
    7. API_KEY = '123456789'
    8. def read_config():
    9. with open(CONFIG_FILE, 'r') as file:
    10. return yaml.safe_load(file)
    11. def write_config(config):
    12. with open(CONFIG_FILE, 'w') as file:
    13. yaml.safe_dump(config, file)
    14. def restart_service(service_name):
    15. try:
    16. subprocess.run(['sudo', 'systemctl', 'restart', service_name], check=True)
    17. return True
    18. except subprocess.CalledProcessError:
    19. return False
    20. def check_service_status(service_name):
    21. try:
    22. result = subprocess.run(['sudo', 'systemctl', 'is-active', service_name], check=True, stdout=subprocess.PIPE)
    23. if result.stdout.decode('utf-8').strip() == 'active':
    24. return True
    25. else:
    26. return False
    27. except subprocess.CalledProcessError:
    28. return False
    29. @app.route('/api', methods=['POST'])
    30. def manage_user():
    31. # 验证API Key
    32. api_key = request.headers.get('Authorization')
    33. if api_key != API_KEY:
    34. return jsonify({'error': 'Unauthorized'}), 401
    35. # 解析请求数据
    36. data = request.json
    37. if not data or 'username' not in data or 'action' not in data:
    38. return jsonify({'error': 'Bad Request'}), 400
    39. username = data['username']
    40. action = data['action'].lower()
    41. # 读取配置文件
    42. config = read_config()
    43. userpass = config.get('auth', {}).get('userpass', {})
    44. service_name = 'hyst*******马赛克******eria2' # 服务名称
    45. need_restart = False
    46. if action == 'add':
    47. if 'password' not in data:
    48. return jsonify({'error': 'Missing password for add action'}), 400
    49. password = data['password']
    50. userpass[username] = password
    51. need_restart = True
    52. elif action == 'delete':
    53. if username in userpass:
    54. userpass.pop(username, None)
    55. need_restart = True
    56. else:
    57. return jsonify({'error': 'User not found'}), 404
    58. elif action == 'query':
    59. password = userpass.get(username)
    60. if password is not None:
    61. return jsonify({username: password})
    62. else:
    63. return jsonify({'error': 'User not found'}), 404
    64. else:
    65. return jsonify({'error': 'Invalid action'}), 400
    66. # 对于非查询动作,更新配置文件并重启服务
    67. if need_restart:
    68. config['auth']['userpass'] = userpass
    69. write_config(config)
    70. if restart_service(service_name):
    71. if check_service_status(service_name):
    72. return jsonify({'success': True, 'message': 'Service restarted and running'})
    73. else:
    74. return jsonify({'error': 'Service restarted but not running'}), 500
    75. else:
    76. return jsonify({'error': 'Failed to restart service'}), 500
    77. return jsonify({'success': True})
    78. if __name__ == '__main__':
    79. app.run(host='0.0.0.0', port=5000)

    add功能,带验证

    del功能

     

    查询功能 

    代码完成:chatgpt4 

  • 相关阅读:
    SpringBoot(一、快速入门)
    安卓备份基带分区 备份字库 步骤解析 以免误檫除分区或者“格机” 后悔莫及
    Linux下Docker安装几种NoSQL和MQ
    力扣:22-括号生成
    xsser工具使用教程
    VBA一个sheet多行按照固定行数分割到多个excel中
    关于VSCode安装 python 语法检测器插件 pylint 配置(Mac)
    iOS 关于UIDatePicker常见使用方法
    Java SPI机制
    多维度比对三种软件开发方式后,无代码开发到底赢在哪?
  • 原文地址:https://blog.csdn.net/jxyk2007/article/details/136184241