-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.py
117 lines (104 loc) · 3.62 KB
/
websocket.py
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/12/29 17:24
# @Author : Alvin
# @File : websocket.py
from channels.generic.websocket import WebsocketConsumer
from ssh import SSH
from django.http.request import QueryDict
from assets import models
from django.utils.six import StringIO
import json
# import base64
from django.shortcuts import get_object_or_404
class WebSSH(WebsocketConsumer):
message = {'status': 0, 'message': None}
"""
status:
0: ssh 连接正常, websocket 正常
1: 发生未知错误, 关闭 ssh 和 websocket 连接
message:
status 为 1 时, message 为具体的错误信息
status 为 0 时, message 为 ssh 返回的数据, 前端页面将获取 ssh 返回的数据并写入终端页面
"""
# status = {'code': 1001, 'error': ''}
def connect(self):
try:
self.accept()
query_string = self.scope['query_string']
connect_argv = QueryDict(query_string=query_string, encoding='utf-8')
server_id = connect_argv.get('server_id')
user = connect_argv.get('user')
width = connect_argv.get('width')
height = connect_argv.get('height')
width = int(width)
height = int(height)
connect_info = get_object_or_404(models.Server, id=server_id)
host = connect_info.alias
port = connect_info.ssh_port
# auth = ''
# pkey = ''
# connect_info.delete()
if user == str("root"):
# # password = base64.b64decode(pwd).decode('utf-8')
password = connect_info.ssh_user_root_password
else:
password = connect_info.ssh_user_other_password
self.ssh = SSH(websocker=self, message=self.message)
# self.ssh = SSH(websocker=self)
self.ssh.connect(
host=host,
user=user,
password=password,
port=port,
pty_width=width,
pty_height=height
)
# if auth == 'key':
# pkey = pkey
# obj = StringIO()
# obj.write(pkey)
# obj.flush()
# obj.seek(0)
# self.pkey = obj
#
# self.ssh.connect(
# host=host,
# user=user,
# password=password,
# pkey=self.pkey,
# port=port,
# pty_width=width,
# pty_height=height
# )
# else:
# self.ssh.connect(
# host=host,
# user=user,
# password=password,
# port=port,
# pty_width=width,
# pty_height=height
# )
except Exception as e:
self.message['status'] = 1
self.message['message'] = str(e)
message = json.dumps(self.message)
self.send(message)
self.close()
def disconnect(self, close_code):
try:
self.ssh.close()
except:
pass
def receive(self, text_data=None, bytes_data=None):
data = json.loads(text_data)
if type(data) == dict:
status = data['status']
if status == 0:
data = data['data']
self.ssh.shell(data)
else:
cols = data['cols']
rows = data['rows']
self.ssh.resize_pty(cols=cols, rows=rows)