Python Flask案例:制作一个Linux命令执行网站
来自CloudWiki
python
from flask import Flask from flask import Flask, render_template, flash, redirect, url_for, session, request, logging app = Flask(__name__)#创建一个该类的实例,第一个参数是应用模块或者包的名称 def search(kw): #此处应该插入mysql查询命令 linux_dict ={ 'cd':"切换目录", 'ls':"查看目录", 'mkdir':"创建目录", 'echo':"输出信息", 'cat':"查看文件", 'ipconfig':"查看网络情况" } detail ="" for k in linux_dict: if kw == k: detail =linux_dict.get(k) if detail=="": detail="对不起,该条命令暂时未收录" return kw,detail import subprocess @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'GET': # 如果展示表单 return render_template('index.html') elif request.method == 'POST':#如果是提交表单 keywords = request.form['keywords'] name,detail =search(keywords) if name =="ipconfig": result =subprocess.run(name,shell=True, \ stdout=subprocess.PIPE,encoding="gb2312") detail = result.stdout return render_template('index.html',name=name,detail=detail) if __name__ == '__main__':#程序入口 #app.run()#让应用运行在本地服务器上。 app.secret_key='secret123' app.run(host='0.0.0.0',port="5005",debug="true") #允许任意网址访问本站
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div class="content"> <h1 class="title-center">Linux命令查询</h1> <form action="" method="POST" > <div class="form-group"> <label>请输入linux 关键词(例如,"ls")</label> <input type="text" name="keywords" class="form-control" ><button type="submit" class="btn btn-primary">查询</button> </div> <div style="color:blue;font-size:30px;line-height:150%;margin-left:40px"><h2>{{name}}</h2></div> <div style="color:blue;font-size:30px;line-height:150%;margin-left:40px">{{detail}}</div> </form> </div> <script> </script> </body> </html>