运维开发:python websocket网页实时显示远程服务器日志信息

功能:用websocket技术,在运维工具的浏览器上实时显示远程服务器上的日志信息

一般我们在运维工具部署环境的时候,需要实时展现部署过程中的信息,或者在浏览器中实时显示程序日志给开发人员看。你还在用ajax每隔段时间去获取服务器日志?out了,试试用websocket方式吧

我用bottle框架,写了个websocket服务端,浏览器连接到websocket server,再用python subprocess获取远程服务器的日志信息,subprocess,就是用Popen调用shell的shell命令而已,这样可以获取到实时的日志了,然后再send到websocket server中,那连接到websocket server的浏览器,就会实时展现出来了

用二台服务器来实现这个场景,A服务器是websocket服务端,B服务器是日志端

A服务器是我浏览器本机,websocket服务端也是这台机,IP是:192.168.1.221

B服务器是要远程查看日志的服务器,我这里用:192.168.1.10

以下是A服务器的websocket servet的python代码:

 
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. # __author__ = '戴儒锋'
  4. # http://www.linuxyw.com
  5. """
  6.     执行代码前需要安装
  7.     pip install bottle
  8.     pip install websocket-client
  9.     pip install bottle-websocket
  10. """
  11. from bottle import get, run
  12. from bottle.ext.websocket import GeventWebSocketServer
  13. from bottle.ext.websocket import websocket
  14. users = set()   # 连接进来的websocket客户端集合
  15. @get('/websocket/', apply=[websocket])
  16. def chat(ws):
  17.     users.add(ws)
  18.     while True:
  19.         msg = ws.receive()  # 接客户端的消息
  20.         if msg:
  21.             for u in users:
  22.                 u.send(msg) # 发送信息给所有的客户端
  23.         else:
  24.             break
  25.     # 如果有客户端断开连接,则踢出users集合
  26.     users.remove(ws)
  27. run(host='0.0.0.0', port=8000, server=GeventWebSocketServer)

记得安装bottle、websocket-client 、bottle-websocket 模块,服务端允许所有的IP访问其8000端口

websocket服务端除了用以上的方法外,还可以用这下面的方法实现:

使用gevent-websocket实现websocket服务端程序

在电脑桌面,写一个简单的HTML5  javascripts页面,随便命名了,如web_socket.html,这个页面使用了websocket连接到websocket服务端:

 
  1.  <!DOCTYPE html>
  2. <html>
  3. <head>
  4. </head>
  5.     <style>
  6.         #msg{
  7.             400px; height:400px; overflow:auto; border:2px solid #000000;color:#ffffff;
  8.     }
  9.     </style>
  10. </head>
  11. <body>
  12.     <p>实时日志</p>
  13.     <div id="msg"></div>
  14.     <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
  15.     <script>
  16.     $(document).ready(function() {
  17.         /* !window.WebSocket、window.MozWebSocket检测浏览器对websocket的支持*/
  18.         if (!window.WebSocket) {
  19.             if (window.MozWebSocket) {
  20.                 window.WebSocket = window.MozWebSocket;
  21.             } else {
  22.                 $('#msg').prepend("<p>你的浏览器不支持websocket</p>");
  23.             }
  24.         }
  25.         /* ws = new WebSocket 创建WebSocket的实例  注意设置对以下的websocket的地址哦*/
  26.         ws = new WebSocket('ws://192.168.1.221:8000/websocket/');
  27.         /*
  28.             ws.onopen  握手完成并创建TCP/IP通道,当浏览器和WebSocketServer连接成功后,会触发onopen消息
  29.             ws.onmessage 接收到WebSocketServer发送过来的数据时,就会触发onmessage消息,参数evt中包含server传输过来的数据;
  30.         */
  31.         ws.onopen = function(evt) {
  32.             $('#msg').append('<li>websocket连接成功</li>');
  33.         }
  34.         ws.onmessage = function(evt) {
  35.             $('#msg').prepend('<li>' + evt.data + '</li>');
  36.         }
  37.     });
  38. </script>
  39. </body>
  40. </html>

注意:WebSocket('ws://192.168.1.221:8000/websocket/');  这里的192.168.1.221一定要改成你的websocket服务端IP,切记!!!

到这里,就搞定浏览器连接到websocket服务端的场景了,现在要A服务器里写一段代码,去采集B服务器的实时信息了,其实采集原理很简单,就是使用shell中的tailf命令,实时显示最新的信息而已,我们在这段脚本中,使用subprocess.Popen()来远程查看日志信息:

python代码如下:

 
  1. #!/usr/bin/python
  2. # encoding=utf-8
  3. import subprocess
  4. import time
  5. from websocket import create_connection
  6. # 配置远程服务器的IP,帐号,密码,端口等,因我做了双机密钥信任,所以不需要密码
  7. r_user = "root"
  8. r_ip = "192.168.1.10"
  9. r_port = 22
  10. r_log = "/tmp/web_socket.log"   # 远程服务器要被采集的日志路径
  11. # websocket服务端地址
  12. ws_server = "ws://192.168.1.221:8000/websocket/"
  13. # 执行的shell命令(使用ssh远程执行)
  14. cmd = "/usr/bin/ssh -p {port} {user}@{ip} /usr/bin/tailf {log_path}".format(user=r_user,ip=r_ip,port=r_port,log_path=r_log)
  15. def tailfLog():
  16.     """获取远程服务器实时日志,并发送到websocket服务端"""
  17.     popen = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
  18.     print('连接成功')
  19.     ws = create_connection(ws_server)   # 创建websocket连接
  20.     while True:
  21.         line = popen.stdout.readline().strip()  #获取内容
  22.         if line:
  23.             ws.send(line)   #把内容发送到websocket服务端
  24.         print time.time()
  25. if __name__ == '__main__':
  26.     tailfLog()

文章最后再解析subprocess.Popen的原理和功能

执行websocket服务端脚本和上面这个websocket客户端采集脚本,再打开用浏览器打开上面的html5页面后,环境就基本部署好了,双websocket客户端连接到websocket服务端中

上面脚本指定的r_log = "/tmp/web_socket.log"日志路径,我们需要生成这个日志文件,并不停地往里面写入日志,这样才能在浏览器中实时显示效果(真实场景中,可以指定服务器某日志,如apache,nginx日志等)

我们在B服务器写一段python代码,然后每隔一秒就往r_log = "/tmp/web_socket.log"日志中写入内容:

python代码如下:

 
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import time
  4. import random
  5. log_path = '/tmp/web_socket.log'
  6. while 1:
  7.     with open(log_path,'a') as f:
  8.         f.write('[%s]   %s  ' % (time.ctime(),random.random()))
  9.     time.sleep(1)

脚本写入的内容大概是:

[Tue Jul 26 18:30:41 2016] 0.527242649654 
[Tue Jul 26 18:30:42 2016] 0.21080845298 
[Tue Jul 26 18:30:43 2016] 0.23128691356 
[Tue Jul 26 18:30:44 2016] 0.689547600796

执行这段脚本,然后看浏览器效果:

websocket实时日志效果

这只是我临时写的,如果要在真实的运维工具中使用,还需要根据具体情况,修改不少内容,但原理就是这样,大家可根据自己的情况修改,完善使用。

刚才提到subprocess.Popen的原理和功能,请看以下资料:

http://www.cnblogs.com/fengbeihong/articles/3374132.html

bottle websocket参考资料:

http://rfyiamcool.blog.51cto.com/1030776/1269232/

原文地址:https://www.cnblogs.com/php-rearch/p/6661241.html