以下是一个使用Python Flask框架实现的简单示例,实现了在服务器上执行命令和停止进程的功能:

from flask import Flask, render_template, request
import subprocess
import os
import signal

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/start')
def start():
    # 执行命令
    subprocess.Popen(['iperf3', '-s', '-p', '11111'])
    return 'Command executed successfully.'

@app.route('/stop')
def stop():
    # 停止进程
    pid = os.popen("pgrep -f 'iperf3 -s -p 11111'").read()
    if pid:
        os.kill(int(pid), signal.SIGTERM)
        return 'Process stopped successfully.'
    else:
        return 'Process is not running.'

if __name__ == '__main__':
    app.run()

同时,需要在同级目录下创建一个名为templates的文件夹,并在该文件夹下创建一个名为index.html的文件,用于显示按钮:

<!DOCTYPE html>
<html>
<head>
    <title>Button Example</title>
</head>
<body>
    <button onclick="start()">Start</button>
    <button onclick="stop()">Stop</button>

    <script>
        function start() {
            fetch('/start')
                .then(response => response.text())
                .then(message => console.log(message))
                .catch(error => console.error(error));
        }

        function stop() {
            fetch('/stop')
                .then(response => response.text())
                .then(message => console.log(message))
                .catch(error => console.error(error));
        }
    </script>
</body>
</html>

请确保你的计算机已经安装了Flask和iperf3,并且可以在终端中直接执行iperf3命令。运行该Python程序后,访问http://localhost:5000即可看到页面上的按钮,并可以通过点击按钮来执行命令和停止进程

请实现一个网页页面有2个按钮A和B。按下按钮A的时候在服务器上执行一个命令iperf3 -s -p 11111当按下按钮B时停止这个进程。请使用python完整的实现这个程序错误了Internal Server ErrorThe server encountered an internal error and was unable to complete your request Either t

原文地址: https://www.cveoy.top/t/topic/iRGq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录