python製作websocket伺服器執行個體分享,pythonwebsocket

來源:互聯網
上載者:User

python製作websocket伺服器執行個體分享,pythonwebsocket

一、開始的話

  使用python簡單的實現websocket伺服器,可以在瀏覽器上即時顯示遠程伺服器的日誌資訊。

  之前做了一個web版的發布系統,但沒實現線上看日誌,每次發布版本後,都需要登入到伺服器上查看日誌,非常麻煩,為了偷懶,能在頁面點幾下按鈕完成工作,這幾天尋找了這方面的資料,實現了這個功能,瞬間覺的看日誌什麼的,太方便了,以後也可以給開發們查日誌,再也不用麻煩營運了,廢話少說,先看效果吧。

二、代碼

  需求:在web上彈出iframe層來即時顯示遠程伺服器的日誌,點擊stop按鈕,停止日誌輸出,以便查看相關日誌,點start按鈕,繼續輸出日誌,點close按鈕,關閉iframe層。

  在實現這功能前,google了一些資料,發現很多隻能在web上顯示本地的日誌,不能看遠程伺服器的日誌,能看遠程日誌的是引用了其他架構(例如bottle,tornado)來實現的,而且所有這些都是要重寫thread的run方法來實現的,由於本人技術太菜,不知道怎麼改成自己需要的樣子,而且我是用django這個web架構的,不想引入其他架構,搞的太複雜,所以用python簡單的實現websocket伺服器。recv_data方法和send_data是直接引用別人的代碼。由於技術問題,代碼有點粗糙,不過能實現功能就行,先將就著用吧。

執行下面命令啟動django和websocketserver

nohup python manage.py runserver 10.1.12.110 &nohup python websocketserver.py &

  啟動websocket後,接收到請求,起一個線程和用戶端握手,然後根據用戶端發送的ip和type,去資料庫尋找對應的日誌路徑,用paramiko模組ssh登入到遠程伺服器上tail查看日誌,再推送給瀏覽器,服務端完整代碼如下:

# coding:utf-8import osimport structimport base64import hashlibimport socketimport threadingimport paramikodef get_ssh(ip, user, pwd):  try:    ssh = paramiko.SSHClient()    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    ssh.connect(ip, 22, user, pwd, timeout=15)    return ssh  except Exception, e:    print e    return "False"def recv_data(conn):  # 伺服器解析瀏覽器發送的資訊  try:    all_data = conn.recv(1024)    if not len(all_data):      return False  except:    pass  else:    code_len = ord(all_data[1]) & 127    if code_len == 126:      masks = all_data[4:8]      data = all_data[8:]    elif code_len == 127:      masks = all_data[10:14]      data = all_data[14:]    else:      masks = all_data[2:6]      data = all_data[6:]    raw_str = ""    i = 0    for d in data:      raw_str += chr(ord(d) ^ ord(masks[i % 4]))      i += 1    return raw_strdef send_data(conn, data):  # 伺服器處理髮送給瀏覽器的資訊  if data:    data = str(data)  else:    return False  token = "\x81"  length = len(data)  if length < 126:    token += struct.pack("B", length)  # struct為Python中處理位元的模組,二進位流為C,或網路流的形式。  elif length <= 0xFFFF:    token += struct.pack("!BH", 126, length)  else:    token += struct.pack("!BQ", 127, length)  data = '%s%s' % (token, data)  conn.send(data)  return Truedef handshake(conn, address, thread_name):  headers = {}  shake = conn.recv(1024)  if not len(shake):    return False  print ('%s : Socket start handshaken with %s:%s' % (thread_name, address[0], address[1]))  header, data = shake.split('\r\n\r\n', 1)  for line in header.split('\r\n')[1:]:    key, value = line.split(': ', 1)    headers[key] = value  if 'Sec-WebSocket-Key' not in headers:    print ('%s : This socket is not websocket, client close.' % thread_name)    conn.close()    return False  MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'  HANDSHAKE_STRING = "HTTP/1.1 101 Switching Protocols\r\n" \            "Upgrade:websocket\r\n" \            "Connection: Upgrade\r\n" \            "Sec-WebSocket-Accept: {1}\r\n" \            "WebSocket-Origin: {2}\r\n" \            "WebSocket-Location: ws://{3}/\r\n\r\n"  sec_key = headers['Sec-WebSocket-Key']  res_key = base64.b64encode(hashlib.sha1(sec_key + MAGIC_STRING).digest())  str_handshake = HANDSHAKE_STRING.replace('{1}', res_key).replace('{2}', headers['Origin']).replace('{3}', headers['Host'])  conn.send(str_handshake)  print ('%s : Socket handshaken with %s:%s success' % (thread_name, address[0], address[1]))  print 'Start transmitting data...'  print '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'  return Truedef dojob(conn, address, thread_name):  handshake(conn, address, thread_name)   # 握手  conn.setblocking(0)            # 設定socket為非阻塞  ssh = get_ssh('192.168.1.1', 'root', '123456')  # 串連遠程伺服器  ssh_t = ssh.get_transport()  chan = ssh_t.open_session()  chan.setblocking(0)  # 設定非阻塞  chan.exec_command('tail -f /var/log/messages')  while True:    clientdata = recv_data(conn)    if clientdata is not None and 'quit' in clientdata:  # 但瀏覽器點擊stop按鈕或close按鈕時,中斷連線      print ('%s : Socket close with %s:%s' % (thread_name, address[0], address[1]))      send_data(conn, 'close connect')      conn.close()      break    while True:      while chan.recv_ready():        clientdata1 = recv_data(conn)        if clientdata1 is not None and 'quit' in clientdata1:          print ('%s : Socket close with %s:%s' % (thread_name, address[0], address[1]))          send_data(conn, 'close connect')          conn.close()          break        log_msg = chan.recv(10000).strip()  # 接收日誌資訊        print log_msg        send_data(conn, log_msg)      if chan.exit_status_ready():        break      clientdata2 = recv_data(conn)      if clientdata2 is not None and 'quit' in clientdata2:        print ('%s : Socket close with %s:%s' % (thread_name, address[0], address[1]))        send_data(conn, 'close connect')        conn.close()        break    breakdef ws_service():  index = 1  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  sock.bind(("127.0.0.1", 12345))  sock.listen(100)  print ('\r\n\r\nWebsocket server start, wait for connect!')  print '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'  while True:    connection, address = sock.accept()    thread_name = 'thread_%s' % index    print ('%s : Connection from %s:%s' % (thread_name, address[0], address[1]))    t = threading.Thread(target=dojob, args=(connection, address, thread_name))    t.start()    index += 1ws_service()

