Flask Web Ping: Real-time Ping Monitoring with SocketIO
<p>import subprocess
from flask import Flask, render_template, request, jsonify, make_response
from flask_socketio import SocketIO, emit</p>
<p>app = Flask(<strong>name</strong>, template_folder='C:\Users\zh\PycharmProjects\webping\')
socketio = SocketIO(app, async_mode='eventlet') # 添加async_mode参数
process = None</p>
<p>@app.route('/')
def index():
return render_template('index.html')</p>
<p>@app.route('/execute', methods=['POST'])
def execute():
global process
if request.form['action'] == 'start':
if process is not None and process.poll() is None:
return jsonify({'output': '进程正在运行,请先停止'})
process = subprocess.Popen(['ping', '1.1.1.1', '-t'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
output = process.stdout.readline()
if output == b'' and process.poll() is not None:
break
if output:
output_text = output.decode('gbk').strip()
print(output_text)
emit('ping_output', {'output': output_text})
return jsonify({'output': '命令已执行'})
elif request.form['action'] == 'stop':
if process is not None and process.poll() is None:
process.terminate()
process.wait()
process = None
return jsonify({'output': '进程已停止'})
else:
return make_response(jsonify({'error': '无效的动作'}), 400)</p>
<p>if <strong>name</strong> == '<strong>main</strong>':
# socketio.run(app, debug=True)
socketio.run(app, debug=True,allow_unsafe_werkzeug=True)</p>
<!DOCTYPE html>
<html>
<head>
<title>Ping Monitor</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div class="container">
<h1>Ping Monitor</h1>
<div id="ping-output"></div>
<button id="start-ping" class="btn btn-primary">Start Ping</button>
<button id="stop-ping" class="btn btn-secondary">Stop Ping</button>
</div>
<script>
var socket = io.connect('http://localhost:5000');
<pre><code>$('#start-ping').click(function() {
$.ajax({
url: '/execute',
method: 'POST',
data: {action: 'start'},
success: function(response) {
console.log(response);
}
});
});
$('#stop-ping').click(function() {
$.ajax({
url: '/execute',
method: 'POST',
data: {action: 'stop'},
success: function(response) {
console.log(response);
}
});
});
socket.on('ping_output', function(data) {
$('#ping-output').append('<p>' + data.output + '</p>');
});
</code></pre>
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/qyx3 著作权归作者所有。请勿转载和采集!