DevOps Development: Python websocket Web page displays remote server log information in real time

Source: Internet
Author: User
Tags python subprocess

Function: Use websocket technology to display the log information on remote server in real time on the browser of operation and Maintenance tool

In general, we need to present the information in the deployment process in real time when the OPS tool is deployed, or show the program log to the developer in real time in the browser. Are you still using AJAX to get the server log every once in a while? Out, try the websocket way.

I used the bottle framework, wrote a websocket server, the browser connected to WebSocket server, and then Python subprocess to get the log information of remote servers, subprocess, is to invoke the shell command with Popen, so that you can get to the real-time log, and then send to the websocket server , the browser connected to WebSocket server, will be displayed in real time

With two servers to achieve this scenario, a server is the WebSocket server, B is the log end

A server is my browser this machine, WebSocket service is also this machine, IP is: 192.168.1.221

b Server is the server to view logs remotely, I use: 192.168.1.10

The following is the Python code for the WebSocket Servet of a server:

  1. #!/usr/bin/env python
  2. #coding =utf-8
  3. # __author__ = ' Dairu '
  4. # http://www.linuxyw.com
  5. """
  6. Need to install before executing code
  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 () # Connect incoming WebSocket client collection
  15. @get ('/websocket/', Apply=[websocket])
  16. def chat (ws):
  17. Users.add (WS)
  18. while True:
  19. msg = Ws.receive () # message to client
  20. If msg:
  21. For u in users:
  22. U.send (msg) # Send a message to all clients
  23. Else:
  24. Break
  25. # If a client disconnects, kick out the Users collection
  26. Users. Remove (WS)
  27. Run (host= ' 0.0.0.0 ', port=8000, Server=geventwebsocketserver)

Remember to install the bottle,websocket-client,bottle-websocket module, the server allows all IP access to its 8000 port

WebSocket Server In addition to the above methods, you can also use the following method to achieve:

Using Gevent-websocket to implement WebSocket service-side programs

On the computer desktop, write a simple HTML5 javascripts page, casually named, such as web_socket.html, this page uses the WebSocket connection to the WebSocket server:

  1. <! DOCTYPE html>
  2. <style>
  3. #msg {
  4. width:400px; height:400px; Overflow:auto; border:2px solid #000000; color: #ffffff;
  5. }
  6. </style>
  7. <body>
  8. <p> Real-time log </p>
  9. <div id="msg" ></div>
  10. <script src="Http://libs.baidu.com/jquery/1.9.1/jquery.min.js" ></script>
  11. <script>
  12. $ (document). Ready (function () {
  13. / *!window. WebSocket, window. Mozwebsocket Detection of browser support for WebSocket * /
  14. if (!window. WebSocket) {
  15. if (window. Mozwebsocket) {
  16. Window. WebSocket = window. Mozwebsocket;
  17. } Else {
  18. $ (' #msg '). Prepend ("<p> your browser does not support websocket</p>");
  19. }
  20. }
  21. / * ws = new WebSocket Create an instance of WebSocket note set the address of the WebSocket to the following OH * /
  22. WS = new WebSocket (' WS://192.168.1.221:8000/websocket/');
  23. /*
  24. Ws.onopen handshake completes and creates a TCP/IP channel, and when the browser and Websocketserver connection succeeds, the OnOpen message is triggered
  25. When the ws.onmessage receives the data sent by Websocketserver, it triggers the onmessage message, and the parameter evt contains the data transmitted by the server;
  26. */
  27. Ws.onopen = function (evt) {
  28. $ (' #msg '). Append (' <li>websocket connection Success </li> ');
  29. }
  30. Ws.onmessage = function (evt) {
  31. $ (' #msg '). Prepend (' <li> ' + evt.data + ' </li> ');
  32. }
  33. });
  34. </script>
  35. </body>

Note : WebSocket (' WS://192.168.1.221:8000/websocket/'); Here the 192.168.1.221 must be changed to your WebSocket server IP, remember!!!

Here, the browser connected to the WebSocket service side of the scene, now to a server to write a piece of code, to collect B server real-time information, in fact, the collection principle is very simple, is to use the shell of the TAILF command, real-time display the latest information just, we in this script, Use subprocess. Popen () To view log information remotely:

The Python code is as follows:

  1. #!/usr/bin/python
  2. # Encoding=utf-8
  3. Import subprocess
  4. Import Time
  5. From WebSocket import create_connection
  6. # Configure remote server IP, account number, password, port, etc., because I do double secret key trust, so do not need password
  7. R_user = "root"
  8. R_IP = "192.168.1.10"
  9. R_port = 22
  10. R_log = "/tmp/web_socket.log" # Log path to be collected by the remote server
  11. # WebSocket Server Address
  12. Ws_server = "ws://192.168.1.221:8000/websocket/"
  13. # Execution of SHELL commands (remote execution using 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. "" Gets the remote server real-time log and sends it to the WebSocket service-side " " "
  17. Popen = subprocess. Popen (cmd,stdout=subprocess. Pipe,stderr=subprocess. Pipe,shell=True)
  18. print (' connection successful ')
  19. WS = Create_connection (ws_server) # Create WebSocket connection
  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 ()

The article finally parses subprocess. The principle and function of Popen

Execute the WebSocket server script and the above WebSocket client capture script, and then open the browser to open the above HTML5 page, the environment is basically deployed, the dual WebSocket client connected to the WebSocket server

The above script Specifies the R_log = "/tmp/web_socket.log" Log path, we need to generate this log file, and continue to write to the log in order to display the effect in the browser in real time (real scene, you can specify a server log, such as Apache, Nginx logs, etc.)

We write a Python code on the B server and write to R_log = "/tmp/web_socket.log" Log every second:

The Python code is as follows:

    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 \ n '% (time.ctime (),random. Random ()))
    9. time.sleep (1)

What the script writes is probably:

[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

Execute the script and look at the browser effect:

This is just my temporary write, if you want to use in the real operation tools, but also need to modify a lot of content according to the specific circumstances, but the principle is this, we can modify according to their own circumstances, perfect use.

Just mentioned subprocess. Popen's principle and function, please see the following information:

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

Bottle WebSocket Reference:

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

DevOps Development: Python websocket Web page displays remote server log information in real time

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.