前言最近工作中需要開發(fā)前端操作遠(yuǎn)程虛擬機(jī)的功能,簡稱 WebShell。基于當(dāng)前的技術(shù)棧為 react+django,調(diào)研了一會(huì)發(fā)現(xiàn)大部分的后端實(shí)現(xiàn)都是 django+channels 來實(shí)現(xiàn) websocket 服務(wù)。
大致看了下覺得這不夠有趣,翻了翻 django 的官方文檔發(fā)現(xiàn) django 原生是不支持 websocket 的,但 django3 之后支持了 asgi 協(xié)議可以自己實(shí)現(xiàn) websocket 服務(wù)。
于是選定 gunicorn+uvicorn+asgi+websocket+django3.2+paramiko 來實(shí)現(xiàn) WebShell。
實(shí)現(xiàn) websocket 服務(wù)使用 django 自帶的腳手架生成的項(xiàng)目會(huì)自動(dòng)生成 asgi.py 和 wsgi.py 兩個(gè)文件,普通應(yīng)用大部分用的都是 wsgi.py 配合 nginx 部署線上服務(wù)。
這次主要使用 asgi.py 實(shí)現(xiàn) websocket 服務(wù)的思路大致網(wǎng)上搜一下就能找到,主要就是實(shí)現(xiàn) connect/send/receive/disconnect 這個(gè)幾個(gè)動(dòng)作的處理方法。
這里 How to Add Websockets to a Django App without Extra Dependencies就是一個(gè)很好的實(shí)例,但過于簡單……
思路
#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!'
})
實(shí)現(xiàn)
上面的代碼提供了思路
其中最核心的實(shí)現(xiàn)部分我放下面:
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
縫合怪
做為合格的代碼搬運(yùn)工,為了提高搬運(yùn)效率還是要造點(diǎn)輪子填點(diǎn)坑的,如何將上面的 WebSocket 類與 paramiko 結(jié)合起來,實(shí)現(xiàn)從前端接受字符傳遞給遠(yuǎn)程主機(jī),并同時(shí)接受返回呢?
importasyncio
importtraceback
importparamiko
fromwebshell.sshimportBase,RemoteSSH
fromwebshell.connectionimportWebSocket
classWebShell:
"""整理WebSocket和paramiko.Channel,實(shí)現(xiàn)兩者的數(shù)據(jù)互通"""
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歡迎相關(guān)內(nèi)容
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 完全滿足,搜索下找個(gè)看著簡單的就行。
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
-
數(shù)據(jù)
+關(guān)注
關(guān)注
8文章
7232瀏覽量
90685 -
主機(jī)
+關(guān)注
關(guān)注
0文章
1029瀏覽量
35713 -
代碼
+關(guān)注
關(guān)注
30文章
4874瀏覽量
69934 -
WebSocket
+關(guān)注
關(guān)注
0文章
30瀏覽量
3960
原文標(biāo)題:Django3 使用 WebSocket 實(shí)現(xiàn) WebShell
文章出處:【微信號:magedu-Linux,微信公眾號:馬哥Linux運(yùn)維】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。
發(fā)布評論請先 登錄
相關(guān)推薦
Python+Django+Mysql實(shí)現(xiàn)在線電影推薦系統(tǒng)
基于Django的XSS防御研究與實(shí)現(xiàn)

什么是WebSocket?進(jìn)行通信解析 WebSocket 報(bào)文及實(shí)現(xiàn)

Django教程之Django的使用心得詳細(xì)資料免費(fèi)下載

根據(jù)WebSocket協(xié)議完全使用C++實(shí)現(xiàn)函數(shù)
使用websocket技術(shù)實(shí)現(xiàn)后端向前端的推送消息

WebSocket有什么優(yōu)點(diǎn)
WebSocket工作原理及使用方法

在Django應(yīng)用程序開發(fā)中設(shè)計(jì)Django模板的方法
Django Simple Captcha Django驗(yàn)證組件

Django的簡單應(yīng)用示例

WebSocket的6種集成方式介紹
websocket協(xié)議的原理

評論