好湿?好紧?好多水好爽自慰,久久久噜久噜久久综合,成人做爰A片免费看黄冈,机机对机机30分钟无遮挡

主頁 > 知識庫 > Django3基于WebSocket實現WebShell的詳細過程

Django3基于WebSocket實現WebShell的詳細過程

熱門標簽:地圖標注審核表 宿遷星美防封電銷卡 ai電銷機器人源碼 西藏房產智能外呼系統要多少錢 百度地圖標注沒有了 湛江智能外呼系統廠家 外呼并發線路 長沙高頻外呼系統原理是什么 ai電話機器人哪里好

前言

最近工作中需要開發前端操作遠程虛擬機的功能,簡稱WebShell. 基于當前的技術棧為react+django,調研了一會發現大部分的后端實現都是django+channels來實現websocket服務.
大致看了下覺得這不夠有趣,翻了翻django的官方文檔發現django原生是不支持websocket的,但django3之后支持了asgi協議可以自己實現websocket服務. 于是選定
gunicorn+uvicorn+asgi+websocket+django3.2+paramiko來實現WebShell.

實現websocket服務

使用django自帶的腳手架生成的項目會自動生成asgi.py和wsgi.py兩個文件,普通應用大部分用的都是wsgi.py配合nginx部署線上服務. 這次主要使用asgi.py
實現websocket服務的思路大致網上搜一下就能找到,主要就是實現 connect/send/receive/disconnect這個幾個動作的處理方法.
這里 How to Add Websockets to a Django App without Extra Dependencies 就是一個很好的實例
, 但過于簡單........:

思路

# asgi.py 
import os

from django.core.asgi import get_asgi_application
from websocket_app.websocket import websocket_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket_app.settings')

django_application = get_asgi_application()


async def application(scope, receive, send):
    if scope['type'] == 'http':
        await django_application(scope, receive, send)
    elif scope['type'] == 'websocket':
        await websocket_application(scope, receive, send)
    else:
        raise NotImplementedError(f"Unknown scope type {scope['type']}")


# websocket.py
async def websocket_application(scope, receive, send):
    pass
# websocket.py
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!'
                })

實現

上面的代碼提供了思路,比較完整的可以參考這里 websockets-in-django-3-1 基本可以復用了
其中最核心的實現部分我放下面:

class WebSocket:
    def __init__(self, scope, receive, send):
        self._scope = scope
        self._receive = receive
        self._send = send
        self._client_state = State.CONNECTING
        self._app_state = State.CONNECTING

    @property
    def headers(self):
        return Headers(self._scope)

    @property
    def scheme(self):
        return self._scope["scheme"]

    @property
    def path(self):
        return self._scope["path"]

    @property
    def query_params(self):
        return QueryParams(self._scope["query_string"].decode())

    @property
    def query_string(self) -> str:
        return self._scope["query_string"]

    @property
    def scope(self):
        return self._scope

    async def accept(self, subprotocol: str = None):
        """Accept connection.
        :param subprotocol: The subprotocol the server wishes to accept.
        :type subprotocol: str, optional
        """
        if self._client_state == State.CONNECTING:
            await self.receive()
        await self.send({"type": SendEvent.ACCEPT, "subprotocol": subprotocol})

    async def close(self, code: int = 1000):
        await self.send({"type": SendEvent.CLOSE, "code": code})

    async def send(self, message: t.Mapping):
        if self._app_state == State.DISCONNECTED:
            raise RuntimeError("WebSocket is disconnected.")

        if self._app_state == State.CONNECTING:
            assert message["type"] in {SendEvent.ACCEPT, SendEvent.CLOSE}, (
                    'Could not write event "%s" into socket in connecting state.'
                    % message["type"]
            )
            if message["type"] == SendEvent.CLOSE:
                self._app_state = State.DISCONNECTED
            else:
                self._app_state = State.CONNECTED

        elif self._app_state == State.CONNECTED:
            assert message["type"] in {SendEvent.SEND, SendEvent.CLOSE}, (
                    'Connected socket can send "%s" and "%s" events, not "%s"'
                    % (SendEvent.SEND, SendEvent.CLOSE, message["type"])
            )
            if message["type"] == SendEvent.CLOSE:
                self._app_state = State.DISCONNECTED

        await self._send(message)

    async def receive(self):
        if self._client_state == State.DISCONNECTED:
            raise RuntimeError("WebSocket is disconnected.")

        message = await self._receive()

        if self._client_state == State.CONNECTING:
            assert message["type"] == ReceiveEvent.CONNECT, (
                    'WebSocket is in connecting state but received "%s" event'
                    % message["type"]
            )
            self._client_state = State.CONNECTED

        elif self._client_state == State.CONNECTED:
            assert message["type"] in {ReceiveEvent.RECEIVE, ReceiveEvent.DISCONNECT}, (
                    'WebSocket is connected but received invalid event "%s".'
                    % message["type"]
            )
            if message["type"] == ReceiveEvent.DISCONNECT:
                self._client_state = State.DISCONNECTED

        return message

縫合怪

做為合格的代碼搬運工,為了提高搬運效率還是要造點輪子填點坑的,如何將上面的WebSocket類與paramiko結合起來實現從前端接受字符傳遞給遠程主機并同時接受返回呢?

import asyncio
import traceback
import paramiko
from webshell.ssh import Base, RemoteSSH
from webshell.connection import WebSocket


