平台
Web前端:Vue.js
Web后端:tornado
WebSocket插件:Xtermjs
环境配置
前端配置——安装xterm
1 | npm install --save xterm |
xterm.js
的插件,使终端的尺寸适合包含元素。1
npm install --save xterm-addon-fit
xterm.js
的附加组件,用于附加到Web Socket
。1
npm install --save xterm-addon-attach
附:建议版本:1
2
3"xterm": "^3.1.0",
"xterm-addon-attach": "^0.6.0",
"xterm-addon-fit": "^0.5.0"
在main.js
加入import 'xterm/dist/xterm.css'
,否则显示有问题。
后端配置——安装tornado
1 | pip install tornado==4.5.3 |
代码实现
后端服务器实现
后端启动代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71# -*- coding: utf-8 -*-
import tornado
import tornado.websocket
import paramiko
import threading
import time
# 配置服务器信息
HOSTS = "192.168.64.131"
PORT = 22
USERNAME = "cxx"
PASSWORD = " "
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)
self.chan.write_message(data)
except Exception as ex:
# 注释掉print,否则会报错,原因:库版本不对
# print(str(ex))
pass
self.chan.sshclient.close()
return False
class webSSHServer(tornado.websocket.WebSocketHandler):
def open(self):
self.sshclient = paramiko.SSHClient()
self.sshclient.load_system_host_keys()
self.sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.sshclient.connect(HOSTS, PORT, USERNAME, PASSWORD)
self.chan = self.sshclient.invoke_shell(term='xterm')
self.chan.settimeout(0)
t1 = MyThread(999, self)
t1.setDaemon(True)
t1.start()
def on_message(self, message):
try:
self.chan.send(message)
except Exception as ex:
print(str(ex))
def on_close(self):
self.sshclient.close()
def check_origin(self, origin):
# 允许跨域访问
return True
if __name__ == '__main__':
# 定义路由
app = tornado.web.Application([
(r"/terminals/", webSSHServer),
],
debug=True
)
# 启动服务器
http_server = tornado.httpserver.HTTPServer(app)
# 监听的端口号
http_server.listen(3000)
tornado.ioloop.IOLoop.current().start()
前端实现
1 | import { Terminal } from 'xterm' |
Vue模块
1 | <template> |
附:vue-prism-editor
安装
1 | npm install vue-prism-editor |
实现
1 | <template> |