營運開發:python websocket網頁即時顯示遠程伺服器日誌資訊

來源:互聯網
上載者:User

標籤: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代碼:

 
  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.             width: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 \n‘ % (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

執行這段指令碼,然後看瀏覽器效果:

 

這隻是我臨時寫的,如果要在真實的營運工具中使用,還需要根據具體情況,修改不少內容,但原理就是這樣,大家可根據自己的情況修改,完善使用。

 

剛才提到subprocess.Popen的原理和功能,請看以下資料:

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

bottle websocket參考資料:

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

營運開發:python websocket網頁即時顯示遠程伺服器日誌資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.