欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解基于django實現(xiàn)的webssh簡單例子

 更新時間:2018年07月17日 08:30:42   作者:295631788  
這篇文章主要介紹了基于 django 實現(xiàn)的 webssh 簡單例子,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

本文介紹了詳解基于django實現(xiàn)的webssh簡單例子,分享給大家,具體如下:

說明

新建一個 django 程序,本文為 chain。

以下僅為簡單例子,實際應(yīng)用 可根據(jù)自己平臺情況 進行修改。

打開首頁后,需要輸入1,后臺去登錄主機,然后返回登錄結(jié)果。

正常項目 可以post 主機和登錄賬戶,進行權(quán)限判斷,然后去后臺讀取賬戶密碼,進行登錄。

djang后臺

需要安裝以下模塊

安裝后會有一個版本號報錯,不影響

channels==2.0.2
channels-redis==2.1.0
amqp==1.4.9
anyjson==0.3.3
asgi-redis==1.4.3
asgiref==2.3.0
async-timeout==2.0.0
attrs==17.4.0

cd /tmp/
wget https://files.pythonhosted.org/packages/12/2a/e9e4fb2e6b2f7a75577e0614926819a472934b0b85f205ba5d5d2add54d0/Twisted-18.4.0.tar.bz2
tar xf Twisted-18.4.0.tar.bz2
cd Twisted-18.4.0
python3 setup.py install

啟動redis

目錄

chain/
    chain/
       settings.py
       asgi.py
       consumers.py
       routing.py
  templates/
      index.html

settings.py

# django-channels配置
CHANNEL_LAYERS = {
  "default": {
    "BACKEND": "channels_redis.core.RedisChannelLayer",
    "CONFIG": {
      "hosts": [("127.0.0.1", 6379)],
    },
  },
}

# 配置ASGI
ASGI_APPLICATION = "chain.routing.application"

consumers.py

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer

import paramiko
import threading
import time

from channels.layers import get_channel_layer
channel_layer = get_channel_layer()

class MyThread(threading.Thread):
  def __init__(self, id, chan):
    threading.Thread.__init__(self)
    self.chan = chan

  def run(self):
    while not self.chan.chan.exit_status_ready():
      time.sleep(0.1)
      try:
        data = self.chan.chan.recv(1024)
        async_to_sync(self.chan.channel_layer.group_send)(
          self.chan.scope['user'].username,
          {
            "type": "user.message",
            "text": bytes.decode(data)
          },
        )
      except Exception as ex:
        print(str(ex))
    self.chan.sshclient.close()
    return False

class EchoConsumer(WebsocketConsumer):

  def connect(self):
    # 創(chuàng)建channels group, 命名為:用戶名,并使用channel_layer寫入到redis
    async_to_sync(self.channel_layer.group_add)(self.scope['user'].username, self.channel_name)
    # 返回給receive方法處理
    self.accept()

  def receive(self, text_data):

    if text_data == '1':
      self.sshclient = paramiko.SSHClient()
      self.sshclient.load_system_host_keys()
      self.sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
      self.sshclient.connect('47.104.140.38', 22, 'root', '123456')
      self.chan = self.sshclient.invoke_shell(term='xterm')
      self.chan.settimeout(0)
      t1 = MyThread(999, self)
      t1.setDaemon(True)
      t1.start()
    else:
      try:
        self.chan.send(text_data)
      except Exception as ex:
        print(str(ex))

  def user_message(self, event):
    # 消費
    self.send(text_data=event["text"])

  def disconnect(self, close_code):
    async_to_sync(self.channel_layer.group_discard)(self.scope['user'].username, self.channel_name)

asgi.py

import os
import django
from channels.routing import get_default_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chain.settings")
django.setup()
application = get_default_application()
routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import URLRouter, ProtocolTypeRouter
from django.urls import path

from .consumers import EchoConsumer

application = ProtocolTypeRouter({
  "websocket": AuthMiddlewareStack(
    URLRouter([
      path(r"ws/", EchoConsumer),
      # path(r"stats/", StatsConsumer),
    ])
  )
})

