pull/350/head
midoks 2 years ago
parent bf064d89f4
commit b4d090021c
  1. 127
      class/core/ssh_terminal.py
  2. 22
      plugins/webssh/js/webssh.js
  3. 8
      route/__init__.py
  4. 35
      route/static/js/term-websocketio.js

@ -54,6 +54,7 @@ class ssh_terminal:
__ssh_list = {}
__ssh_last_request_time = {}
__ssh_connecting = {}
def __init__(self):
ht = threading.Thread(target=self.heartbeat)
@ -164,7 +165,7 @@ class ssh_terminal:
return self.connectBySocket()
def connectLocalSsh(self):
self.createSshInfo()
mw.createSshInfo()
self.__ps = paramiko.SSHClient()
self.__ps.set_missing_host_key_policy(paramiko.AutoAddPolicy())
@ -207,7 +208,6 @@ class ssh_terminal:
term='xterm', width=83, height=21)
ssh.setblocking(0)
self.__ssh_list[self.__sid] = ssh
self.__ssh_last_request_time[self.__sid] = time.time()
mw.writeLog(self.__log_type, '成功登录到SSH服务器 [{}:{}]'.format(
self.__host, self.__port))
self.debug('local-ssh:通道已构建')
@ -329,7 +329,6 @@ class ssh_terminal:
ssh.get_pty(term='xterm', width=100, height=34)
ssh.invoke_shell()
self.__ssh_list[self.__sid] = ssh
self.__ssh_last_request_time[self.__sid] = time.time()
mw.writeLog(self.__log_type, '成功登录到SSH服务器 [{}:{}]'.format(
self.__host, self.__port))
self.debug('通道已构建')
@ -394,61 +393,35 @@ class ssh_terminal:
except Exception as e:
return emit('server_response', {'data': recv})
def getSshDir(self):
if mw.isAppleSystem():
user = mw.execShell(
"who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
return '/Users/' + user + '/.ssh'
return '/root/.ssh'
def createRsa(self):
ssh_dir = self.getSshDir()
ssh_ak = ssh_dir + '/authorized_keys'
if not os.path.exists(ssh_ak):
mw.execShell('touch ' + ssh_ak)
if not os.path.exists(ssh_dir + '/id_rsa.pub') and os.path.exists(ssh_dir + '/id_rsa'):
cmd = 'echo y | ssh-keygen -q -t rsa -P "" -f ' + ssh_dir + '/id_rsa'
mw.execShell(cmd)
else:
cmd = 'ssh-keygen -q -t rsa -P "" -f ' + ssh_dir + '/id_rsa'
mw.execShell(cmd)
cmd = 'cat ' + ssh_dir + '/id_rsa.pub >> ' + ssh_dir + '/authorized_keys'
mw.execShell(cmd)
cmd = 'chmod 600 ' + ssh_dir + '/authorized_keys'
mw.execShell(cmd)
def createSshInfo(self):
ssh_dir = self.getSshDir()
if not os.path.exists(ssh_dir + '/id_rsa') or not os.path.exists(ssh_dir + '/id_rsa.pub'):
self.createRsa()
# 检查是否写入authorized_keys
cmd = "cat " + ssh_dir + "/id_rsa.pub | awk '{print $3}'"
data = mw.execShell(cmd)
if data[0] != "":
cmd = "cat " + ssh_dir + "/authorized_keys | grep " + data[0]
ak_data = mw.execShell(cmd)
if ak_data[0] == "":
cmd = 'cat ' + ssh_dir + '/id_rsa.pub >> ' + ssh_dir + '/authorized_keys'
mw.execShell(cmd)
cmd = 'chmod 600 ' + ssh_dir + '/authorized_keys'
mw.execShell(cmd)
def wsSendConnect(self):
return emit('connect', {'data': 'ok'})
def heartbeat(self):
# limit_cos = 10
while True:
time.sleep(3)
cur_time = time.time()
print("heartbeat:cur_time:", cur_time)
print("heartbeat:__ssh_list:", len(self.__ssh_list))
for x in self.__ssh_list:
for x in list(self.__ssh_list.keys()):
ssh_last_time = self.__ssh_last_request_time[x]
print(x, self.__ssh_list[x])
# self.debug("heartbeat:__ssh_list:" + str(len(self.__ssh_list)))
# if self.__tp and self.__tp.is_active():
# self.__tp.send_ignore()
sid_off_cos = cur_time - ssh_last_time
print("heartbeat off cos :", x, sid_off_cos)
if sid_off_cos > 3:
cur_ssh = self.__ssh_list[x]
if not cur_ssh:
del(self.__ssh_list[x])
del(self.__ssh_last_request_time[x])
continue
# if self.__ps and self.__ps.is_active():
# self.__ps.send_ignore()
if cur_ssh.exit_status_ready():
del(self.__ssh_list[x])
del(self.__ssh_last_request_time[x])
continue
cur_ssh.send("exit\r\n")
del(self.__ssh_list[x])
del(self.__ssh_last_request_time[x])
def run(self, sid, info):
# sid = mw.md5(sid)
@ -456,38 +429,38 @@ class ssh_terminal:
if not self.__sid:
return self.wsSend('WebSocketIO无效')
if self.__connecting and not 'host' in info:
return
result = self.returnMsg(False, '')
self.__ssh_last_request_time[sid] = time.time()
if not sid in self.__ssh_list:
if type(info) == dict and 'host' in info:
self.__connecting = True
result = self.setAttr(info)
self.__connecting = False
if result['status']:
return self.wsSendConnect()
else:
return self.wsSend(result['msg'])
result = self.returnMsg(False, '')
if sid in self.__ssh_list:
if 'resize' in info:
self.resize(info)
result = self.returnMsg(True, '已连接')
print("req.__ssh_list:", str(len(self.__ssh_list)))
print("req.:cmd:", sid, info)
if result['status']:
if type(info) == str:
time.sleep(0.1)
cur_ssh = self.__ssh_list[sid]
if cur_ssh.exit_status_ready():
self.wsSend("logout\r\n")
del(self.__ssh_list[sid])
return
cur_ssh.send(info)
try:
time.sleep(0.005)
recv = cur_ssh.recv(8192)
return self.wsSend(recv)
except Exception as ex:
return self.wsSend('')
else:
return self.wsSend(result['msg'])
print("req.__ssh_list:", len(self.__ssh_list))
print("req.:cmd:", sid, info)
if result['status']:
if type(info) == str:
time.sleep(0.1)
cur_ssh = self.__ssh_list[sid]
if cur_ssh.exit_status_ready():
self.wsSend("logout\r\n")
del(self.__ssh_list[sid])
return
cur_ssh.send(info)
try:
time.sleep(0.005)
recv = cur_ssh.recv(8192)
return self.wsSend(recv)
except Exception as ex:
return self.wsSend('')
else:
return self.wsSend(result['msg'])

@ -78,11 +78,13 @@ $(document).ready(function(){
function webShell_Resize(){
var cur_ssh = $('.term_item_tab .list .active');
var data = $(cur_ssh).data();
var item = host_ssh_list[data.id];
item.term.focus();
item.term.fit();
item.resize({ cols: item.term.cols, rows: item.term.rows});
if (cur_ssh.length > 0){
var data = $(cur_ssh).data();
var item = host_ssh_list[data.id];
item.term.focus();
item.term.fit();
item.resize({ cols: item.term.cols, rows: item.term.rows});
}
}
function webShell_Load(){
@ -174,8 +176,6 @@ function webShell_Load(){
});
webShell_Menu();
// webShell_Resize();
// $('.term_content_tab .term-tool-button').click();
}
@ -284,12 +284,16 @@ function webShell_getCmdList(){
});
}
function Terms_WebSocketIO_Create(ip,random){
function Terms_WebSocketIO_Create(ip, random){
var n = new Terms_WebSocketIO('#'+random, { ssh_info: { host: ip, ps: "22", id: random } });
n.registerCloseCallBack(function(){
webShell_removeTermView(random);
layer.msg('已经关闭【'+ip+'】', { icon: 1, time: 3000 });
});
n.registerConnectedCallBack(function(){
webShell_Resize();
});
return n;
}
@ -315,8 +319,6 @@ function webShell_openTermView(info) {
}
item_list.append('<span class="active item ' + (info.host == '127.0.0.1' ? 'localhost_item' : '') + '" data-host="' + info.host + '" data-id="' + random + '"><i class="icon icon-sucess"></i><div class="content"><span>' + info.ps + '</span></div><span class="icon-trem-close"></span></span>');
host_ssh_list[random] = Terms_WebSocketIO_Create(info.host, random);
webShell_Resize();
}

