python3 使用flask_socketio实时推送服务器状态(top)和 日志信息(tail)

2020-06-19 10:39:08 浏览数 (1)

使用python3和flask_socketio ,实现服务器上的tail和top命令的实时展示,将结果实时展示在web上

tail在页面上限制了显示长度,自动滚动显示最新数据

效果如下:

tail效果

top效果

和Vue配合使用时,可能会出现如下问题

代码语言:javascript复制
GET http://127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=M-9xlys 400 (BAD REQUEST)

Access to XMLHttpRequest at 'http://127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=M-9xlys' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

提示的很明显,就是跨域了,然后理所当然的按平时的解决方式

比如使用flask_cors或者自己利用flask的钩子函数在请求前后,设置请求头等,但是依然会报错!!!

正确的解决方式是,在实例化SocketIO时,加上 cors_allowed_origins="*"

代码语言:javascript复制
socketio = SocketIO(app , cors_allowed_origins="*")

主要代码如下:

代码语言:javascript复制
# coding=utf-8
import os
import re
from threading import Lock

from flask import Flask, render_template
from flask_socketio import SocketIO
from config import LOG_FILE, SECRET_KEY

app = Flask(__name__)
app.config['SECRET_KEY'] = SECRET_KEY
socketio = SocketIO(app)
# 跨域时使用下面的
# socketio = SocketIO(app,cors_allowed_origins="*") 
代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript"
            src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
    <script type="text/javascript"
            src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>

    <script type="text/javascript" charset="utf-8">

        $(document).ready(function () {
            var child_num = 0;
            var namespace = '/shell';
            var socket = io.connect(location.protocol   '//'   document.domain   ':'   location.port   namespace);
            socket.on('tail_response', function (res) {
                if (child_num < 40) {
                    $('#terminal').append('<div>'   res.text   '</div>');
                    child_num  = 1
                } else {
                    // 先删后加
                    $('#terminal div:first').remove();
                    $('#terminal').append('<div>'   res.text   '</div>');
                }
                $(document).scrollTop($(document).height()); // 将滚动条滚到最下方
                console.log(res.text);
            });
            socket.on('connect', function (res) {
                socket.emit('open_tail', {'data': 'I'm connected!'});
            });

            //socket.on('disconnect', function (data) {
            //    socket.emit('close_tail', {'data': 'I'm disconnected!'});
            //});

            $(window).bind('beforeunload', function () {    // 离开页面前关闭tail
                    socket.emit('close_tail', {'data': 'I'm leave!'});

                }
            );


        });

        $(window).resize(function () {
            var cliWidth = document.body.clientWidth;
            var cliHeight = document.body.clientHeight;
            var divWidth = cliWidth - 2;
            var divHeight = cliHeight - 2;
            $('#terminal').css("width", divWidth   "px");
            $('#terminal').css("height", divHeight   "px");
            $(document).scrollTop($(document).height()); // 将滚动条滚到最下方
        })

    </script>
    <style>
        html, body {
            height: 100%;
            margin: 0;
        }

        .outer {
            height: 100%;
        }

        #terminal {
            height: 100%;
            background-color: black;
            color: white;
            padding-left: 10px;
        }

        #terminal div {
            background-color: black;
            color: white;
        }
    </style>

</head>

<body>


<div class="outer">

    <div id="terminal">


    </div>
</div>


</body>


</html>
代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript"
            src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
    <script type="text/javascript"
            src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>

    <script type="text/javascript" charset="utf-8">
        $(document).ready(function () {
            var namespace = "/shell";
            var socket = io.connect('http://'   document.domain   ':'   location.port   namespace);
            socket.on('connect', function (res) {
                socket.emit('handle_top', {'data': 'I'm connected!'});
            });

            socket.on('top_response', function (res) {
                var top_info = res.text;
                document.getElementById("terminal").innerHTML = top_info;
                setTimeout(function () {
                    socket.emit("handle_top", {"data": "handle_top"});
                }, 2000)
            });
        });
    </script>
    <style type="text/css">

        #terminal {
            background-color: black;
            color: white;
        }

        #terminal div {
            width: 1024px;
            text-align: justify;
        }

        table {
            width: 1024px;
            table-layout: fixed;
            text-align: right;
        }
    </style>

</head>

<body>


<div>

    <div id="terminal">

    </div>
</div>

</body>


</html>

项目完整地址:https://github.com/Mark-IT/system_log_web

0 人点赞