class WebShell:
    """整理 WebSocket 和 paramiko.Channel,實現兩者的數據互通"""

    def __init__(self, ws_session: WebSocket,
                 ssh_session: paramiko.SSHClient = None,
                 chanel_session: paramiko.Channel = None
                 ):
        self.ws_session = ws_session
        self.ssh_session = ssh_session
        self.chanel_session = chanel_session

    def init_ssh(self, host=None, port=22, user="admin", passwd="admin@123"):
        self.ssh_session, self.chanel_session = RemoteSSH(host, port, user, passwd).session()

    def set_ssh(self, ssh_session, chanel_session):
        self.ssh_session = ssh_session
        self.chanel_session = chanel_session

    async def ready(self):
        await self.ws_session.accept()

    async def welcome(self):
        # 展示Linux歡迎相關內容
        for i in range(2):
            if self.chanel_session.send_ready():
                message = self.chanel_session.recv(2048).decode('utf-8')
                if not message:
                    return
                await self.ws_session.send_text(message)

    async def web_to_ssh(self):
        # print('--------web_to_ssh------->')
        while True:
            # print('--------------->')
            if not self.chanel_session.active or not self.ws_session.status:
                return
            await asyncio.sleep(0.01)
            shell = await self.ws_session.receive_text()
            # print('-------shell-------->', shell)
            if self.chanel_session.active and self.chanel_session.send_ready():
                self.chanel_session.send(bytes(shell, 'utf-8'))
            # print('--------------->', "end")

    async def ssh_to_web(self):
        # print('--------ssh_to_web-----------')
        while True:
            # print('-------------------')
            if not self.chanel_session.active:
                await self.ws_session.send_text('ssh closed')
                return
            if not self.ws_session.status:
                return
            await asyncio.sleep(0.01)
            if self.chanel_session.recv_ready():
                message = self.chanel_session.recv(2048).decode('utf-8')
                # print('---------message----------', message)
                if not len(message):
                    continue
                await self.ws_session.send_text(message)
            # print('-------------------', "end")

    async def run(self):
        if not self.ssh_session:
            raise Exception("ssh not init!")
        await self.ready()
        await asyncio.gather(
            self.web_to_ssh(),
            self.ssh_to_web()
        )

    def clear(self):
        try:
            self.ws_session.close()
        except Exception:
            traceback.print_stack()
        try:
            self.ssh_session.close()
        except Exception:
            traceback.print_stack()

前端

xterm.js 完全滿足,搜索下找個看著簡單的就行.

export class Term extends React.Component {
    private terminal!: HTMLDivElement;
    private fitAddon = new FitAddon();

    componentDidMount() {
        const xterm = new Terminal();
        xterm.loadAddon(this.fitAddon);
        xterm.loadAddon(new WebLinksAddon());

        // using wss for https
        //         const socket = new WebSocket("ws://" + window.location.host + "/api/v1/ws");
        const socket = new WebSocket("ws://localhost:8000/webshell/");
        // socket.onclose = (event) => {
        //     this.props.onClose();
        // }
        socket.onopen = (event) => {
            xterm.loadAddon(new AttachAddon(socket));
            this.fitAddon.fit();
            xterm.focus();
        }

        xterm.open(this.terminal);
        xterm.onResize(({ cols, rows }) => {
            socket.send("RESIZE>" + cols + "," + rows)
        });

        window.addEventListener('resize', this.onResize);
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.onResize);
    }

    onResize = () => {
        this.fitAddon.fit();
    }

    render() {
        return div className="Terminal" ref={(ref) => this.terminal = ref as HTMLDivElement}>/div>;
    }
}

好了,廢話不多少了,代碼我放這里了webshell 歡迎star/fork!

參考資料

webshell

django文檔

graphene-django文檔

django 異步視圖

websockets-in-django-3-1

How to Add Websockets to a Django App without Extra Dependencies

到此這篇關于Django3使用WebSocket實現WebShell的文章就介紹到這了,更多相關Django3實現WebShell內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Django websocket原理及功能實現代碼
  • 詳解Django3中直接添加Websockets方式
  • Django通過dwebsocket實現websocket的例子
  • 詳解Django-channels 實現WebSocket實例
  • Django使用Channels實現WebSocket的方法

標簽:寧夏 大同 林芝 南平 海南 漯河 普洱 盤錦

巨人網絡通訊聲明:本文標題《Django3基于WebSocket實現WebShell的詳細過程》,本文關鍵詞  Django3,基于,WebSocket,實現,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Django3基于WebSocket實現WebShell的詳細過程》相關的同類信息!
  • 本頁收集關于Django3基于WebSocket實現WebShell的詳細過程的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 91久久精品青青草原伊人| 小鲜肉男男Gay做受XXX网站| 国产伦精品一区二区三区视频黑人| 干干射| 91视频完整版高清| 中文彩漫多香子u罗汉漫画最新版| 免费看女人稳私app| 国产精品21区| 草草视频在线免费观看| 天天综合五月天| 中文字幕亚洲| 免费看又色又爽又黄的APP| 武则天一级婬片高清免费观看| 色网站在线免费观看| 国产日韩欧美一区| 三国性艳史三级在线观看 | 冲田杏梨午夜久久99视| 高h花蒂失禁| 成人自拍视频在线观看| 国产良心大作白丝精厕| 国产xxxx99真实实拍| 美女gif出处抽搐动态图| 情侣国产一二三区视频观看| 国产精品18久久久久久不卡| 夜夜夜AV视频一二三区| 金沙383直播的最新版本更新内容| 8050午夜二级一片 更新时间| 曰曰鲁夜夜免费播放直播| 色欲98AⅤ蜜臀aV欧美| 调教屁股羞耻撅着跪着| 动漫3d美女被吸乳羞羞漫画| 美女视频网站免费看| freefron性中国国产高清| _日本一级特黄大片老鸭 www. | 丽玲老师高跟鞋调教小说| 国产自制一区| 亚洲日本中文字幕| 爱我免费视频观看在线www| 97色伦图片97综合影院| 和黑大佬的365天第一部| 欧美一卡二三卡四卡不卡|