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,谷歌浏览器会报错
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'))