从0开发一个webssh(基于django)
了解计算机网络协议的人,应该都知道:HTTP 协议是一种无状态的、无连接的、单向的应用层协议。它采用了请求/响应模型。通信请求只能由客户端发起,服务端对请求做出应答处理。
这种通信模型有一个弊端:HTTP 协议无法实现服务器主动向客户端发起消息。
这种单向请求的特点,注定了如果服务器有连续的状态变化,客户端要获知就非常麻烦。大多数 Web 应用程序将通过频繁的异步JavaScript和XML(AJAX)请求实现长轮询。轮询的效率低,非常浪费资源(因为必须不停连接,或者 HTTP 连接始终打开)。

因此,工程师们一直在思考,有没有更好的方法。WebSocket 就是这样发明的。WebSocket 连接允许客户端和服务器之间进行全双工通信,以便任一方都可以通过建立的连接将数据推送到另一端。WebSocket 只需要建立一次连接,就可以一直保持连接状态。这相比于轮询方式的不停建立连接显然效率要大大提高。

WebSocket 如何工作?
Web浏览器和服务器都必须实现 WebSockets 协议来建立和维护连接。由于 WebSockets 连接长期存在,与典型的HTTP连接不同,对服务器有重要的影响。
基于多线程或多进程的服务器无法适用于 WebSockets,因为它旨在打开连接,尽可能快地处理请求,然后关闭连接。任何实际的 WebSockets 服务器端实现都需要一个异步服务器。
python中的那些框架是异步服务器呢,大多数人会选用tornado。
实现django异步服务器
因为笔者本人是用django框架开发程序的,django又是同步框架,怎么办呢?
这里引出gevent库
gevent自带wsgi的模块,然后还提供websocket的handler。
请在manager.py同级目录建一个start.py,这个文件用于以后的启动。
import os import argparse from gevent import monkey;monkey.patch_all() from gevent.pywsgi import WSGIServer from geventwebsocket.handler import WebSocketHandler from LuffyAudit.wsgi import application #把你自己项目的application导过来 version = "1.0.0" root_path = os.path.dirname(__file__) parser = argparse.ArgumentParser( description="LuffyAudit - 基于WebSocket的堡垒机" ) parser.add_argument('--port','-p', type=int, default=8000, help="服务器端口,默认为8000") parser.add_argument('--host','-H', default="0.0.0.0", help='服务器IP,默认为0.0.0.0') args = parser.parse_args() print('LuffyAudit{0} running on {1}:{2}'.format(version,args.host,args.port)) print((args.host,args.port)) ws_server = WSGIServer( (args.host,args.port), application, log=None, handler_class=WebSocketHandler, ) try: ws_server.serve_forever() except KeyboardInterrupt: print("服务器关闭")
settings.py修改
STATIC_URL = '/statics/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "statics"), ) LOGIN_URL = "/login/" STATIC_ROOT = "statics" SESSION_TRACKER_SCRIPT = os.path.join(BASE_DIR, 'audit/backend/session_tracker.sh')
url修改
from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^hostlist/$',views.host_list, name="host_list"), ] + static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
这样就实现了django的异步通信。
接下来我们开始写js
写到一个js文件,luffy.js
/** * Created by Administrator on 2018-6-25. */ function IronSSHClient(){ } IronSSHClient.prototype._generateURl = function (options) { if (window.location.protocol == "https") { var protocol = "wss://"; }else { var protocol = "ws://"; } var url = protocol + window.location.host + "/host/" + encodeURIComponent(options.des_id) + "/"; return url; }; IronSSHClient.prototype.connect = function (options) { var des_url = this._generateURl(options); if (window.WebSocket){ this._connection = new WebSocket(des_url); } else if (window.MozWebSocket){ this._connection = new MozWebSocket(des_url); } else { options.onError("当前浏览器不支持WebSocket"); return; } this._connection.onopen = function () { options.onConnect(); }; this._connection.onmessage = function (evt) { var data = JSON.parse(evt.data.toString()); console.log(evt,data); if (data.error !== undefined){ options.onError(data.error); } else { options.onData(data.data); } }; this._connection.onclose = function (evt) { options.onClose(); }; }; IronSSHClient.prototype.send = function (data) { this._connection.send(JSON.stringify({'data':data})); };
然后在自己子项目里建一个server.py去实现功能(websocket与ssh的连接通信)
import gevent import paramiko import json from gevent.socket import wait_read,wait_write from . import models class WSSHBridge: """ 桥接websocket 和 SSH的核心类 :param hostname: :param port: :param username: :param password: :return: """ def __init__(self,websocket,user): self.user = user self._websocket = websocket self._tasks = [] self.trans = None self.channel = None self.cptext = '' self.cmd_string = '' def open(self,hostname,port=22,username=None,password=None): """ 建立SSH连接 :param host_ip: :param port: :param username: :param password: :return: """ try: self.trans = paramiko.Transport(hostname,port) self.trans.start_client() self.trans.auth_password(username=username,password=password) channel = self.trans.open_session() channel.get_pty() self.channel = channel except Exception as e: self._websocket.send(json.dumps({"error":e})) raise def _forward_inbound(self,channel): """ 正向数据转发,websocket -> ssh :param channel: :return: """ try: while True: data = self._websocket.receive() if not data: return data = json.loads(str(data)) # data["data"] = data["data"] + "2" if "data" in data: self.cmd_string += data["data"] channel.send(data["data"]) finally: self.close() def _forword_outbound(self,channel): """ 反向数据转发,ssh -> websocket :param channel: :return: """ try: while True: wait_read(channel.fileno()) data = channel.recv(65535) if not len(data): return self._websocket.send(json.dumps({"data":data.decode()})) finally: self.close() def _bridge(self,channel): channel.setblocking(False) channel.settimeout(0.0) self._tasks = [ gevent.spawn(self._forward_inbound,channel), gevent.spawn(self._forword_outbound, channel), ] gevent.joinall(self._tasks) def close(self): """ 结束会话 :return: """ gevent.killall(self._tasks,block=True) self._tasks = [] def shell(self): """ 启动一个shell通信界面 :return: """ self.channel.invoke_shell() self._bridge(self.channel) self.channel.close() # 创建日志 add_log(self.user,self.cmd_string,)
然后写views.py
def connect_host(request,user_bind_host_id): # 如果当前请求不是websocket方式,则退出 if not request.environ.get("wsgi.websocket"): return HttpResponse("错误,非websocket请求") try: remote_user_bind_host = request.user.account.host_user_binds.get(id=user_bind_host_id) except Exception as e: message = "无效的账户,或者无权访问" + str(e)return HttpResponse("请求主机异常"+message) username = remote_user_bind_host.host.ip_addr print(username,request.META.get("REMOTE_ADDR")) message = "来自{remote}的请求 尝试连接 -> {username}@{hostname} <{ip}:{port}>".format( remote = request.META.get("REMOTE_ADDR"),# 请求地址 username = remote_user_bind_host.host_user.username, hostname = remote_user_bind_host.host.hostname, ip = remote_user_bind_host.host.ip_addr, port = remote_user_bind_host.host.port, ) bridge = WSSHBridge(request.environ.get("wsgi.websocket"),request.user) try: bridge.open( hostname=remote_user_bind_host.host.ip_addr, port=remote_user_bind_host.host.port, username=remote_user_bind_host.host_user.username, password=remote_user_bind_host.host_user.password, ) except Exception as e: message = "尝试连接{0}的过程中发生错误 :{1}\n".format( remote_user_bind_host.host.hostname,e ) print(message)return HttpResponse("错误!无法建立SSH连接!") print(request.GET.get("copytext")) bridge.shell() request.environ.get("wsgi.websocket").close() print("用户断开连接....") return HttpResponse("200,ok")
现在实现页面点击连接出发的js代码,首先把之前的luffy.js导入,然后请去网上或git上下载xterm.js,网址。放入自己的js文件夹中,然后导入js和css
<div id="page-body-right" class="panel col-lg-9">
<div class="panel-heading">
<h3 class="panel-title">主机列表</h3>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="host_table" class="table table-striped">
<thead>
<tr>
<th>Hostname</th>
<th>IP</th>
<th>IDC</th>
<th>Port</th>
<th>Username</th>
<th>Login</th>
<th>Token</th>
</tr>
</thead>
<tbody id="hostlist">
</tbody>
</table>
</div>
</div>
</div>
<div id="page-body">
<div id="disconnect" style="margin-top: 20px">
<button type="button" class="btn btn-danger">关闭连接</button>
</div>
<div id="term" class="son"></div>
</div>
<script src="/statics/js/luffy.js"></script>
<script src="/statics/js/xterm.min.js"></script>
<link href="/statics/css/xterm.min.css" rel="stylesheet" type="text/css"/>
<script>
function GetHostlist(gid, self) {
$.get("{% url 'get_host_list' %}", {'gid': gid}, function (callback) {
var data = JSON.parse(callback);
console.log(data);
var trs = '';
$.each(data, function (index, i) {
{# var trs = "<tr><td>" + i.host__hostname + "</td><td>" + i.host__ip__addr#}
trs += "<tr><td>";
trs += i.host__hostname + "</td><td>";
trs += i.host__ip_addr + "</td><td>";
trs += i.host__idc__name + "</td><td>";
trs += i.host__port + "</td><td>";
trs += i.host_user__username + "</td><td>";
trs += "<a class='btn btn-info' onclick=GetToken(this,'" + i.id + "')>Token</a>";
trs += "<span >" + i.id + "</span><button id='conn_button' onclick=Getid(this) type='button' class='btn btn-info' >连接</button>";
trs += "</td></tr>"
});
$("#hostlist").html(trs);
});
$(self).addClass("active").siblings().removeClass("active")
}
function openTerminal(options) { //创建websocket通道 var client = new IronSSHClient(); copytext = false; var term = new Terminal( { cols: 80, rows: 24, handler: function (key) { console.log(key); if (copytext){ client.send(copytext); copytext = false } client.send(key); }, screenKeys: true, useStyle: true, cursorBlink: true }); term.open(); $('.terminal').detach().appendTo('#term'); term.resize(80,24) term.write("开始连接...."); client.connect( $.extend(options, { onError: function (error) { term.write("错误:" + error + "\r\n"); }, onConnect: function () { term.write('\r'); }, onClose: function () { term.write("对方断开了连接......"); }, //term.destroy() onData: function (data) { if (copytext){ term.write(copytext); copytext = false } else { term.write(data) } } } ) ); }
</script>
把上面的页面嵌入到自己的页面,页面写的不好,openTerminal函数参考一下。
这样就基本实现了。
启动方式就是python start.py,后面可以跟参数
如出现admin样式问题,找到Lib\site-packages\django\contrib\admin\static\admin,将静态文件拷贝到自己的static目录
vim还有颜色,可以复制粘贴(这点比term.js好太多)

浙公网安备 33010602011771号