@ -597,12 +597,4 @@ def webssh(msg):
except Exception as ex:
emit('server_response', {'data': str(ex)})
try:
ssh = paramiko.SSHClient()
# 启动尝试时连接
# connect_ssh()
except Exception as e:
print("本地终端无法使用")
##################### ssh end ###########################

@ -13,7 +13,10 @@ function Terms_WebSocketIO (el, config) {
this.ssh_info = config.ssh_info;
this.term_timer = null;
this.is_connected = false;
this.callback_close = null;
this.callback_connected = null;
this.run();
}
@ -23,10 +26,12 @@ Terms_WebSocketIO.prototype = {
this.callback_close = callback;
},
registerConnectedCallBack:function(callback){
this.callback_connected = callback;
},
connectWs: function (callback) {
if(!this.ws){
this.ws = io.connect();
}
this.ws = io.connect();
},
connectSsh:function(){
@ -35,13 +40,13 @@ Terms_WebSocketIO.prototype = {
},
close:function(){
console.log('try close...');
this.ws.disconnect();
this.ws.close();
},
on_message: function (ws_event) {
this.term.write(ws_event.data);
console.log(ws_event.data);
if (ws_event.data == '\r\n登出\r\n' || ws_event.data == '登出\r\n' ||
ws_event.data == '\r\nlogout\r\n' || ws_event.data == 'logout\r\n'||
ws_event.data == '\r\nexit\r\n' || ws_event.data == 'exit\r\n') {
@ -59,7 +64,11 @@ Terms_WebSocketIO.prototype = {
on_connect:function(ws_event){
// console.log(ws_event);
this.is_connected = true;
if (this.callback_connected){
this.callback_connected();
}
},
on_exit:function(ws_event){
@ -93,16 +102,20 @@ Terms_WebSocketIO.prototype = {
if (this.ws) {
that.send('');
this.term_timer = setInterval(function () {
that.send('');
if (that.is_connected){
that.send('');
}
}, 600);
}
this.term.on('data', function (data) {
try {
that.send(data)
} catch (e) {
that.term.write('\r\n连接丢失,正在尝试重新连接!\r\n');
that.connectSsh();
if (that.is_connected){
try {
that.send(data)
} catch (e) {
that.term.write('\r\n连接丢失,正在尝试重新连接!\r\n');
that.connectSsh();
}
}
});
that.term.write('\r\n请稍等,正在链接中...\r\n');

Loading…
Cancel
Save