前言最近工作中需要開發前端操作遠程虛擬機的功能,簡稱 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
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
-
數據
+關注
關注
8文章
7030瀏覽量
89038 -
主機
+關注
關注
0文章
995瀏覽量
35136 -
代碼
+關注
關注
30文章
4788瀏覽量
68616 -
WebSocket
+關注
關注
0文章
29瀏覽量
3748
原文標題:Django3 使用 WebSocket 實現 WebShell
文章出處:【微信號:magedu-Linux,微信公眾號:馬哥Linux運維】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
相關推薦
評論