標籤:env nbsp 即時 rom function 網頁 jquery 基本 strong
功能:用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代碼:
- #!/usr/bin/env python
- #coding=utf-8
- # __author__ = ‘戴儒鋒‘
- # http://www.linuxyw.com
- """
- 執行代碼前需要安裝
- 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() # 串連進來的websocket用戶端集合
- @get(‘/websocket/‘, apply=[websocket])
- def chat(ws):
- users.add(ws)
- while True:
- msg = ws.receive() # 接用戶端的訊息
- if msg:
- for u in users:
- u.send(msg) # 發送資訊給所有的用戶端
- else:
- break
- # 如果有用戶端中斷連線,則踢出users集合
- users.remove(ws)
- 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服務端:
- <!DOCTYPE html>
- <html>
- <head>
- </head>
- <style>
- #msg{
- width:400px; height:400px; overflow:auto; border:2px solid #000000;color:#ffffff;
- }
- </style>
- </head>
- <body>
- <p>即時日誌</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檢測瀏覽器對websocket的支援*/
- if (!window.WebSocket) {
- if (window.MozWebSocket) {
- window.WebSocket = window.MozWebSocket;
- } else {
- $(‘#msg‘).prepend("<p>你的瀏覽器不支援websocket</p>");
- }
- }
- /* ws = new WebSocket 建立WebSocket的執行個體 注意設定對以下的websocket的地址哦*/
- ws = new WebSocket(‘ws://192.168.1.221:8000/websocket/‘);
- /*
- ws.onopen 握手完成並建立TCP/IP通道,當瀏覽器和WebSocketServer串連成功後,會觸發onopen訊息
- ws.onmessage 接收到WebSocketServer發送過來的資料時,就會觸發onmessage訊息,參數evt中包含server傳輸過來的資料;
- */
- ws.onopen = function(evt) {
- $(‘#msg‘).append(‘<li>websocket串連成功</li>‘);
- }
- ws.onmessage = function(evt) {
- $(‘#msg‘).prepend(‘<li>‘ + evt.data + ‘</li>‘);
- }
- });
- </script>
- </body>
- </html>
注意:WebSocket(‘ws://192.168.1.221:8000/websocket/‘); 這裡的192.168.1.221一定要改成你的websocket服務端IP,切記!!!
到這裡,就搞定瀏覽器串連到websocket服務端的情境了,現在要A伺服器裡寫一段代碼,去採集B伺服器的即時資訊了,其實採集原理很簡單,就是使用shell中的tailf命令,即時顯示最新的資訊而已,我們在這段指令碼中,使用subprocess.Popen()來遠程查看日誌資訊:
python代碼如下:
- #!/usr/bin/python
- # encoding=utf-8
- import subprocess
- import time
- from websocket import create_connection
- # 配置遠程伺服器的IP,帳號,密碼,連接埠等,因我做了雙機密鑰信任,所以不要求輸入密碼
- r_user = "root"
- r_ip = "192.168.1.10"
- r_port = 22
- r_log = "/tmp/web_socket.log" # 遠程伺服器要被採集的日誌路徑
- # websocket服務端地址
- ws_server = "ws://192.168.1.221:8000/websocket/"
- # 執行的shell命令(使用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():
- """擷取遠程伺服器即時日誌,並發送到websocket服務端"""
- popen = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
- print(‘串連成功‘)
- ws = create_connection(ws_server) # 建立websocket串連
- while True:
- line = popen.stdout.readline().strip() #擷取內容
- if line:
- ws.send(line) #把內容發送到websocket服務端
- print time.time()
- if __name__ == ‘__main__‘:
- 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代碼如下:
- #!/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)
指令碼寫入的內容大概是:
[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
執行這段指令碼,然後看瀏覽器效果:
這隻是我臨時寫的,如果要在真實的營運工具中使用,還需要根據具體情況,修改不少內容,但原理就是這樣,大家可根據自己的情況修改,完善使用。
剛才提到subprocess.Popen的原理和功能,請看以下資料:
http://www.cnblogs.com/fengbeihong/articles/3374132.html
bottle websocket參考資料:
http://rfyiamcool.blog.51cto.com/1030776/1269232/
營運開發:python websocket網頁即時顯示遠程伺服器日誌資訊