前言最近工作中需要开发前端操作远程虚拟机的功能,简称 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文章
7002浏览量
88937 -
主机
+关注
关注
0文章
993浏览量
35114 -
代码
+关注
关注
30文章
4779浏览量
68516 -
WebSocket
+关注
关注
0文章
29浏览量
3745
原文标题:Django3 使用 WebSocket 实现 WebShell
文章出处:【微信号:magedu-Linux,微信公众号:马哥Linux运维】欢迎添加关注!文章转载请注明出处。
发布评论请先 登录
相关推荐
评论