從0開發一個webssh(基於django)


了解計算機網絡協議的人,應該都知道:HTTP 協議是一種無狀態的、無連接的、單向的應用層協議。它采用了請求/響應模型。通信請求只能由客戶端發起,服務端對請求做出應答處理。

這種通信模型有一個弊端:HTTP 協議無法實現服務器主動向客戶端發起消息。

這種單向請求的特點,注定了如果服務器有連續的狀態變化,客戶端要獲知就非常麻煩。大多數 Web 應用程序將通過頻繁的異步JavaScript和XML(AJAX)請求實現長輪詢。輪詢的效率低,非常浪費資源(因為必須不停連接,或者 HTTP 連接始終打開)。

ajax-long-polling.png

因此,工程師們一直在思考,有沒有更好的方法。WebSocket 就是這樣發明的。WebSocket 連接允許客戶端和服務器之間進行全雙工通信,以便任一方都可以通過建立的連接將數據推送到另一端。WebSocket 只需要建立一次連接,就可以一直保持連接狀態。這相比於輪詢方式的不停建立連接顯然效率要大大提高。

websockets-flow.png

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好太多)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM