<acronym id="s8ci2"><small id="s8ci2"></small></acronym>
<rt id="s8ci2"></rt><rt id="s8ci2"><optgroup id="s8ci2"></optgroup></rt>
<acronym id="s8ci2"></acronym>
<acronym id="s8ci2"><center id="s8ci2"></center></acronym>
0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

Django3如何使用WebSocket實現WebShell

馬哥Linux運維 ? 來源:從零開始的程序員生活 ? 作者:從零開始的程序員 ? 2021-11-17 09:58 ? 次閱讀

前言最近工作中需要開發前端操作遠程虛擬機的功能,簡稱 WebShell?;诋斍暗募夹g棧為 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
importos

fromdjango.core.asgiimportget_asgi_application
fromwebsocket_app.websocketimportwebsocket_application

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

django_application=get_asgi_application()


asyncdefapplication(scope,receive,send):
ifscope['type']=='http':
awaitdjango_application(scope,receive,send)
elifscope['type']=='websocket':
awaitwebsocket_application(scope,receive,send)
else:
raiseNotImplementedError(f"Unknownscopetype{scope['type']}")


#websocket.py
asyncdefwebsocket_application(scope,receive,send):
pass

#websocket.py
asyncdefwebsocket_application(scope,receive,send):
whileTrue:
event=awaitreceive()

ifevent['type']=='websocket.connect':
awaitsend({
'type':'websocket.accept'
})

ifevent['type']=='websocket.disconnect':
break

ifevent['type']=='websocket.receive':
ifevent['text']=='ping':
awaitsend({
'type':'websocket.send',
'text':'pong!'
})

實現

上面的代碼提供了思路

其中最核心的實現部分我放下面:

classWebSocket:
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
defheaders(self):
returnHeaders(self._scope)

@property
defscheme(self):
returnself._scope["scheme"]

@property
defpath(self):
returnself._scope["path"]

@property
defquery_params(self):
returnQueryParams(self._scope["query_string"].decode())

@property
defquery_string(self)->str:
returnself._scope["query_string"]

@property
defscope(self):
returnself._scope

asyncdefaccept(self,subprotocol:str=None):
"""Acceptconnection.
:paramsubprotocol:Thesubprotocoltheserverwishestoaccept.
:typesubprotocol:str,optional
"""
ifself._client_state==State.CONNECTING:
awaitself.receive()
awaitself.send({"type":SendEvent.ACCEPT,"subprotocol":subprotocol})

asyncdefclose(self,code:int=1000):
awaitself.send({"type":SendEvent.CLOSE,"code":code})

asyncdefsend(self,message:t.Mapping):
ifself._app_state==State.DISCONNECTED:
raiseRuntimeError("WebSocketisdisconnected.")

ifself._app_state==State.CONNECTING:
assertmessage["type"]in{SendEvent.ACCEPT,SendEvent.CLOSE},(
'Couldnotwriteevent"%s"intosocketinconnectingstate.'
%message["type"]
)
ifmessage["type"]==SendEvent.CLOSE:
self._app_state=State.DISCONNECTED
else:
self._app_state=State.CONNECTED

elifself._app_state==State.CONNECTED:
assertmessage["type"]in{SendEvent.SEND,SendEvent.CLOSE},(
'Connectedsocketcansend"%s"and"%s"events,not"%s"'
%(SendEvent.SEND,SendEvent.CLOSE,message["type"])
)
ifmessage["type"]==SendEvent.CLOSE:
self._app_state=State.DISCONNECTED

awaitself._send(message)

asyncdefreceive(self):
ifself._client_state==State.DISCONNECTED:
raiseRuntimeError("WebSocketisdisconnected.")

message=awaitself._receive()

ifself._client_state==State.CONNECTING:
assertmessage["type"]==ReceiveEvent.CONNECT,(
'WebSocketisinconnectingstatebutreceived"%s"event'
%message["type"]
)
self._client_state=State.CONNECTED

elifself._client_state==State.CONNECTED:
assertmessage["type"]in{ReceiveEvent.RECEIVE,ReceiveEvent.DISCONNECT},(
'WebSocketisconnectedbutreceivedinvalidevent"%s".'
%message["type"]
)
ifmessage["type"]==ReceiveEvent.DISCONNECT:
self._client_state=State.DISCONNECTED

returnmessage

縫合怪

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

