python运维开发实例(python运维管理系统)

来源:国外服务器 在您之前已被浏览:1 次
导读:目前正在解读《python运维开发实例(python运维管理系统)》的相关信息,《python运维开发实例(python运维管理系统)》是由用户自行发布的知识型内容!下面请观看由(国外主机 - www.2bp.net)用户发布《python运维开发实例(python运维管理系统)》的详细说明。
笨笨网美国主机,w ww.2 b p .n e t

在日常工作中,我们以往登录到服务器部署安装环境时,所操作的命令都是实时打印过程信息或者查看应用日志实时输出日志的时候我们也可以用tailf命令实时显示,

但是当我们把这些工作web平台化之后,怎么使用实时查看日志呢,我使用过以下两种方法实现:

1. 前端网页使用ajax定时向服务器请求获取日志信息返回。是不是有点low,但功能还是实现了。

2. 前端网页使用websocket建立连接,实时从服务器接收日志。

目前使用第二种方法通过使用flask来实现。

以下简单演示实现过程,从服务器中实时显示日志,可根据实际情况进行修改。python运维开发实例(python运维管理系统)

配图,代码参考往下内容

1.测试环境python3 使用pip安装以下库

Flask==1.1.2

gevent==20.9.0

gevent-websocket==0.10.1

2.服务端代码

import osimport timeimport loggingfrom gevent import monkeymonkey.patch_all()from gevent.pywsgi import WSGIServerfrom geventwebsocket.handler import WebSocketHandlerfrom geventwebsocket.exceptions import WebSocketErrorfrom flask import Flask, request, render_templatefrom multiprocessing import cpu_count, Processapp = Flask(__name__)def tailf(filename, websocket): """打开文件并把读取内容发给websocket""" with open(filename) as f: # 输出已经存在的文件内容 websocket.send(''.join(f.readlines())) # 移动到了文件EOF处 f.seek(0, 2) while True: line = f.readline() if line: websocket.send(line) else: time.sleep(1)@app.route('/tailf/')def tailf_log(): websocket = request.environ['wsgi.websocket'] # 演示功能这里写死,实际使用可自定义 filename = '/data/ops/20201117/test.log' if os.path.exists(filename): try: tailf(filename, websocket) except WebSocketError as e: logging.info('error {} websocket Closed!'.format(e)) websocket.close() return 'ok' else: websocket.send('<h3>查看的文件不存在!</h3>')@app.route('/')def index(): return render_template('index.html')# 日志配置logging.basicConfig( filename='logs.log', format='%(asctime)s %(levelname)s: %(message)s', level='INFO')# 实例化 这里包括监听端口ws_server = WSGIServer( ('0.0.0.0', 5000), app, log=logging, handler_class=WebSocketHandler,)ws_server.start()def serve_forever(): try: ws_server.start_accepting() ws_server._stop_event.wait() except KeyboardInterrupt: ws_server.stop()if __name__ == "__main__": # 用multiprocessing配合gevent来启动多进程 for i in range(cpu_count()): p = Process(target=serve_forever) p.start()

3.前端代码(需要引入jquery.min.js

<!doctype html><html lang="en"><head> <title>实时日志查看</title> <!-- jQuery 3 --> <script src=https://www.2bp.net/wp-content/uploads/2021/10/1757abccd08541cd945d69ffa6b903df.gif alt=运维开发之利用python实现WEB实时查看服务器日志>

PS: 我比较好奇在头条发这一类文章有没有流量的,毕竟在这里的大部分以手机端娱乐为主

笨笨网美国主机,w ww.2 b p .n e t
提醒:《python运维开发实例(python运维管理系统)》最后刷新时间 2025-03-21 11:18:13,本站为公益型个人网站,仅供个人学习和记录信息,不进行任何商业性质的盈利。如果内容、图片资源失效或内容涉及侵权,请反馈至,我们会及时处理。本站只保证内容的可读性,无法保证真实性,《python运维开发实例(python运维管理系统)》该内容的真实性请自行鉴别。