1、安装
Django # 大于2.0,小于2.1.5 dwebsocket paramiko
2、视图
from dwebsocket.decorators import accept_websocket import paramiko
@accept_websocket def show_log(request): # 判断是不是websocket连接 if not request.is_websocket(): # 如果是普通的http方法 try: message = request.GET['message'] return HttpResponse(message) except: return render(request, 'show_log.html') else: for message in request.websocket: # 接收前端发来的数据 message = message.decode('utf-8') print(message) # 这里根据web页面获取的值进行对应的操作 if message == 'backup_all': # 这里是要执行的命令或者脚本 command = 'bash /home/lezhu/projects/ACG/test.sh' # 远程连接服务器 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=config.host_name, username=config.username, password=config.password) # 务必要加上get_pty=True,否则执行命令会没有权限 stdin, stdout, stderr = ssh.exec_command(command, get_pty=True) # 循环发送消息给前端页面 while True: # 读取脚本输出内容 next_line = stdout.readline().strip() # 发送消息到客户端 request.websocket.send(next_line.encode('utf-8')) # 判断消息为空时,退出循环 if not next_line: break # 关闭ssh连接 ssh.close() else: request.websocket.send('小样儿,没权限!!!'.encode('utf-8'))
3、路由 省略
4、模板(前段)
{% extends 'base.html' %} {% block content %} <button style="margin: 20px;height: 40px;background-color: #337ab7; border-color: #2e6da4;" type="button" id="backup_all" value="backup_all"> 查看日志 </button> <h3 style="margin: 20px;">脚本执行结果:</h3> <div id="messagecontainer" style="margin: 20px;"> </div> <hr/> {% endblock %} {% block my_script %} <script type="text/javascript"> $(function () { $('#backup_all').click(function () { var socket = new WebSocket("ws://" + window.location.host + "/show_log/"); 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').append(e.data + '<br/>'); }; }); }); </script> {% endblock %}