Python 实现网页按钮点击执行 ping 命令并显示结果
要实现在前端网页上点击按钮后执行命令并将结果输出到网页上,你可以使用 Python 的 Flask 库来创建一个简单的 Web 应用,并使用 subprocess 库来执行系统命令。\n\n首先,确保你已经安装了 Flask 库和 subprocess 库。你可以使用以下命令来安装它们:\n\n\npip install flask\n\n\n接下来,创建一个名为app.py的 Python 文件,并将以下代码复制到文件中:\n\npython\nfrom flask import Flask, render_template, request\nimport subprocess\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/ping', methods=['POST'])\ndef ping():\n result = subprocess.run(['ping', '1.1.1.1'], capture_output=True, text=True)\n output = result.stdout.splitlines()\n return render_template('index.html', output=output)\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n\n在上面的代码中,我们首先导入了 Flask 和 subprocess 库。然后,我们创建了一个 Flask 应用,并定义了两个路由。\n\nindex()函数用于渲染主页,它会呈现一个包含一个按钮的 HTML 页面(在后面的步骤中我们会创建这个页面)。\n\nping()函数是一个 POST 请求处理程序,它会执行ping 1.1.1.1命令,并将结果分割成行,然后将结果作为输出渲染到主页。\n\n最后,我们通过运行app.run(debug=True)启动 Flask 应用。\n\n接下来,创建一个名为templates的文件夹,并在其中创建一个名为index.html的 HTML 文件。将以下代码复制到index.html文件中:\n\nhtml\n<!DOCTYPE html>\n<html>\n<head>\n <title>Ping Results</title>\n</head>\n<body>\n <h1>Click the button to ping 1.1.1.1:</h1>\n <form method="POST" action="/ping">\n <input type="submit" value="Ping">\n </form>\n <h2>Ping Results:</h2>\n {% if output %}\n <ul>\n {% for line in output %}\n <li>{{ line }}</li>\n {% endfor %}\n </ul>\n {% endif %}\n</body>\n</html>\n\n\n在上面的代码中,我们创建了一个简单的 HTML 页面,其中包含一个表单和一个用于显示结果的无序列表。当点击按钮时,表单会向/ping路由发送一个 POST 请求,并将结果显示在无序列表中。\n\n最后,打开终端,进入到包含app.py文件的目录,并运行以下命令启动 Web 应用:\n\n\npython app.py\n\n\n然后,打开浏览器,访问http://localhost:5000,你应该能够看到一个网页,其中包含一个按钮。当你点击按钮时,命令ping 1.1.1.1将会在服务器上执行,并将结果显示在网页上。
原文地址: https://www.cveoy.top/t/topic/qyCs 著作权归作者所有。请勿转载和采集!