websocket+Django+python+paramiko實現web頁面執行命令並實時輸出
- 2020 年 2 月 24 日
- 筆記
一、概述
WebSocket
WebSocket的工作流程:瀏覽器通過JavaScript向服務端發出建立WebSocket連接的請求,在WebSocket連接建立成功後,客戶端和服務端就可以通過 TCP連接傳輸數據。因為WebSocket連接本質上是TCP連接,不需要每次傳輸都帶上重複的頭部數據,所以它的數據傳輸量比輪詢和Comet技術小很多。
paramiko
paramiko模組,基於SSH用於連接遠程伺服器並執行相關操作。
shell腳本
/opt/test.sh
#!/bin/bash for i in {1..10} do sleep 0.5 echo 母雞生了$i個雞蛋; done
網頁執行腳本,效果如下:

怎麼樣,是不是很nb!下面會詳細介紹如何具體實現!
二、詳細操作
django版本
最新版本 2.1.5有問題,使用websocket,Google瀏覽器會報錯
WebSocket connection to 'ws://127.0.01:8000/echo_once/' failed: Error during WebSocket handshake: Unexpected response code: 400
所以不能使用最新版本,必須使用 2.1.4以及2.x系列都可以!
安裝模組
pip3 install paramiko dwebsocket django==2.1.4
創建項目
使用Pycharm創建一個項目 wdpy ,這個是測試的,名字無所謂!

添加路由,修改文件 urls.py
from django.contrib import admin from django.urls import path from websocket import views urlpatterns = [ path('admin/', admin.site.urls), path('echo_once/', views.echo_once), ]
修改views.py,增加視圖函數
from django.shortcuts import render from dwebsocket.decorators import accept_websocket, require_websocket from django.http import HttpResponse import paramiko # def exec_command(comm): # hostname = '192.168.0.162' # username = 'root' # password = 'root' # # ssh = paramiko.SSHClient() # ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # ssh.connect(hostname=hostname, username=username, password=password) # stdin, stdout, stderr = ssh.exec_command(comm,get_pty=True) # result = stdout.read() # ssh.close() # yield result @accept_websocket def echo_once(request): if not request.is_websocket(): # 判斷是不是websocket連接 try: # 如果是普通的http方法 message = request.GET['message'] return HttpResponse(message) except: return render(request, 'index.html') else: for message in request.websocket: message = message.decode('utf-8') # 接收前端發來的數據 print(message) if message == 'backup_all':#這裡根據web頁面獲取的值進行對應的操作 command = 'bash /opt/test.sh'#這裡是要執行的命令或者腳本 # 遠程連接伺服器 hostname = '192.168.0.162' username = 'root' password = 'root' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=hostname, username=username, password=password) # 務必要加上get_pty=True,否則執行命令會沒有許可權 stdin, stdout, stderr = ssh.exec_command(command, get_pty=True) # result = stdout.read() # 循環發送消息給前端頁面 while True: nextline = stdout.readline().strip() # 讀取腳本輸出內容 # print(nextline.strip()) request.websocket.send(nextline) # 發送消息到客戶端 # 判斷消息為空時,退出循環 if not nextline: break ssh.close() # 關閉ssh連接 else: request.websocket.send('小樣兒,沒許可權!!!'.encode('utf-8'))
在 templates 目錄下新建文件 index.html
<!DOCTYPE html > <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>CMDB系統</title> <script src="/static/jquery-1.12.4.js"></script> <script type="text/javascript"> $(function () { $('#backup_all').click(function () { var socket = new WebSocket("ws://" + window.location.host + "/echo_once/"); console.log(socket); socket.onopen = function () { console.log('WebSocket open');//成功連接上Websocket socket.send($('#backup_all').val());//發送數據到服務端 }; socket.onmessage = function (e) { console.log('message: ' + e.data);//列印服務端返回的數據 //$('#messagecontainer').prepend('<p><pre>' + e.data + '</pre></p>'); //$('#messagecontainer').prepend('<hr />'); $('#messagecontainer').append(e.data+'<br/>'); {#$('#messagecontainer').prepend('<hr />');#} }; }); }); </script> </head> <body> {#<br>#} <button style="margin: 20px;height: 40px;background-color: #00ff00;" type="button" id="backup_all" value="backup_all"> 執行Shell腳本 </button> <h3 style="margin: 20px;">腳本執行結果:</h3> <div id="messagecontainer" style="margin: 20px;"> </div> <hr/> </body> </html>
和manage.py 同級目錄,新建目錄static,在裡面放 jquery-1.12.4.js 文件
從百度搜索下載即可!
修改 settings.py ,設置satic路徑
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,"static"), )
requirements.txt 這個是項目依賴文件,內容如下:
Django==2.1.4 dwebsocket==0.5.10 paramiko==2.4.2
此時,目錄結果如下:
./ ├── db.sqlite3 ├── manage.py ├── requirements.txt ├── static │ └── jquery-1.12.4.js ├── templates │ └── index.html ├── untitled2 │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── websocket ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py └── views.py
啟動linux伺服器
這裡使用的是linux伺服器,系統是 ubuntu-16.04.4-server-amd64
腳本 /opt/test.sh 就是上面的內容,已經設置了755許可權
啟動項目
使用Pycharm啟動,訪問網頁:
http://127.0.0.1:8000/echo_once/
效果就是上面演示的!
測試命令
除了執行腳本,還可以執行其他命令,比如安裝ntpdate
修改views.py,將 command 修改一下
command = 'apt-get install -y ntpdate'#這裡是要執行的命令或者腳本
再次執行,效果如下:

完整項目
如需完整項目程式碼,請訪問:
https://github.com/py3study/wdpy
本文參考鏈接: https://blog.csdn.net/linxi7/article/details/76161584
注意:這篇文章的效果並不是實時輸出,它是命令執行完成之後,才顯示在網頁上面的!
那麼因此,我在他的程式碼基礎上,做了一些改進!才實現 實時輸出的效果!