LiuYuan's Blog
This is LiuYuan's Blog
Toggle navigation
LiuYuan's Blog
Home
Docker相关
MySQL相关
Ansible相关
维护脚本相关
Windows系统脚本
Python相关
Nginx相关
About Me
Archives
Tags
前端调取脚本示例
2024-06-20 10:46:05
59
0
0
admin
python主程序和两个静态页面,实现ansible批量执行更新脚本 app.py import os import logging from flask import Flask, request, render_template, redirect, url_for, session, render_template_string import hashlib import subprocess import datetime from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SECRET_KEY'] = '自定义32位字符串' app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:passwd@10.0.0.1/python_db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class User(db.Model): __tablename__ = 'users' # 指定表名为 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(100), unique=True, nullable=False) password = db.Column(db.String(255), nullable=False) class LoginLog(db.Model): __tablename__ = 'login_logs' # 指定表名为 'login_logs' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(100), nullable=False) login_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now) def login_required(func): def decorated(*args, **kwargs): if 'username' not in session: return redirect(url_for('login_page')) return func(*args, **kwargs) decorated.__name__ = func.__name__ return decorated @app.route('/') @app.route('/test/') def login_page(): return render_template('login.html') @app.route('/login', methods=['POST']) @app.route('/test/login', methods=['POST']) def login(): username = request.form['username'] password = request.form['password'] password_md5 = hashlib.md5(password.encode('utf-8')).hexdigest() user = User.query.filter_by(username=username, password=password_md5).first() if user: login_time = datetime.datetime.now() login_log = LoginLog(username=username, login_time=login_time) db.session.add(login_log) db.session.commit() session['username'] = username return redirect(url_for('interface_page')) else: return '登录失败:用户名或密码错误' @app.route('/interface') @app.route('/test/interface') @login_required def interface_page(): return render_template('interface.html') @app.route('/execute_playbook', methods=['GET']) @app.route('/test/execute_playbook', methods=['GET']) @login_required def execute_playbook(): playbook_path = request.args.get('playbook_path') tag = request.args.get('tag') command = f"ansible-playbook {playbook_path} --extra-vars 'tag={tag}'" process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = process.communicate() return render_template_string(''' <!DOCTYPE html> <html lang="zh-Hans"> <head> <meta charset="UTF-8"> <title>执行结果</title> </head> <body> <h1>执行结果</h1> <pre>{{ output }}</pre> </body> </html> ''', output=output.decode('utf-8'), error=error.decode('utf-8')) @app.route('/view_running_containers') @app.route('/test/view_running_containers') @login_required def view_running_containers(): command = "ansible all -m shell -a \"docker ps -a --format '{{ '{{'}}.Image{{ '}}' }}|{{ '{{'}}.Names{{ '}}' }}|{{ '{{'}}.Status{{ '}}' }}|{{ '{{'}}.CreatedAt{{ '}}' }}'\"" process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = process.communicate() return render_template_string(''' <!DOCTYPE html> <html lang="zh-Hans"> <head> <meta charset="UTF-8"> <title>正在运行的容器</title> </head> <body> <h1>正在运行的容器</h1> <pre>{{ output }}</pre> </body> </html> ''', output=output.decode('utf-8'), error=error.decode('utf-8')) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True) templates/login.html <!DOCTYPE html> <html lang="zh-Hans"> <head> <meta charset="UTF-8"> <title>项目更新</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <!-- 引入 Bootstrap CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"> </head> <body> <div class="container"> <div class="row justify-content-center mt-5"> <div class="col-md-6"> <h1 class="text-center mb-4">登录</h1> <form id="loginForm" action="/test/login" method="post"> <div class="mb-3"> <label for="username" class="form-label">用户名:</label> <input type="text" class="form-control" id="username" name="username" required> </div> <div class="mb-3"> <label for="password" class="form-label">密码:</label> <input type="password" class="form-control" id="password" name="password" required> </div> <div class="d-grid"> <input type="submit" class="btn btn-primary" value="登录"> </div> </form> </div> </div> </div> <!-- 引入 Bootstrap JS 文件(如果需要) --> <!-- 注意:如果你已经在页面中引入了 Bootstrap 的 JS 文件,可以将下面一行代码注释掉 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> </body> </html> templates/interface.html <!DOCTYPE html> <html lang="zh-Hans"> <head> <meta charset="UTF-8"> <title>执行 Ansible</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <style> body { font-family: Arial, sans-serif; max-width: 400px; margin: 0 auto; padding: 20px; background-color: #f2f2f2; } h1 { text-align: center; margin-bottom: 20px; color: #333; } form { display: flex; flex-direction: column; align-items: center; } label { margin-bottom: 10px; color: #666; } input[type="text"] { width: 200px; padding: 5px; border: 1px solid #ccc; border-radius: 5px; font-size: 14px; } input[type="submit"] { margin-top: 10px; padding: 8px 16px; background-color: #007bff; color: #fff; border: none; border-radius: 5px; cursor: pointer; font-size: 14px; } input[type="submit"]:hover { background-color: #0056b3; } </style> </head> <body> <h1>执行 Ansible</h1> <form id="ansibleForm"> <label for="tag">版本号:</label> <input type="text" id="tag" name="tag" required> <input type="submit" value="执行更新Web" onclick="executePlaybook('/data/test/update_web.yaml')"> <input type="submit" value="执行更新Server" onclick="executePlaybook('/data/test/update_server.yaml')"> <input type="submit" value="查看正在运行的容器" onclick="viewRunningContainers()"> </form> <script> function executePlaybook(playbookPath) { var tag = document.getElementById('tag').value; // 构造 URL,包含 playbookPath 和 tag 参数 var url = `/test/execute_playbook?playbook_path=${encodeURIComponent(playbookPath)}&tag=${encodeURIComponent(tag)}`; // 打开新页面,并跳转到上面构造的 URL window.open(url, '_blank'); } function viewRunningContainers() { var url = `/test/view_running_containers`; // Open a new browser window and redirect to the specified URL window.open(url, '_blank'); } </script> </body> </html> python_db.sql -- MySQL dump 10.13 Distrib 8.0.20, for Linux (x86_64) -- -- Host: localhost Database: python_db -- ------------------------------------------------------ -- Server version 8.0.20 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!50503 SET NAMES utf8mb4 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `login_logs` -- DROP TABLE IF EXISTS `login_logs`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `login_logs` ( `id` int NOT NULL AUTO_INCREMENT, `username` varchar(255) COLLATE utf8mb4_general_ci NOT NULL, `login_time` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `login_logs` -- LOCK TABLES `login_logs` WRITE; /*!40000 ALTER TABLE `login_logs` DISABLE KEYS */; INSERT INTO `login_logs` VALUES (1,'test','2023-08-02 11:55:12'),(2,'test','2023-08-02 12:23:56'),(3,'test','2023-08-02 12:25:50'),(4,'test','2023-08-02 12:47:01'),(5,'test','2023-08-02 12:53:09'),(6,'test','2023-08-02 12:54:14'),(7,'test','2023-08-02 12:54:23'),(8,'test','2023-08-02 12:54:30'),(9,'test','2023-08-02 12:56:51'); /*!40000 ALTER TABLE `login_logs` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `users` -- DROP TABLE IF EXISTS `users`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `users` ( `id` int NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(32) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `users` -- LOCK TABLES `users` WRITE; /*!40000 ALTER TABLE `users` DISABLE KEYS */; INSERT INTO `users` VALUES (1,'test','ee9beabc32b53cd25f700f78582afa96'),(2,'liuyuan','ee9beabc32b53cd25f700f78582afa96'); /*!40000 ALTER TABLE `users` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2023-08-02 13:03:23
Pre:
apache node mysql安装
Next:
微博评论爬取
0
likes
59
Weibo
Wechat
Tencent Weibo
QQ Zone
RenRen
Footer
Table of content