get_ssh的代碼如下:

import paramikodef get_ssh(ip, user, pwd):  try:    ssh = paramiko.SSHClient()    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    ssh.connect(ip, 22, user, pwd, timeout=15)    return ssh  except Exception, e:    print e    return "False"

開啟頁面時,自動連接websocket伺服器,完成握手,並發送ip和type給服務端,所以可以看不同類型,不同機器上的日誌,

 頁面代碼如下:

<!DOCTYPE html>
<html>
<head>
<title>WebSocket</title>

<style>
#log {
width: 440px;
height: 200px;
border: 1px solid #7F9DB9;
overflow: auto;
}
pre {
margin: 0 0 0;
padding: 0;
border: hidden;
background-color: #0c0c0c;
color: #00ff00;
}
#btns {
text-align: right;
}
</style>

<script>
var socket;
function init() {
var host = "ws://127.0.0.1:12345/";

try {
socket = new WebSocket(host);
socket.onopen = function () {
log('Connected');
};
socket.onmessage = function (msg) {
log(msg.data);
var obje = document.getElementById("log"); //日誌過多時清屏
var textlength = obje.scrollHeight;
if (textlength > 10000) {
obje.innerHTML = '';
}
};
socket.onclose = function () {
log("Lose Connection!");
$("#start").attr('disabled', false);
$("#stop").attr('disabled', true);
};
$("#start").attr('disabled', true);
$("#stop").attr('disabled', false);
}
catch (ex) {
log(ex);
}
}
window.onbeforeunload = function () {
try {
socket.send('quit');
socket.close();
socket = null;
}
catch (ex) {
log(ex);
}
};
function log(msg) {
var obje = document.getElementById("log");
obje.innerHTML += '<pre><code>' + msg + '</code></pre>';
obje.scrollTop = obje.scrollHeight; //捲軸顯示最新資料
}
function stop() {
try {
log('Close connection!');
socket.send('quit');
socket.close();
socket = null;
$("#start").attr('disabled', false);
$("#stop").attr('disabled', true);
}
catch (ex) {
log(ex);
}
}
function closelayer() {
try {
log('Close connection!');
socket.send('quit');
socket.close();
socket = null;
}
catch (ex) {
log(ex);
}
var index = parent.layer.getFrameIndex(window.name); //先得到當前iframe層的索引
parent.layer.close(index); //再執行關閉
}
</script>

</head>


<body onload="init()">
<div >
<div >
<div id="log" ></div>
<br>
</div>
</div>
<div >
<div >
<div id="btns">
<input disabled="disabled" type="button" value="start" id="start" onclick="init()">
<input disabled="disabled" type="button" value="stop" id="stop" onclick="stop()" >
<input type="button" value="close" id="close" onclick="closelayer()" >
</div>
</div>
</div>
</body>

</html>

以上就是本文的全部內容了,希望大家能夠喜歡

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.