├── .gitignore ├── README.md ├── WebsshProject ├── __init__.py ├── routing.py ├── settings.py ├── urls.py └── wsgi.py ├── db.sqlite3 ├── django_webssh ├── __init__.py ├── admin.py ├── apps.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py ├── tools │ ├── __init__.py │ ├── channel │ │ ├── __init__.py │ │ ├── routing.py │ │ └── websocket.py │ ├── ssh.py │ └── tools.py └── views.py ├── manage.py ├── requirements.txt ├── screenshots ├── 0.png ├── image-20200418162650671.png ├── image-20200418162802400.png └── image-20200418163237539.png ├── static ├── bootbox │ └── 5.4.0 │ │ └── bootbox.min.js ├── bootstrap.min.css ├── bootstrap │ └── 3.3.7 │ │ ├── bootstrap.min.css │ │ └── bootstrap.min.js ├── favicon.ico ├── jquery.min.js ├── jquery │ └── 3.4.1 │ │ └── jquery.min.js ├── webssh.js ├── xterm │ ├── 3.14.5 │ │ ├── addons │ │ │ ├── attach.min.js │ │ │ ├── fit.min.js │ │ │ ├── fullscreen.min.css │ │ │ ├── fullscreen.min.js │ │ │ ├── search.min.js │ │ │ ├── terminado.min.js │ │ │ ├── webLinks.min.js │ │ │ └── zmodem.min.js │ │ ├── xterm.min.css │ │ └── xterm.min.js │ ├── 4.4.0 │ │ ├── xterm.css │ │ └── xterm.min.js │ ├── style.css │ ├── terminado.js │ ├── terminado.js.map │ ├── xterm.css │ ├── xterm.js │ └── xterm.js.map └── zmodem │ ├── zmodem.devel.js │ └── zmodem.min.js └── templates └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | __pycache__ 3 | .idea 4 | /django_webssh/migrations/* 5 | !/django_webssh/migrations/__init__.py -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Django结合websocket和paramiko操作Linux 4 | 5 | ## 前言 6 | 7 | > 怎样优雅的运行Linux命令并实时的显示结果,就像Xshell一样呢?那就要属WebSSH了。 8 | > 基于Web的SSH有很多,基于Python的SSH也有很多,这些都是直接通信,中间没有额外管理。但是以Django为中转桥梁结合websocket和paramiko实现的,网上就很少了。下面是我结合网上参考后的实现图和原理讲解: 9 | ## 项目展示 10 | ![image-20200418162650671](https://raw.githubusercontent.com/wanglu58/webssh/master/screenshots/image-20200418162650671.png) 11 | 12 | ![image-20200418162802400](https://raw.githubusercontent.com/wanglu58/webssh/master/screenshots/image-20200418162802400.png) 13 | 14 | ![image-20200418163237539](https://raw.githubusercontent.com/wanglu58/webssh/master/screenshots/image-20200418163237539.png) 15 | 16 | 17 | 18 | ## **所需技术** 19 | 20 | - websocket 目前市面上大多数的 webssh 都是基于 websocket 协议完成的 21 | - django-channels django 的第三方插件, 为 django 提供 websocket 支持 22 | - xterm.js 前端模拟 shell 终端的一个库 23 | - paramiko python 下对 ssh2 封装的一个库 24 | 25 | 26 | 27 | ## 如何将所需技术整合起来 28 | 29 | 1. xterm.js 在浏览器端模拟 shell 终端, 监听用户输入通过 websocket 将用户输入的内容上传到 django 30 | 2. django 接受到用户上传的内容, 将用户在前端页面输入的内容通过 paramiko 建立的 ssh 通道上传到远程服务器执行 31 | 3. paramiko 将远程服务器的处理结果返回给 django 32 | 4. django 将 paramiko 返回的结果通过 websocket 返回给用户 33 | 5. xterm.js 接收 django 返回的数据并将其写入前端页面 34 | 6. lrzsz 基于zmodem协议实现的文件传输 35 | 36 | 37 | 38 | ## 流程图 39 | 40 | ![img](https://raw.githubusercontent.com/wanglu58/webssh/master/screenshots/0.png) 41 | 42 | 整个数据流:用户打开浏览器--》浏览器发送websocket请求给Django建立长连接--》Django与要操作的服务器建立SSH通道,实时的将收到的用户数据发送给SSH后的主机,并将主机执行的结果数据返回给浏览器 43 | 44 | 操作物理机或者虚拟机的时候我们可以使用`Paramiko`模块来建立SSH长连接隧道,`Paramiko`模块建立SSH长连接通道的方法如下: 45 | 46 | ``` 47 | # 实例化SSHClient 48 | ssh_client = paramiko.SSHClient() 49 | # 当远程服务器没有本地主机的密钥时自动添加到本地,这样不用在建立连接的时候输入yes或no进行确认 50 | ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 51 | # 用key进行认证 52 | if ssh_key: 53 | pass 54 | else: 55 | # 用账号密码的方式进行认证 56 | ssh_client.connect(username=user, password=password, hostname=host, port=port, timeout=timeout) 57 | 58 | # 打开ssh通道,建立长连接 59 | transport = ssh_client.get_transport() 60 | self.channel = transport.open_session() 61 | # 获取ssh通道,并设置term和终端大小 62 | self.channel.get_pty(term=term, width=pty_width, height=pty_height) 63 | # 激活终端,正常登陆 64 | self.channel.invoke_shell() 65 | # 一开始展示Linux欢迎相关内容,后面不进入此方法 66 | for i in range(2): 67 | recv = self.channel.recv(1024).decode('utf-8') 68 | self.message['status'] = 0 69 | self.message['message'] = recv 70 | message = json.dumps(self.message) 71 | self.websocker.send(message) 72 | self.res += recv 73 | 74 | # 创建3个线程将服务器返回的数据发送到django websocket(1个线程都可以) 75 | Thread(target=self.websocket_to_django).start() 76 | # Thread(target=self.websocket_to_django).start() 77 | # Thread(target=self.websocket_to_django).start() 78 | ``` 79 | 80 | 81 | 82 | 连接建立,可以通过如下方法给SSH通道接收数据和发送数据: 83 | 84 | ``` 85 | self.channel.recv(nbytes) 86 | self.channel.send(data) 87 | ``` 88 | 89 | 90 | 91 | 当然SSH返回的数据也可以通过如下方法持续的输出给Websocket: 92 | 93 | ``` 94 | while not self.channel.exit_status_ready(): 95 | data = self.channel.recv(40960) 96 | if not len(data): 97 | return 98 | 99 | # SSH返回的数据需要转码为utf-8,否则json序列化会失败 100 | data = data.decode('utf-8') 101 | self.message['status'] = 0 102 | self.message['message'] = data 103 | self.res += data 104 | message = json.dumps(self.message) 105 | self.websocker.send(message) 106 | ``` 107 | 108 | 109 | 110 | 有了这些信息,实现WebSSH浏览器操作物理机或者虚拟机就不算困难了。 111 | 112 | ## WebSSH动态调整终端窗口大小 113 | 114 | 如果我中途调整了浏览器的大小,显示就乱了,这该怎么办? 好办, 终端窗口的大小需要浏览器和后端返回的Terminal大小保持一致,单单调整页面窗口大小或者后端返回的Terminal窗口大小都是不行的,那么从这两个方向来说明该如何动态调整窗口的大小 。 115 | 116 | 首先`Paramiko`模块建立的SSH通道可以通过`resize_pty`来动态改变返回Terminal窗口的大小,使用方法如下: 117 | 118 | ``` 119 | def resize_pty(self, cols, rows): 120 | self.ssh_channel.resize_pty(width=cols, height=rows) 121 | ``` 122 | 123 | 然后Django的Channels每次接收到前端发过来的数据时,判断一下窗口是否有变化,如果有变化则调用上边的方法动态改变Terminal输出窗口的大小 124 | 125 | 我在实现时会给传过来的数据加个status,如果status不是0,则调用resize_pty的方法动态调整窗口大小,否则就正常调用执行命令的方法,代码如下: 126 | 127 | ``` 128 | def receive(self, text_data=None, bytes_data=None): 129 | if text_data is None: 130 | self.ssh.django_bytes_to_ssh(bytes_data) 131 | else: 132 | data = json.loads(text_data) 133 | if type(data) == dict: 134 | status = data['status'] 135 | if status == 0: 136 | data = data['data'] 137 | 138 | self.ssh.shell(data) 139 | else: 140 | cols = data['cols'] 141 | rows = data['rows'] 142 | self.ssh.resize_pty(cols=cols, rows=rows) 143 | ``` 144 | 145 | ## WebSSH通过lrzsz上传下载文件 146 | 147 | 当使用Xshell或者SecureCRT终端工具时,我的所有文件传输工作都是通过`lrzsz`来完成的,主要是因为其简单方便,不需要额外打开sftp之类的工具,通过命令就可轻松搞定,在用了WebSSH之后一直在想,这么便捷的操作WebSSH能够实现吗? 148 | 149 | 答案是肯定的,能实现!这要感谢这个古老的文件传输协议:`zmodem` 150 | 151 | zmodem采用串流的方式传输文件,是xmodem和ymodem协议的改良进化版,具有传输速度快,支持断点续传、支持完整性校验等优点,成为目前最流行的文件传输协议之一,也被众多终端所支持,例如Xshell、SecureCRT、item2等 152 | 153 | 优点之外,zmodem也有一定的局限性,其中之一便是只能可靠地传输大小**不超过4GB**的文件,但对于大部分场景下已够用,超大文件的传输一般也会寻求其他的传输方式 154 | 155 | lrzsz就是基于zmodem协议实现的文件传输,linux下使用非常方便,只需要一个简单的命令就可以安装,例如centos系统安装方式如下: 156 | 157 | ``` 158 | yum install lrzsz 159 | ``` 160 | 161 | 安装完成后就可以通过`rz`命令上传文件,或者`sz`命令下载文件了,这么说上传或下载其实不是很准确,在zmodem协议中,使用receive接收和send发送来解释更为准确,无论是receive还是send都是由**服务端来发起**的 162 | 163 | `rz`的意思为recevie zmodem,服务端来接收数据,对于客户端来说就是上传 164 | 165 | `sz`的意思是send zmodem,服务端来发送数据,对于客户端来说就是下载 166 | 167 | 文件的传输需要服务端和客户端都支持zmodem协议,服务端通过安装lrzsz实现了对zmodem协议的支持,Xshell和SecureCRT也支持zmodem协议,所以他们能通过rz或sz命令实现文件的上传和下载,那么Web浏览器要如何支持zmodem协议呢? 168 | 169 | 我们所使用的终端工具xterm.js在3.x版本提供过zmodem扩展插件, 但很可惜 xterm v4 版本后去掉了 zmodem 插件,只能直接使用 zmodem.js 实现,但是不知道什么原因,登陆 webssh 后,第一次输出命令回车后会卡顿一下才出数据,v3.14.5 就不会卡顿,v3.14.5还可以也可以直接使用 zmodem.js,所以这里使用 v3.14.5,终端功能方面v3 和 v4 我没发现有什么多大的差别。zmodem调用系统rzsz命令实现文件上传下载了 170 | 171 | 需要注意的是zmodem是个二进制协议,只支持二进制流,所以通过websocket传输的数据必须是二进制的,在django的channel中可以通过指定发送消息的类型为`bytes_data`来实现websocket传输二进制数据,这是后端实现的核心: 172 | 173 | ``` 174 | websocket.send(bytes_data=data) 175 | ``` 176 | 177 | 又深入研究了zmodem协议是如何实现识别的,发现了zmodem的实现原理 178 | 179 | 在服务器上执行sz命令后,会先输出`b'**\x18B0800000000022d\r\x8a'`这样的内容,标识文件下载开始,当文件下载结束后会输出`b'OO'`,取这两个特殊标记之间的二进制流组合成文件,就是要下载的完整文件 180 | 181 | rz命令类似,会在开始时输出`b'rz waiting to receive.**\x18B0100000023be50\r\x8a'`标记, 知道了这个规则, 就好区分用户上传和下载文件了: 182 | 183 | ``` 184 | zmodemszstart = b'rz\r**\x18B00000000000000\r\x8a' 185 | zmodemszend = b'**\x18B0800000000022d\r\x8a' 186 | zmodemrzstart = b'rz waiting to receive.**\x18B0100000023be50\r\x8a' 187 | zmodemrzend = b'**\x18B0800000000022d\r\x8a' 188 | zmodemcancel = b'\x18\x18\x18\x18\x18\x08\x08\x08\x08\x08' 189 | 190 | while not self.channel.exit_status_ready(): 191 | if self.zmodemOO: 192 | # 文件开始下载 193 | self.zmodemOO = False 194 | data = self.channel.recv(2) 195 | if not len(data): 196 | return 197 | # 文件下载结束 198 | if data == b'OO': 199 | self.websocker.send(bytes_data=data) 200 | continue 201 | else: 202 | data = data + self.channel.recv(40960) 203 | else: 204 | data = self.channel.recv(40960) 205 | if not len(data): 206 | return 207 | 208 | if self.zmodem: 209 | if zmodemszend in data or zmodemrzend in data: 210 | self.zmodem = False 211 | if zmodemszend in data: 212 | self.zmodemOO = True 213 | if zmodemcancel in data: 214 | self.zmodem = False 215 | self.websocker.send(bytes_data=data) 216 | else: 217 | if zmodemszstart in data or zmodemrzstart in data: 218 | self.zmodem = True 219 | self.websocker.send(bytes_data=data) 220 | else: 221 | # SSH返回的数据需要转码为utf-8,否则json序列化会失败 222 | data = data.decode('utf-8') 223 | self.message['status'] = 0 224 | self.message['message'] = data 225 | self.res += data 226 | message = json.dumps(self.message) 227 | self.websocker.send(message) 228 | except: 229 | self.close() 230 | ``` 231 | 232 | ## 总结 233 | 234 | 完整代码,我已经放到GitHub上了,忘记了可以参考! 235 | 236 | -------------------------------------------------------------------------------- /WebsshProject/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglu58/webssh/b7d579581cf25356474872e648ad83768dbc60a7/WebsshProject/__init__.py -------------------------------------------------------------------------------- /WebsshProject/routing.py: -------------------------------------------------------------------------------- 1 | from channels.auth import AuthMiddlewareStack 2 | from channels.routing import ProtocolTypeRouter, URLRouter 3 | from django_webssh.tools.channel import routing 4 | 5 | application = ProtocolTypeRouter({ 6 | 'websocket': AuthMiddlewareStack( 7 | URLRouter( 8 | routing.websocket_urlpatterns, 9 | ) 10 | ), 11 | }) -------------------------------------------------------------------------------- /WebsshProject/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for WebsshProject project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.0.13. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | TMP_DIR = os.path.join(BASE_DIR, 'tmp') 18 | 19 | if not os.path.isdir(TMP_DIR): 20 | os.makedirs(TMP_DIR) 21 | 22 | # Quick-start development settings - unsuitable for production 23 | # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ 24 | 25 | # SECURITY WARNING: keep the secret key used in production secret! 26 | SECRET_KEY = 'atouu=br3bf1!&_fq5503%6lcq3bq1_fld4!5q-zxf!qg-&)mr' 27 | 28 | # SECURITY WARNING: don't run with debug turned on in production! 29 | DEBUG = True 30 | 31 | ALLOWED_HOSTS = ['*'] 32 | 33 | 34 | # Application definition 35 | 36 | INSTALLED_APPS = [ 37 | 'django.contrib.admin', 38 | 'django.contrib.auth', 39 | 'django.contrib.contenttypes', 40 | 'django.contrib.sessions', 41 | 'django.contrib.messages', 42 | 'django.contrib.staticfiles', 43 | 'django_webssh', 44 | 'channels', 45 | ] 46 | 47 | MIDDLEWARE = [ 48 | 'django.middleware.security.SecurityMiddleware', 49 | 'django.contrib.sessions.middleware.SessionMiddleware', 50 | 'django.middleware.common.CommonMiddleware', 51 | 'django.middleware.csrf.CsrfViewMiddleware', 52 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 53 | 'django.contrib.messages.middleware.MessageMiddleware', 54 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 55 | ] 56 | 57 | ROOT_URLCONF = 'WebsshProject.urls' 58 | 59 | TEMPLATES = [ 60 | { 61 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 62 | 'DIRS': [os.path.join(BASE_DIR, 'templates')] 63 | , 64 | 'APP_DIRS': True, 65 | 'OPTIONS': { 66 | 'context_processors': [ 67 | 'django.template.context_processors.debug', 68 | 'django.template.context_processors.request', 69 | 'django.contrib.auth.context_processors.auth', 70 | 'django.contrib.messages.context_processors.messages', 71 | ], 72 | }, 73 | }, 74 | ] 75 | 76 | # WSGI_APPLICATION = 'WebsshProject.wsgi.application' 77 | ASGI_APPLICATION = 'WebsshProject.routing.application' 78 | 79 | 80 | # Database 81 | # https://docs.djangoproject.com/en/2.0/ref/settings/#databases 82 | 83 | DATABASES = { 84 | 'default': { 85 | 'ENGINE': 'django.db.backends.sqlite3', 86 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 87 | } 88 | } 89 | 90 | 91 | # Password validation 92 | # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators 93 | 94 | AUTH_PASSWORD_VALIDATORS = [ 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 103 | }, 104 | { 105 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 106 | }, 107 | ] 108 | 109 | 110 | # Internationalization 111 | # https://docs.djangoproject.com/en/2.0/topics/i18n/ 112 | 113 | LANGUAGE_CODE = 'en-us' 114 | 115 | TIME_ZONE = 'UTC' 116 | 117 | USE_I18N = True 118 | 119 | USE_L10N = True 120 | 121 | USE_TZ = True 122 | 123 | 124 | # Static files (CSS, JavaScript, Images) 125 | # https://docs.djangoproject.com/en/2.0/howto/static-files/ 126 | 127 | STATIC_URL = '/static/' 128 | STATICFILES_DIRS = [ 129 | os.path.join(BASE_DIR, 'static') 130 | ] -------------------------------------------------------------------------------- /WebsshProject/urls.py: -------------------------------------------------------------------------------- 1 | """WebsshProject URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from django_webssh import views 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | path('', views.index), 23 | path('upload_ssh_key/', views.upload_ssh_key), 24 | ] 25 | -------------------------------------------------------------------------------- /WebsshProject/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for WebsshProject project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WebsshProject.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglu58/webssh/b7d579581cf25356474872e648ad83768dbc60a7/db.sqlite3 -------------------------------------------------------------------------------- /django_webssh/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglu58/webssh/b7d579581cf25356474872e648ad83768dbc60a7/django_webssh/__init__.py -------------------------------------------------------------------------------- /django_webssh/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /django_webssh/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class DjangoWebsshConfig(AppConfig): 5 | name = 'django_webssh' 6 | -------------------------------------------------------------------------------- /django_webssh/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglu58/webssh/b7d579581cf25356474872e648ad83768dbc60a7/django_webssh/migrations/__init__.py -------------------------------------------------------------------------------- /django_webssh/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /django_webssh/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | 5 | import paramiko 6 | 7 | def main(): 8 | sshClient = paramiko.SSHClient() 9 | sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 10 | sshClient.connect(hostname = "localhost", port = 22, username = "root", password = "password") 11 | 12 | stdin, stdout, stderr= sshClient.exec_command('df -h ')# stdout 为正确输出,stderr为错误输出,同时是有1个变量有值 13 | print(stdout.read().decode('utf-8')) 14 | 15 | sshClient.close() 16 | 17 | 18 | if __name__ == '__main__': 19 | main() -------------------------------------------------------------------------------- /django_webssh/tools/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglu58/webssh/b7d579581cf25356474872e648ad83768dbc60a7/django_webssh/tools/__init__.py -------------------------------------------------------------------------------- /django_webssh/tools/channel/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglu58/webssh/b7d579581cf25356474872e648ad83768dbc60a7/django_webssh/tools/channel/__init__.py -------------------------------------------------------------------------------- /django_webssh/tools/channel/routing.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from django_webssh.tools.channel import websocket 3 | 4 | 5 | websocket_urlpatterns = [ 6 | path('webssh/', websocket.WebSSH), 7 | ] -------------------------------------------------------------------------------- /django_webssh/tools/channel/websocket.py: -------------------------------------------------------------------------------- 1 | from channels.generic.websocket import WebsocketConsumer 2 | from django_webssh.tools.ssh import SSH 3 | from django.http.request import QueryDict 4 | from django.utils.six import StringIO 5 | from WebsshProject.settings import TMP_DIR 6 | import os 7 | import json 8 | import base64 9 | import re 10 | 11 | 12 | class WebSSH(WebsocketConsumer): 13 | message = {'status': 0, 'message': None} 14 | """ 15 | status: 16 | 0: ssh 连接正常, websocket 正常 17 | 1: 发生未知错误, 关闭 ssh 和 websocket 连接 18 | 19 | message: 20 | status 为 1 时, message 为具体的错误信息 21 | status 为 0 时, message 为 ssh 返回的数据, 前端页面将获取 ssh 返回的数据并写入终端页面 22 | """ 23 | 24 | def connect(self): 25 | """ 26 | 打开 websocket 连接, 通过前端传入的参数尝试连接 ssh 主机 27 | :return: 28 | """ 29 | self.accept() 30 | query_string = self.scope.get('query_string') 31 | ssh_args = QueryDict(query_string=query_string, encoding='utf-8') 32 | 33 | width = ssh_args.get('width') 34 | height = ssh_args.get('height') 35 | port = ssh_args.get('port') 36 | 37 | width = int(width) 38 | height = int(height) 39 | port = int(port) 40 | 41 | auth = ssh_args.get('auth') 42 | ssh_key_name = ssh_args.get('ssh_key') 43 | passwd = ssh_args.get('password') 44 | 45 | host = ssh_args.get('host') 46 | user = ssh_args.get('user') 47 | 48 | if passwd: 49 | passwd = base64.b64decode(passwd).decode('utf-8') 50 | else: 51 | passwd = None 52 | 53 | self.ssh = SSH(websocker=self, message=self.message) 54 | 55 | ssh_connect_dict = { 56 | 'host': host, 57 | 'user': user, 58 | 'port': port, 59 | 'timeout': 60, 60 | 'pty_width': width, 61 | 'pty_height': height, 62 | 'password': passwd 63 | } 64 | 65 | if auth == 'key': 66 | ssh_key_file = os.path.join(TMP_DIR, ssh_key_name) 67 | with open(ssh_key_file, 'r') as f: 68 | ssh_key = f.read() 69 | 70 | string_io = StringIO() 71 | string_io.write(ssh_key) 72 | string_io.flush() 73 | string_io.seek(0) 74 | ssh_connect_dict['ssh_key'] = string_io 75 | 76 | os.remove(ssh_key_file) 77 | 78 | self.ssh.connect(**ssh_connect_dict) 79 | 80 | def disconnect(self, close_code): 81 | try: 82 | if close_code == 3001: 83 | pass 84 | else: 85 | self.ssh.close() 86 | except: 87 | pass 88 | finally: 89 | # 过滤点结果中的颜色字符 90 | # res = re.sub('(\[\d{2};\d{2}m|\[0m)', '', self.ssh.res) 91 | print('命令: ') 92 | print(self.ssh.cmd) 93 | # print('结果: ') 94 | # print(res) 95 | pass 96 | 97 | def receive(self, text_data=None, bytes_data=None): 98 | if text_data is None: 99 | self.ssh.django_bytes_to_ssh(bytes_data) 100 | else: 101 | data = json.loads(text_data) 102 | if type(data) == dict: 103 | status = data['status'] 104 | if status == 0: 105 | data = data['data'] 106 | 107 | self.ssh.shell(data) 108 | else: 109 | cols = data['cols'] 110 | rows = data['rows'] 111 | self.ssh.resize_pty(cols=cols, rows=rows) 112 | -------------------------------------------------------------------------------- /django_webssh/tools/ssh.py: -------------------------------------------------------------------------------- 1 | from pprint import pprint 2 | import paramiko 3 | import threading 4 | from threading import Thread 5 | from django_webssh.tools.tools import get_key_obj 6 | import traceback 7 | import socket 8 | import json 9 | 10 | zmodemszstart = b'rz\r**\x18B00000000000000\r\x8a' 11 | zmodemszend = b'**\x18B0800000000022d\r\x8a' 12 | zmodemrzstart = b'rz waiting to receive.**\x18B0100000023be50\r\x8a' 13 | zmodemrzend = b'**\x18B0800000000022d\r\x8a' 14 | zmodemcancel = b'\x18\x18\x18\x18\x18\x08\x08\x08\x08\x08' 15 | 16 | 17 | class SSH: 18 | def __init__(self, websocker, message): 19 | self.websocker = websocker 20 | self.message = message 21 | self.cmd = '' 22 | self.res = '' 23 | self.zmodem = False 24 | self.zmodemOO = False 25 | 26 | # term 可以使用 ansi, linux, vt100, xterm, dumb,除了 dumb外其他都有颜色显示 27 | def connect(self, host, user, password=None, ssh_key=None, port=22, timeout=None, 28 | term='ansi', pty_width=80, pty_height=24): 29 | try: 30 | # 实例化SSHClient 31 | ssh_client = paramiko.SSHClient() 32 | # 当远程服务器没有本地主机的密钥时自动添加到本地,这样不用在建立连接的时候输入yes或no进行确认 33 | ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 34 | # 用key进行认证 35 | if ssh_key: 36 | key = get_key_obj(paramiko.RSAKey, pkey_obj=ssh_key, password=password) or \ 37 | get_key_obj(paramiko.DSSKey, pkey_obj=ssh_key, password=password) or \ 38 | get_key_obj(paramiko.ECDSAKey, pkey_obj=ssh_key, password=password) or \ 39 | get_key_obj(paramiko.Ed25519Key, pkey_obj=ssh_key, password=password) 40 | 41 | ssh_client.connect(username=user, hostname=host, port=port, pkey=key, timeout=timeout) 42 | else: 43 | # 用账号密码的方式进行认证 44 | ssh_client.connect(username=user, password=password, hostname=host, port=port, timeout=timeout) 45 | 46 | # 打开ssh通道,建立长连接 47 | transport = ssh_client.get_transport() 48 | self.channel = transport.open_session() 49 | # 获取ssh通道,并设置term和终端大小 50 | self.channel.get_pty(term=term, width=pty_width, height=pty_height) 51 | # 激活终端,正常登陆 52 | self.channel.invoke_shell() 53 | # 一开始展示Linux欢迎相关内容,后面不进入此方法 54 | for i in range(2): 55 | recv = self.channel.recv(1024).decode('utf-8') 56 | self.message['status'] = 0 57 | self.message['message'] = recv 58 | message = json.dumps(self.message) 59 | self.websocker.send(message) 60 | self.res += recv 61 | 62 | # 创建3个线程将服务器返回的数据发送到django websocket(1个线程都可以) 63 | Thread(target=self.websocket_to_django).start() 64 | # Thread(target=self.websocket_to_django).start() 65 | # Thread(target=self.websocket_to_django).start() 66 | except: 67 | self.message['status'] = 2 68 | self.message['message'] = 'connection faild...' 69 | message = json.dumps(self.message) 70 | self.websocker.send(message) 71 | self.websocker.close(3001) 72 | 73 | def resize_pty(self, cols, rows): 74 | self.channel.resize_pty(width=cols, height=rows) 75 | 76 | def django_to_ssh(self, data): 77 | try: 78 | self.channel.send(data) 79 | if data == '\r': 80 | data = '\n' 81 | self.cmd += data 82 | except Exception: 83 | self.close() 84 | 85 | def django_bytes_to_ssh(self, data): 86 | try: 87 | self.channel.send(data) 88 | except Exception: 89 | self.close() 90 | 91 | def websocket_to_django(self): 92 | try: 93 | while not self.channel.exit_status_ready(): 94 | if self.zmodemOO: 95 | # 文件开始下载 96 | self.zmodemOO = False 97 | data = self.channel.recv(2) 98 | if not len(data): 99 | return 100 | # 文件下载结束 101 | if data == b'OO': 102 | self.websocker.send(bytes_data=data) 103 | continue 104 | else: 105 | data = data + self.channel.recv(40960) 106 | else: 107 | data = self.channel.recv(40960) 108 | if not len(data): 109 | return 110 | 111 | if self.zmodem: 112 | if zmodemszend in data or zmodemrzend in data: 113 | self.zmodem = False 114 | if zmodemszend in data: 115 | self.zmodemOO = True 116 | if zmodemcancel in data: 117 | self.zmodem = False 118 | self.websocker.send(bytes_data=data) 119 | else: 120 | if zmodemszstart in data or zmodemrzstart in data: 121 | self.zmodem = True 122 | self.websocker.send(bytes_data=data) 123 | else: 124 | # SSH返回的数据需要转码为utf-8,否则json序列化会失败 125 | data = data.decode('utf-8') 126 | self.message['status'] = 0 127 | self.message['message'] = data 128 | self.res += data 129 | message = json.dumps(self.message) 130 | self.websocker.send(message) 131 | except: 132 | self.close() 133 | 134 | def close(self): 135 | self.message['status'] = 1 136 | self.message['message'] = 'connection closed...' 137 | message = json.dumps(self.message) 138 | self.websocker.send(message) 139 | self.websocker.close() 140 | self.channel.close() 141 | 142 | def shell(self, data): 143 | # 原作者使用创建线程的方式发送数据到ssh,每次发送都是一个字符,可以不用线程 144 | # 直接调用函数性能更好 145 | # Thread(target=self.django_to_ssh, args=(data,)).start() 146 | self.django_to_ssh(data) 147 | 148 | # 原作者将发送数据到django websocket的线程创建函数如果写到这,会导致每在客户端输入一个字符就创建一个线程 149 | # 最终可能导致线程创建太多,故将其写到 connect 函数中 150 | # Thread(target=self.websocket_to_django).start() 151 | -------------------------------------------------------------------------------- /django_webssh/tools/tools.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author : HuYuan 4 | # @File : tools.py 5 | 6 | import time 7 | import random 8 | import hashlib 9 | 10 | def get_key_obj(pkeyobj, pkey_file=None, pkey_obj=None, password=None): 11 | if pkey_file: 12 | with open(pkey_file) as fo: 13 | try: 14 | pkey = pkeyobj.from_private_key(fo, password=password) 15 | return pkey 16 | except: 17 | pass 18 | else: 19 | try: 20 | pkey = pkeyobj.from_private_key(pkey_obj, password=password) 21 | return pkey 22 | except: 23 | pkey_obj.seek(0) 24 | 25 | def unique(): 26 | ctime = str(time.time()) 27 | salt = str(random.random()) 28 | m = hashlib.md5(bytes(salt, encoding='utf-8')) 29 | m.update(bytes(ctime, encoding='utf-8')) 30 | return m.hexdigest() -------------------------------------------------------------------------------- /django_webssh/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, HttpResponse 2 | import os 3 | from WebsshProject.settings import TMP_DIR 4 | from django_webssh.tools.tools import unique 5 | # Create your views here. 6 | 7 | 8 | def index(request): 9 | return render(request, 'index.html') 10 | 11 | 12 | def upload_ssh_key(request): 13 | if request.method == 'POST': 14 | pkey = request.FILES.get('pkey') 15 | ssh_key = pkey.read().decode('utf-8') 16 | 17 | while True: 18 | filename = unique() 19 | ssh_key_path = os.path.join(TMP_DIR, filename) 20 | if not os.path.isfile(ssh_key_path): 21 | with open(ssh_key_path, 'w') as f: 22 | f.write(ssh_key) 23 | break 24 | else: 25 | continue 26 | 27 | return HttpResponse(filename) -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WebsshProject.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aioredis==1.0.0 2 | asgiref==2.3.2 3 | async-timeout==3.0.1 4 | attrs==19.3.0 5 | autobahn==20.4.2 6 | Automat==20.2.0 7 | bcrypt==3.1.7 8 | cffi==1.14.0 9 | channels==2.0.2 10 | channels-redis==2.1.1 11 | constantly==15.1.0 12 | cryptography==2.9 13 | daphne==2.2.5 14 | Django==2.0.13 15 | hiredis==1.0.1 16 | hyperlink==19.0.0 17 | idna==2.9 18 | incremental==17.5.0 19 | msgpack==0.5.6 20 | paramiko==2.7.1 21 | pyasn1==0.4.8 22 | pyasn1-modules==0.2.8 23 | pycparser==2.20 24 | pycryptodomex==3.9.7 25 | PyHamcrest==2.0.2 26 | PyNaCl==1.3.0 27 | pyOpenSSL==19.1.0 28 | pytz==2019.3 29 | service-identity==18.1.0 30 | six==1.14.0 31 | sqlparse==0.3.1 32 | Twisted==20.3.0 33 | txaio==20.4.1 34 | zope.interface==5.1.0 35 | -------------------------------------------------------------------------------- /screenshots/0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglu58/webssh/b7d579581cf25356474872e648ad83768dbc60a7/screenshots/0.png -------------------------------------------------------------------------------- /screenshots/image-20200418162650671.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglu58/webssh/b7d579581cf25356474872e648ad83768dbc60a7/screenshots/image-20200418162650671.png -------------------------------------------------------------------------------- /screenshots/image-20200418162802400.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglu58/webssh/b7d579581cf25356474872e648ad83768dbc60a7/screenshots/image-20200418162802400.png -------------------------------------------------------------------------------- /screenshots/image-20200418163237539.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wanglu58/webssh/b7d579581cf25356474872e648ad83768dbc60a7/screenshots/image-20200418163237539.png -------------------------------------------------------------------------------- /static/bootbox/5.4.0/bootbox.min.js: -------------------------------------------------------------------------------- 1 | !function(t,e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof exports?module.exports=e(require("jquery")):t.bootbox=e(t.jQuery)}(this,function e(p,u){"use strict";var r,n,i,l;Object.keys||(Object.keys=(r=Object.prototype.hasOwnProperty,n=!{toString:null}.propertyIsEnumerable("toString"),l=(i=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(t){if("function"!=typeof t&&("object"!=typeof t||null===t))throw new TypeError("Object.keys called on non-object");var e,o,a=[];for(e in t)r.call(t,e)&&a.push(e);if(n)for(o=0;o