importasyncio
importtraceback
importparamiko
fromwebshell.sshimportBase,RemoteSSH
fromwebshell.connectionimportWebSocket


classWebShell:
"""整理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

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

defset_ssh(self,ssh_session,chanel_session):
self.ssh_session=ssh_session
self.chanel_session=chanel_session

asyncdefready(self):
awaitself.ws_session.accept()

asyncdefwelcome(self):
#展示Linux歡迎相關內容
foriinrange(2):
ifself.chanel_session.send_ready():
message=self.chanel_session.recv(2048).decode('utf-8')
ifnotmessage:
return
awaitself.ws_session.send_text(message)

asyncdefweb_to_ssh(self):
#print('--------web_to_ssh------->')
whileTrue:
#print('--------------->')
ifnotself.chanel_session.activeornotself.ws_session.status:
return
awaitasyncio.sleep(0.01)
shell=awaitself.ws_session.receive_text()
#print('-------shell-------->',shell)
ifself.chanel_session.activeandself.chanel_session.send_ready():
self.chanel_session.send(bytes(shell,'utf-8'))
#print('--------------->',"end")

asyncdefssh_to_web(self):
#print('<--------ssh_to_web-----------')
whileTrue:
#print('<-------------------')
ifnotself.chanel_session.active:
awaitself.ws_session.send_text('sshclosed')
return
ifnotself.ws_session.status:
return
awaitasyncio.sleep(0.01)
ifself.chanel_session.recv_ready():
message=self.chanel_session.recv(2048).decode('utf-8')
#print('<---------message----------',?message)
ifnotlen(message):
continue
awaitself.ws_session.send_text(message)
#print('<-------------------',?"end")

asyncdefrun(self):
ifnotself.ssh_session:
raiseException("sshnotinit!")
awaitself.ready()
awaitasyncio.gather(
self.web_to_ssh(),
self.ssh_to_web()
)

defclear(self):
try:
self.ws_session.close()
exceptException:
traceback.print_stack()
try:
self.ssh_session.close()
exceptException:
traceback.print_stack()

前端

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

exportclassTermextendsReact.Component{
privateterminal!:HTMLDivElement;
privatefitAddon=newFitAddon();

componentDidMount(){
constxterm=newTerminal();
xterm.loadAddon(this.fitAddon);
xterm.loadAddon(newWebLinksAddon());

//usingwssforhttps
//constsocket=newWebSocket("ws://"+window.location.host+"/api/v1/ws");
constsocket=newWebSocket("ws://localhost:8000/webshell/");
//socket.onclose=(event)=>{
//this.props.onClose();
//}
socket.onopen=(event)=>{
xterm.loadAddon(newAttachAddon(socket));
this.fitAddon.fit();
xterm.focus();
}

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

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

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

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

render(){
return<divclassName="Terminal"ref={(ref)=>this.terminal=refasHTMLDivElement}>div>;
}
}

原文鏈接:https://www.cnblogs.com/lgjbky/p/15186188.html

編輯:jq
聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • 數據
    +關注

    關注

    8

    文章

    6514

    瀏覽量

    87613
  • 主機
    +關注

    關注

    0

    文章

    897

    瀏覽量

    34609
  • 代碼
    +關注

    關注

    30

    文章

    4557

    瀏覽量

    66822
  • WebSocket
    +關注

    關注

    0

    文章

    24

    瀏覽量

    3657

原文標題:Django3 使用 WebSocket 實現 WebShell

文章出處:【微信號:magedu-Linux,微信公眾號:馬哥Linux運維】歡迎添加關注!文章轉載請注明出處。

收藏 人收藏

    評論

    相關推薦

    webshell的四個特征

    webshell檢測預提取特征分析
    發表于 11-05 06:31

    初探實現websocket的心跳重連

    初探和實現websocket心跳重連
    發表于 05-25 15:07

    基于TCP的一種新的網絡協議WebSocket

    開啟 WebSocket 服務WebSocket 服務是網頁程序、安卓 App、微信小程序等獲得數據和服務的接口,是基于TCP 的一種新的網絡協議,它實現了瀏覽器與服務器全雙工通信。通過
    發表于 12-16 07:38

    Python+Django+Mysql實現在線電影推薦系統

    Python+Django+Mysql實現在線電影推薦系統(基于用戶、項目的協同過濾推薦算法)一、項目簡介1、開發工具和實現技術pycharm2020professional版本,python3.8
    發表于 01-03 06:35

    Webshell提權登陸服務器

    Webshell提權登陸服務器
    發表于 09-07 14:04 ?4次下載
    <b class='flag-5'>Webshell</b>提權登陸服務器

    基于Django的XSS防御研究與實現

    跨站腳本攻擊(XSS)是當前最流行的Web應用攻擊方式之一,而Django作為目前比較火熱的Web應用開發框架,并沒有為其開發的Web應用提供有效的XSS防御功能。本文針對此問題,采用中間件,黑白
    發表于 04-09 11:33 ?0次下載
    基于<b class='flag-5'>Django</b>的XSS防御研究與<b class='flag-5'>實現</b>

    什么是WebSocket?進行通信解析 WebSocket 報文及實現

    一般情況下全為 0。當客戶端、服務端協商采用 WebSocket 擴展時,這三個標志位可以非0,且值的含義由擴展進行定義。如果出現非零的值,且并沒有采用 WebSocket 擴展,連接出錯。
    的頭像 發表于 05-15 16:59 ?9191次閱讀
    什么是<b class='flag-5'>WebSocket</b>?進行通信解析 <b class='flag-5'>WebSocket</b> 報文及<b class='flag-5'>實現</b>

    根據WebSocket協議完全使用C++實現函數

    由于需要在項目中增加Websocket協議,與客戶端進行通信,不想使用開源的庫,比如WebSocketPP,就自己根據WebSocket協議實現一套函數,完全使用C++實現。
    的頭像 發表于 11-28 14:29 ?4234次閱讀

    WebSocket有什么優點

    WebSocket是一種在單個TCP連接上進行全雙工通信的協議。WebSocket通信協議于2011年被IETF定為標準RFC 6455,并由RFC7936補充規范。WebSocket API也被W3C定為標準。HTML5開始提
    的頭像 發表于 02-15 15:53 ?7978次閱讀
    <b class='flag-5'>WebSocket</b>有什么優點

    WebSocket工作原理及使用方法

    它有很多名字; WebSocket,WebSocket協議和WebSocket API。從首選的消息傳遞應用程序到流行的在線多人游戲,WebSocket在當今最常用的Web應用程序中是
    的頭像 發表于 05-05 22:12 ?7548次閱讀
    <b class='flag-5'>WebSocket</b>工作原理及使用方法

    Django應用程序開發中設計Django模板的方法

    在本文中,我將介紹在Django應用程序開發中設計Django模板的方法。目的是保持Django應用程序的UI部分井井有條,并避免重復編碼。Django在模板引擎中提供了各種機制來幫助
    的頭像 發表于 07-29 15:44 ?1533次閱讀

    Django Simple Captcha Django驗證組件

    ./oschina_soft/django-simple-captcha.zip
    發表于 05-09 10:53 ?3次下載
    <b class='flag-5'>Django</b> Simple Captcha <b class='flag-5'>Django</b>驗證組件

    Django的簡單應用示例

    Django是python的Web應用框架,并于2008年發布了第一個版本,下面我們先來學習Django的簡單應用示例。
    的頭像 發表于 02-14 14:13 ?760次閱讀
    <b class='flag-5'>Django</b>的簡單應用示例

    WebSocket的6種集成方式介紹

    由于前段時間我實現了一個庫【Spring Cloud】一個配置注解實現 WebSocket 集群方案
    的頭像 發表于 09-02 16:52 ?857次閱讀

    websocket協議的原理

    WebSocket協議是基于TCP的一種新的網絡協議。它實現了瀏覽器與服務器全雙工(full-duplex)通信——允許服務器主動發送信息給客戶端。 WebSocket通信協議于2011年被IETF
    的頭像 發表于 11-09 15:13 ?434次閱讀
    <b class='flag-5'>websocket</b>協議的原理
    亚洲欧美日韩精品久久_久久精品AⅤ无码中文_日本中文字幕有码在线播放_亚洲视频高清不卡在线观看
    <acronym id="s8ci2"><small id="s8ci2"></small></acronym>
    <rt id="s8ci2"></rt><rt id="s8ci2"><optgroup id="s8ci2"></optgroup></rt>
    <acronym id="s8ci2"></acronym>
    <acronym id="s8ci2"><center id="s8ci2"></center></acronym>