網(wǎng)頁設(shè)置:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>django webssh 例子</title>

  <link href="/static/css/plugins/ztree/awesomeStyle/awesome.css" rel="external nofollow" rel="stylesheet">

  <link href="/static/webssh_static/css/xterm.min.css" rel="external nofollow" rel="stylesheet" type="text/css"/>
  <style>
    body {
      padding-bottom: 30px;
    }

    .terminal {
      border: #000 solid 5px;
      font-family: cursive;
    {#        font-family: Arial, Helvetica, Tahoma ,"Monaco", "DejaVu Sans Mono", "Liberation Mono", sans-serif;#}{#        font-family: Tahoma, Helvetica, Arial, sans-serif;#}{#        font-family: "\5B8B\4F53","","Monaco", "DejaVu Sans Mono", "Liberation Mono", "Microsoft YaHei", monospace;#} font-size: 15px;
    {#        color: #f0f0f0;#} background: #000;
    {#        width: 893px;#}{#        height: 550px;#} box-shadow: rgba(0, 0, 0, 0.8) 2px 2px 20px;
    }

    .reverse-video {
      color: #000;
      background: #f0f0f0;
    }
  </style>
</head>
<body>

<div id="terms"></div>
</body>

<script src="/static/webssh_static/js/xterm.min.js"></script>
<script>
  var socket = new WebSocket('ws://' + window.location.host + '/ws/');

  socket.onopen = function () {

    var term = new Terminal();
    term.open(document.getElementById('terms'));

    term.on('data', function (data) {
      console.log(data);
      socket.send(data);
    });

    socket.onmessage = function (msg) {
      console.log(msg);
      console.log(msg.data);
      term.write(msg.data);
    };
    socket.onerror = function (e) {
      console.log(e);
    };

    socket.onclose = function (e) {
      console.log(e);
      term.destroy();
    };
  };

</script>
</html>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python 把序列轉(zhuǎn)換為元組的函數(shù)tuple方法

    Python 把序列轉(zhuǎn)換為元組的函數(shù)tuple方法

    今天小編就為大家分享一篇Python 把序列轉(zhuǎn)換為元組的函數(shù)tuple方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • Python采集騰訊新聞實例

    Python采集騰訊新聞實例

    這篇文章主要介紹了Python采集騰訊新聞實例,一個簡單的例子,著重于實現(xiàn)步驟的講解,需要的朋友可以參考下
    2014-07-07
  • Python的10道簡單測試題(含答案)

    Python的10道簡單測試題(含答案)

    這篇文章主要介紹了Python的10道簡單測試題(含答案),學(xué)習(xí)了一段時間python的小伙伴來做幾道測試題檢驗一下自己的學(xué)習(xí)成果吧
    2023-04-04
  • 詳解Python如何獲取視頻文件的大小和時長

    詳解Python如何獲取視頻文件的大小和時長

    這篇文章主要為大家詳細介紹了Python如何實現(xiàn)獲取視頻文件的大小和時長,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下
    2023-03-03
  • Python for循環(huán)搭配else常見問題解決

    Python for循環(huán)搭配else常見問題解決

    這篇文章主要介紹了Python for循環(huán)搭配else常見問題解決,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02
  • Python Selenium實現(xiàn)無可視化界面過程解析

    Python Selenium實現(xiàn)無可視化界面過程解析

    這篇文章主要介紹了Python Selenium實現(xiàn)無可視化界面過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-08-08
  • 初窺Python門縫了解入門路徑

    初窺Python門縫了解入門路徑

    Python由荷蘭數(shù)學(xué)和計算機科學(xué)研究學(xué)會的Guido van Rossum 于1990 年代初設(shè)計,作為一門叫做ABC語言的替代品。 Python提供了高效的高級數(shù)據(jù)結(jié)構(gòu),還能簡單有效地面向?qū)ο缶幊?/div> 2021-10-10
  • python廣度優(yōu)先搜索得到兩點間最短路徑

    python廣度優(yōu)先搜索得到兩點間最短路徑

    這篇文章主要為大家詳細介紹了python廣度優(yōu)先搜索得到兩點間最短路徑,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • Python基于模塊Paramiko實現(xiàn)SSHv2協(xié)議

    Python基于模塊Paramiko實現(xiàn)SSHv2協(xié)議

    這篇文章主要介紹了Python基于模塊Paramiko實現(xiàn)SSHv2協(xié)議,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04
  • Pandas數(shù)據(jù)清洗與過濾空值技巧

    Pandas數(shù)據(jù)清洗與過濾空值技巧

    在數(shù)據(jù)分析過程中,使用pandas庫進行數(shù)據(jù)清洗和過濾空值是基本而重要的步驟,首先,導(dǎo)入pandas庫并加載數(shù)據(jù),其次,利用isnull()或isna()方法檢查數(shù)據(jù)中的空值,接著,可以使用dropna()方法過濾掉含有空值的行,或針對特定列過濾空值
    2024-09-09

最新評論