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:
- #!/usr/bin/env python
- #coding =utf-8
- # __author__ = ' Dairu '
- # http://www.linuxyw.com
- """
- Need to install before executing code
- Pip Install bottle
- Pip Install Websocket-client
- Pip Install Bottle-websocket
- """
- From bottle import get, run
- From Bottle.ext.websocket import geventwebsocketserver
- From Bottle.ext.websocket import WebSocket
- Users = Set () # Connect incoming WebSocket client collection
- @get ('/websocket/', Apply=[websocket])
- def chat (ws):
- Users.add (WS)
- while True:
- msg = Ws.receive () # message to client
- If msg:
- For u in users:
- U.send (msg) # Send a message to all clients
- Else:
- Break
- # If a client disconnects, kick out the Users collection
- Users. Remove (WS)
- 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:
- <! DOCTYPE html>
- <style>
- #msg {
- width:400px; height:400px; Overflow:auto; border:2px solid #000000; color: #ffffff;
- }
- </style>
- <body>
- <p> Real-time log </p>
- <div id="msg" ></div>
- <script src="Http://libs.baidu.com/jquery/1.9.1/jquery.min.js" ></script>
- <script>
- $ (document). Ready (function () {
- / *!window. WebSocket, window. Mozwebsocket Detection of browser support for WebSocket * /
- if (!window. WebSocket) {
- if (window. Mozwebsocket) {
- Window. WebSocket = window. Mozwebsocket;
- } Else {
- $ (' #msg '). Prepend ("<p> your browser does not support websocket</p>");
- }
- }
- / * ws = new WebSocket Create an instance of WebSocket note set the address of the WebSocket to the following OH * /
- WS = new WebSocket (' WS://192.168.1.221:8000/websocket/');
- /*
- Ws.onopen handshake completes and creates a TCP/IP channel, and when the browser and Websocketserver connection succeeds, the OnOpen message is triggered
- 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;
- */
- Ws.onopen = function (evt) {
- $ (' #msg '). Append (' <li>websocket connection Success </li> ');
- }
- Ws.onmessage = function (evt) {
- $ (' #msg '). Prepend (' <li> ' + evt.data + ' </li> ');
- }
- });
- </script>
- </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:
- #!/usr/bin/python
- # Encoding=utf-8
- Import subprocess
- Import Time
- From WebSocket import create_connection
- # Configure remote server IP, account number, password, port, etc., because I do double secret key trust, so do not need password
- R_user = "root"
- R_IP = "192.168.1.10"
- R_port = 22
- R_log = "/tmp/web_socket.log" # Log path to be collected by the remote server
- # WebSocket Server Address
- Ws_server = "ws://192.168.1.221:8000/websocket/"
- # Execution of SHELL commands (remote execution using SSH)
- 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)
- Def tailflog ():
- "" Gets the remote server real-time log and sends it to the WebSocket service-side " " "
- Popen = subprocess. Popen (cmd,stdout=subprocess. Pipe,stderr=subprocess. Pipe,shell=True)
- print (' connection successful ')
- WS = Create_connection (ws_server) # Create WebSocket connection
- while True:
- line = Popen.stdout.readline (). Strip () #获取内容
- If line:
- Ws.send (line) #把内容发送到websocket服务端
- print time . Time ()
- If __name__ = = '__main__ ':
- 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:
- #!/usr/bin/env python
- #coding =utf-8
- Import Time
- Import Random
- Log_path = '/tmp/web_socket.log '
- While 1:
- with open (Log_path, ' a ') as F:
- F.write (' [%s]%s \ n '% (time.ctime (),random. Random ()))
- 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