Django3+websocket+paramiko实现web页面实时输出

一、概述

在上一篇文章中,简单在浏览器测试了websocket,链接如下:https://www.cnblogs.com/xiao987334176/p/13615170.html

但是,我们最终的效果是web页面上,能够实时输出结果,比如执行一个shell脚本。

以母鸡下蛋的例子,来演示一下,先来看效果:

 

二、代码实现

环境说明

操作系统:windows 10

python版本:3.7.9

 

操作系统:centos 7.6

ip地址:192.168.31.196

 

说明:windows10用来运行django项目,centos系统用来执行shell脚本。脚本路径为:/opt/test.sh,内容如下:

#!/bin/bash

for i in {1..10}
do
    sleep 0.5
    echo 母鸡生了$i个鸡蛋;
done

 

新建项目

这里,我在上篇文章中的项目基础上,进行修改。项目:django3_websocket,应用名称:web

安装paramiko模块

pip3 install paramiko

 

修改urls.py,增加首页

from django.contrib import admin
from django.urls import path
from web import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
]

 

修改web目录下的views.py,内容如下:

from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request,'index.html')

 

修改web目录下的websocket.py,内容如下:

# !/usr/bin/python3
# -*- coding: utf-8 -*-
import paramiko


async def websocket_application(scope, receive, send):
    while True:
        event = await receive()

        if event['type'] == 'websocket.connect':
            await send({
                'type': 'websocket.accept'
            })

        if event['type'] == 'websocket.disconnect':
            break

        if event['type'] == 'websocket.receive':
            if event['text'] == 'ping':
                await send({
                    'type': 'websocket.send',
                    'text': 'pong!'
                })

            # 这里根据web页面获取的值进行对应的操作
            if event['text'] == 'laying_eggs':
                print("要执行脚本了")
                # 执行的命令或者脚本
                command = 'bash /opt/test.sh'

                # 远程连接服务器
                hostname = '192.168.31.196'
                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())
                    # 发送消息到客户端
                    await send({
                        'type': 'websocket.send',
                        'text': nextline
                    })
                    # 判断消息为空时,退出循环
                    if not nextline:
                        break

                ssh.close()  # 关闭ssh连接
                # 关闭websocket连接
                await send({
                    'type': 'websocket.close',
                })
View Code

注意:这里面的服务器ip,用户名,密码,脚本路径。请根据实际情况修改! 

 

在templates目录下,新建文件index.html,内容如下:

<!DOCTYPE html >
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>测试demo</title>
    <style type="text/css">
        #execute_script {
            margin: 20px;
            height: 40px;
            background-color: #00ff00;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

</head>
<body>

<button type="button" id="execute_script" value="laying_eggs">执行Shell脚本</button>
<h3 style="margin: 20px;">脚本执行结果:</h3>
<div id="messagecontainer" style="margin: 20px;">
</div>
<hr/>
</body>
<script type="text/javascript">
    $(function () {

    });
    // 点击按钮
    $('#execute_script').click(function () {
        // 打开一个 web socket
        var socket = new WebSocket("ws://" + window.location.host);
        console.log(socket);
        // 连接建立成功事件
        socket.onopen = function () {
            console.log('WebSocket open');
            //发送字符: laying_eggs到服务端
            socket.send('laying_eggs');
        };
        // 接收消息事件
        socket.onmessage = function (e) {
            if (e.data.length > 0) {
                //打印服务端返回的数据
                console.log('message: ' + e.data);
                $('#messagecontainer').append(e.data + '<br/>');
            }
        };
        // 关闭连接事件
        socket.onclose = function(e) {
            console.log("connection closed (" + e.code + ")");
        }
    });
</script>
</html>
View Code

 

使用uvicorn启动项目

uvicorn web.asgi:application

 

访问首页

http://127.0.0.1:8000/index/

 

 

 点击执行脚本,效果就是文章开头部分的动态效果了。

 

完整代码在github中,地址:

https://github.com/py3study/django3_websocket

 

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Django中使用WebSocket实现系统消息通知可以通过以下步骤实现: 1. 安装Django Channels和asgiref ```bash pip install channels asgiref ``` 2. 创建一个Django应用程序 ```bash python manage.py startapp notifications ``` 3. 创建一个WebSocket路由 在`notifications`应用程序中创建一个`routing.py`文件,添加以下内容: ```python from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/notifications/$', consumers.NotificationConsumer.as_asgi()), ] ``` 4. 创建一个WebSocket消费者 在`notifications`应用程序中创建一个`consumers.py`文件,添加以下内容: ```python import asyncio import json from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from django.contrib.auth.models import User class NotificationConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept" }) user = self.scope["user"] if user.is_authenticated: await self.channel_layer.group_add( f"user_{user.id}", self.channel_name ) async def websocket_receive(self, event): user = self.scope["user"] if user.is_authenticated: data = json.loads(event["text"]) message = data["message"] await self.create_message(user, message) await self.channel_layer.group_send( f"user_{user.id}", { "type": "user.message", "message": message } ) async def websocket_disconnect(self, event): user = self.scope["user"] if user.is_authenticated: await self.channel_layer.group_discard( f"user_{user.id}", self.channel_name ) @database_sync_to_async def create_message(self, user, message): user = User.objects.get(id=user.id) user.notifications.create(message=message) ``` 5. 配置WebSocket路由 在`settings.py`文件中添加以下内容: ```python ASGI_APPLICATION = 'project_name.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } ROOT_URLCONF = 'project_name.urls' INSTALLED_APPS = [ ... 'channels', 'notifications', ] ``` 6. 创建一个JavaScript文件 在`static/js/notifications.js`文件中添加以下内容: ```javascript var socket = new WebSocket("ws://" + window.location.host + "/ws/notifications/"); socket.onmessage = function(event) { var message = JSON.parse(event.data)["message"]; alert(message); } ``` 7. 在模板中引入JavaScript文件 在需要使用WebSocket的模板中添加以下内容: ```html {% load static %} <script src="{% static 'js/notifications.js' %}"></script> ``` 现在,当用户登录并连接到WebSocket时,他们将加入名为`user_<user_id>`的组。当用户收到新消息时,消息将保存到数据库中,并通过WebSocket发送到所有连接到该组的用户。在前端,我们使用JavaScript来处理接收到的消息,这里简单地使用了一个警报框来显示消息,你可以改为使用其他的UI库。 希望这个教程能够帮助你实现DjangoWebSocket的消息通知功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值