From 55503c89e9390d1348fbaa99eb8025a2b470cb35 Mon Sep 17 00:00:00 2001 From: kelianchun_miller <360271747@qq.com> Date: Sun, 22 Nov 2015 19:15:58 +0800 Subject: [PATCH 1/6] update connect.py --- connect.py | 80 ++++++++++++++++-------------------------------------- 1 file changed, 23 insertions(+), 57 deletions(-) diff --git a/connect.py b/connect.py index 05d84dd8f..b02c6428b 100644 --- a/connect.py +++ b/connect.py @@ -107,87 +107,60 @@ class Tty(object): result_command = '' #最后的结果 backspace_num = 0 #光标移动的个数 - backspace_list = [] reach_backspace_flag = False #没有检测到光标键则为true - reach_backspace_second_flag = False - pattern_list = [] pattern_str='' while str_r: - tmp = re.match(r'\s*\w+\s*', str_r) #获取字符串,其它特殊字符匹配暂时还不知道。。 + tmp = re.match(r'\s*\w+\s*', str_r) if tmp: if reach_backspace_flag : - if not reach_backspace_second_flag: - pattern_str +=str(tmp.group(0)) - else: - pattern_list.append(pattern_str) - pattern_str=str(tmp.group(0)) - reach_backspace_second_flag=False + pattern_str +=str(tmp.group(0)) str_r = str_r[len(str(tmp.group(0))):] continue else: result_command += str(tmp.group(0)) str_r = str_r[len(str(tmp.group(0))):] continue - - tmp = re.match(r'\x1b\[K[\x08]*', str_r) #遇到删除确认符,确定删除数据 + + tmp = re.match(r'\x1b\[K[\x08]*', str_r) if tmp: - for x in backspace_list: - backspace_num += int(x) if backspace_num > 0: if backspace_num > len(result_command) : - result_command += ''.join(pattern_list) result_command += pattern_str result_command = result_command[0:-backspace_num] else: result_command = result_command[0:-backspace_num] - result_command += ''.join(pattern_list) result_command += pattern_str del_len = len(str(tmp.group(0)))-3 if del_len > 0: result_command = result_command[0:-del_len] reach_backspace_flag = False - reach_backspace_second_flag =False backspace_num =0 - del pattern_list[:] - del backspace_list[:] pattern_str='' str_r = str_r[len(str(tmp.group(0))):] continue - - tmp = re.match(r'\x08+', str_r) #将遇到的退格数字存放到队列中 + + tmp = re.match(r'\x08+', str_r) if tmp: - if reach_backspace_flag: - reach_backspace_second_flag = True - else: - reach_backspace_flag = True str_r = str_r[len(str(tmp.group(0))):] - if len(str_r) != 0: #如果退格键在最后,则放弃 - backspace_list.append(len(str(tmp.group(0)))) - continue - - if reach_backspace_flag : - if not reach_backspace_second_flag: - pattern_str +=str_r[0] + if len(str_r) != 0: + if reach_backspace_flag: + result_command = result_command[0:-backspace_num] + pattern_str + pattern_str = '' + else: + reach_backspace_flag = True + backspace_num = len(str(tmp.group(0))) + continue else: - pattern_list.append(pattern_str) - pattern_str=str_r[0] - reach_backspace_second_flag=False + break + + if reach_backspace_flag : + pattern_str +=str_r[0] else : result_command += str_r[0] str_r = str_r[1:] - - if pattern_str !='': - pattern_list.append(pattern_str) - - #退格队列中还有腿哥键,则进行删除操作 - if len(backspace_list) > 0 : - for backspace in backspace_list: - if int(backspace) >= len(result_command): - result_command = pattern_list[0] - else: - result_command = result_command[:-int(backspace)] - result_command += pattern_list[0] - pattern_list = pattern_list[1:] + + if backspace_num > 0 : + result_command = result_command[0:-backspace_num] + pattern_str control_char = re.compile(r""" \x1b[ #%()*+\-.\/]. | @@ -200,21 +173,14 @@ class Tty(object): """, re.X) result_command = control_char.sub('', result_command.strip()) global VIM_FLAG - global VIM_COMMAND if not VIM_FLAG: if result_command.startswith('vi'): VIM_FLAG = True - VIM_COMMAND = result_command return result_command.decode('utf8',"ignore") else: - if check_vim_status(VIM_COMMAND, ssh): + if result_command.endswith(':wq') or result_command.endswith(':wq!') or result_command.endswith(':q!'): VIM_FLAG = False - VIM_COMMAND='' - if result_command.endswith(':wq') or result_command.endswith(':wq!') or result_command.endswith(':q!'): - return '' - return result_command.decode('utf8',"ignore") - else: - return '' + return '' @staticmethod def remove_control_char(str_r): From 0c42d039fff3610a8c6541e5690c6a230e7cf3ce Mon Sep 17 00:00:00 2001 From: kelianchun_miller <360271747@qq.com> Date: Sun, 22 Nov 2015 20:18:33 +0800 Subject: [PATCH 2/6] update connect.py --- connect.py | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/connect.py b/connect.py index b02c6428b..548482ed1 100644 --- a/connect.py +++ b/connect.py @@ -178,8 +178,6 @@ class Tty(object): VIM_FLAG = True return result_command.decode('utf8',"ignore") else: - if result_command.endswith(':wq') or result_command.endswith(':wq!') or result_command.endswith(':q!'): - VIM_FLAG = False return '' @staticmethod @@ -338,9 +336,12 @@ class SshTty(Tty): log_file_f, log_time_f, log = self.get_log() old_tty = termios.tcgetattr(sys.stdin) pre_timestamp = time.time() + pattern = re.compile('\[.*@.*\][\$#]') data = '' + chan_str = '' input_mode = False - + global VIM_FLAG + try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) @@ -357,6 +358,8 @@ class SshTty(Tty): x = self.channel.recv(1024) if len(x) == 0: break + if VIM_FLAG: + chan_str += x sys.stdout.write(x) sys.stdout.flush() now_timestamp = time.time() @@ -377,10 +380,19 @@ class SshTty(Tty): input_mode = True if str(x) in ['\r', '\n', '\r\n']: - data = self.deal_command(data, self.ssh) - - TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() + if VIM_FLAG: + match = pattern.search(chan_str) + if match: + VIM_FLAG = False + data = self.deal_command(data, self.ssh) + if len(data) > 0: + TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() + else: + data = self.deal_command(data, self.ssh) + if len(data) > 0: + TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() data = '' + chan_str = '' input_mode = False if len(x) == 0: From c359d1e264ab16f7300d4d27294bddf736a88c62 Mon Sep 17 00:00:00 2001 From: kelianchun_miller <360271747@qq.com> Date: Sun, 22 Nov 2015 20:20:04 +0800 Subject: [PATCH 3/6] update connect.py --- connect.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/connect.py b/connect.py index 548482ed1..b3440a628 100644 --- a/connect.py +++ b/connect.py @@ -96,7 +96,7 @@ class Tty(object): return False @staticmethod - def deal_command(str_r, ssh): + def deal_command(str_r): """ 处理命令中特殊字符 """ @@ -384,11 +384,11 @@ class SshTty(Tty): match = pattern.search(chan_str) if match: VIM_FLAG = False - data = self.deal_command(data, self.ssh) + data = self.deal_command(data) if len(data) > 0: TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() else: - data = self.deal_command(data, self.ssh) + data = self.deal_command(data) if len(data) > 0: TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() data = '' From 5f9e675d00e95874a0b62dd25543b65145dd853a Mon Sep 17 00:00:00 2001 From: kelianchun_miller <360271747@qq.com> Date: Sun, 22 Nov 2015 20:29:35 +0800 Subject: [PATCH 4/6] update connect.py --- connect.py | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/connect.py b/connect.py index b3440a628..5bf3b8981 100644 --- a/connect.py +++ b/connect.py @@ -52,23 +52,6 @@ def color_print(msg, color='red', exits=False): sys.exit() -def check_vim_status(command, ssh): - global SSH_TTY - print command - if command == '': - return True - else: - command_str= 'ps -ef |grep "%s" | grep "%s"|grep -v grep |wc -l' % (command,SSH_TTY) - print command_str - stdin, stdout, stderr = ssh.exec_command(command_str) - ps_num = stdout.read() - print ps_num - if int(ps_num) == 0: - return True - else: - return False - - class Tty(object): """ A virtual tty class From 70db8c69d263a077146f0a3a806dae6f0a3c3b38 Mon Sep 17 00:00:00 2001 From: ibuler Date: Sun, 22 Nov 2015 20:45:48 +0800 Subject: [PATCH 5/6] global SSH_FLAG to self.ssh_flag --- connect.py | 74 ++++++++++++++++++------------------------------------ 1 file changed, 24 insertions(+), 50 deletions(-) diff --git a/connect.py b/connect.py index b3440a628..00ece2f60 100644 --- a/connect.py +++ b/connect.py @@ -26,7 +26,6 @@ from jumpserver.settings import LOG_DIR from jperm.ansible_api import Command login_user = get_object(User, username=getpass.getuser()) -VIM_FLAG = False try: import termios @@ -52,23 +51,6 @@ def color_print(msg, color='red', exits=False): sys.exit() -def check_vim_status(command, ssh): - global SSH_TTY - print command - if command == '': - return True - else: - command_str= 'ps -ef |grep "%s" | grep "%s"|grep -v grep |wc -l' % (command,SSH_TTY) - print command_str - stdin, stdout, stderr = ssh.exec_command(command_str) - ps_num = stdout.read() - print ps_num - if int(ps_num) == 0: - return True - else: - return False - - class Tty(object): """ A virtual tty class @@ -86,6 +68,7 @@ class Tty(object): self.ssh = None self.connect_info = None self.login_type = 'ssh' + self.vim_flag = False @staticmethod def is_output(strings): @@ -95,25 +78,24 @@ class Tty(object): return True return False - @staticmethod - def deal_command(str_r): + def deal_command(self, str_r): """ - 处理命令中特殊字符 + 处理命令中特殊字符 """ - str_r = re.sub('\x07','',str_r) #删除响铃 - patch_char = re.compile('\x08\x1b\[C') #删除方向左右一起的按键 + str_r = re.sub('\x07', '', str_r) # 删除响铃 + patch_char = re.compile('\x08\x1b\[C') # 删除方向左右一起的按键 while patch_char.search(str_r): str_r = patch_char.sub('', str_r.rstrip()) - result_command = '' #最后的结果 - backspace_num = 0 #光标移动的个数 - reach_backspace_flag = False #没有检测到光标键则为true - pattern_str='' + result_command = '' # 最后的结果 + backspace_num = 0 # 光标移动的个数 + reach_backspace_flag = False # 没有检测到光标键则为true + pattern_str = '' while str_r: tmp = re.match(r'\s*\w+\s*', str_r) if tmp: - if reach_backspace_flag : - pattern_str +=str(tmp.group(0)) + if reach_backspace_flag: + pattern_str += str(tmp.group(0)) str_r = str_r[len(str(tmp.group(0))):] continue else: @@ -124,7 +106,7 @@ class Tty(object): tmp = re.match(r'\x1b\[K[\x08]*', str_r) if tmp: if backspace_num > 0: - if backspace_num > len(result_command) : + if backspace_num > len(result_command): result_command += pattern_str result_command = result_command[0:-backspace_num] else: @@ -134,8 +116,8 @@ class Tty(object): if del_len > 0: result_command = result_command[0:-del_len] reach_backspace_flag = False - backspace_num =0 - pattern_str='' + backspace_num = 0 + pattern_str = '' str_r = str_r[len(str(tmp.group(0))):] continue @@ -153,13 +135,13 @@ class Tty(object): else: break - if reach_backspace_flag : - pattern_str +=str_r[0] - else : + if reach_backspace_flag: + pattern_str += str_r[0] + else: result_command += str_r[0] str_r = str_r[1:] - if backspace_num > 0 : + if backspace_num > 0: result_command = result_command[0:-backspace_num] + pattern_str control_char = re.compile(r""" @@ -172,11 +154,10 @@ class Tty(object): [\x80-\x9f] | (?:\x1b\]0.*) | \[.*@.*\][\$#] | (.*mysql>.*) #匹配 所有控制字符 """, re.X) result_command = control_char.sub('', result_command.strip()) - global VIM_FLAG - if not VIM_FLAG: + if not self.vim_flag: if result_command.startswith('vi'): - VIM_FLAG = True - return result_command.decode('utf8',"ignore") + self.vim_flag = True + return result_command.decode('utf8', "ignore") else: return '' @@ -247,11 +228,6 @@ class Tty(object): """ 获取需要登陆的主机的信息和映射用户的账号密码 """ - - # 1. get ip, port - # 2. get 映射用户 - # 3. get 映射用户的账号,密码或者key - # self.connect_info = {'user': '', 'asset': '', 'ip': '', 'port': 0, 'role_name': '', 'role_pass': '', 'role_key': ''} asset_info = get_asset_info(self.asset) self.connect_info = {'user': self.user, 'asset': self.asset, 'ip': asset_info.get('ip'), 'port': int(asset_info.get('port')), 'role_name': self.role.name, @@ -340,8 +316,6 @@ class SshTty(Tty): data = '' chan_str = '' input_mode = False - global VIM_FLAG - try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) @@ -358,7 +332,7 @@ class SshTty(Tty): x = self.channel.recv(1024) if len(x) == 0: break - if VIM_FLAG: + if self.vim_flag: chan_str += x sys.stdout.write(x) sys.stdout.flush() @@ -380,10 +354,10 @@ class SshTty(Tty): input_mode = True if str(x) in ['\r', '\n', '\r\n']: - if VIM_FLAG: + if self.vim_flag: match = pattern.search(chan_str) if match: - VIM_FLAG = False + self.vim_flag = False data = self.deal_command(data) if len(data) > 0: TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() From eb779e5bf64a3c153fb5160a27644898a895cd1d Mon Sep 17 00:00:00 2001 From: ibuler Date: Sun, 22 Nov 2015 21:59:07 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E4=BF=AE=E6=94=B9run=5Fwebsocket?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- connect.py | 38 ++++++++------------------------------ run_websocket.py | 30 ++++++++++++++++++++---------- 2 files changed, 28 insertions(+), 40 deletions(-) diff --git a/connect.py b/connect.py index 00ece2f60..cf0824a7d 100644 --- a/connect.py +++ b/connect.py @@ -19,7 +19,7 @@ import struct, fcntl, signal, socket, select os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings' if django.get_version() != '1.6': django.setup() -from jumpserver.api import ServerError, User, Asset, AssetGroup, get_object, mkdir, get_asset_info, get_role +from jumpserver.api import ServerError, User, Asset, PermRole, AssetGroup, get_object, mkdir, get_asset_info, get_role from jumpserver.api import logger, Log, TtyLog, get_role_key from jperm.perm_api import gen_resource, get_group_asset_perm, get_group_user_perm from jumpserver.settings import LOG_DIR @@ -69,6 +69,8 @@ class Tty(object): self.connect_info = None self.login_type = 'ssh' self.vim_flag = False + self.ps1_pattern = re.compile('\[.*@.*\][\$#]') + self.vim_data = '' @staticmethod def is_output(strings): @@ -161,27 +163,6 @@ class Tty(object): else: return '' - @staticmethod - def remove_control_char(str_r): - """ - 处理日志特殊字符 - """ - control_char = re.compile(r""" - \x1b[ #%()*+\-.\/]. | - \r | #匹配 回车符(CR) - (?:\x1b\[|\x9b) [ -?]* [@-~] | #匹配 控制顺序描述符(CSI)... Cmd - (?:\x1b\]|\x9d) .*? (?:\x1b\\|[\a\x9c]) | \x07 | #匹配 操作系统指令(OSC)...终止符或振铃符(ST|BEL) - (?:\x1b[P^_]|[\x90\x9e\x9f]) .*? (?:\x1b\\|\x9c) | #匹配 设备控制串或私讯或应用程序命令(DCS|PM|APC)...终止符(ST) - \x1b. #匹配 转义过后的字符 - [\x80-\x9f] #匹配 所有控制字符 - """, re.X) - backspace = re.compile(r"[^\b][\b]") - line_filtered = control_char.sub('', str_r.rstrip()) - while backspace.search(line_filtered): - line_filtered = backspace.sub('', line_filtered) - - return line_filtered - def get_log(self): """ Logging user command and output. @@ -312,9 +293,7 @@ class SshTty(Tty): log_file_f, log_time_f, log = self.get_log() old_tty = termios.tcgetattr(sys.stdin) pre_timestamp = time.time() - pattern = re.compile('\[.*@.*\][\$#]') data = '' - chan_str = '' input_mode = False try: tty.setraw(sys.stdin.fileno()) @@ -333,7 +312,7 @@ class SshTty(Tty): if len(x) == 0: break if self.vim_flag: - chan_str += x + self.vim_data += x sys.stdout.write(x) sys.stdout.flush() now_timestamp = time.time() @@ -352,21 +331,20 @@ class SshTty(Tty): if sys.stdin in r: x = os.read(sys.stdin.fileno(), 1) input_mode = True - if str(x) in ['\r', '\n', '\r\n']: if self.vim_flag: - match = pattern.search(chan_str) + match = self.ps1_pattern.search(self.vim_data) if match: self.vim_flag = False - data = self.deal_command(data) + data = self.deal_command(data)[0:200] if len(data) > 0: TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() else: - data = self.deal_command(data) + data = self.deal_command(data)[0:200] if len(data) > 0: TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() data = '' - chan_str = '' + self.vim_data = '' input_mode = False if len(x) == 0: diff --git a/run_websocket.py b/run_websocket.py index 9d565fe42..bb8a0a8ff 100644 --- a/run_websocket.py +++ b/run_websocket.py @@ -20,15 +20,9 @@ from tornado.websocket import WebSocketClosedError from tornado.options import define, options from pyinotify import WatchManager, Notifier, ProcessEvent, IN_DELETE, IN_CREATE, IN_MODIFY, AsyncNotifier +import select -# from gevent import monkey -# monkey.patch_all() -# import gevent -# from gevent.socket import wait_read, wait_write -import struct, fcntl, signal, socket, select, fnmatch - -import paramiko -from connect import Tty +from connect import Tty, User, Asset, PermRole from connect import TtyLog, Log try: @@ -217,7 +211,10 @@ class WebTerminalHandler(tornado.websocket.WebSocketHandler): username = self.get_argument('username', '') token = self.get_argument('token', '') print asset_name, username, token - self.term = WebTty('a', 'b') + user = User.objects.get(username='lastimac') + asset = Asset.objects.get(ip='192.168.244.129') + role = PermRole.objects.get(name='dev') + self.term = WebTty(user, asset, role) self.term.get_connection() self.term.channel = self.term.ssh.invoke_shell(term='xterm') WebTerminalHandler.tasks.append(MyThread(target=self.forward_outbound)) @@ -236,7 +233,17 @@ class WebTerminalHandler(tornado.websocket.WebSocketHandler): if data.get('data'): self.term.input_mode = True if str(data['data']) in ['\r', '\n', '\r\n']: - TtyLog(log=self.log, datetime=datetime.datetime.now(), cmd=self.term.deal_command(self.term.data, self.term.ssh)).save() + if self.term.vim_flag: + match = self.term.ps1_pattern.search(self.term.vim_data) + if match: + self.term.vim_flag = False + vim_data = self.term.deal_command(self.term.vim_data)[0:200] + if len(data) > 0: + TtyLog(log=self.log, datetime=datetime.datetime.now(), cmd=vim_data).save() + + TtyLog(log=self.log, datetime=datetime.datetime.now(), + cmd=self.term.deal_command(self.term.data)[0:200]).save() + self.term.vim_data = '' self.term.data = '' self.term.input_mode = False self.term.channel.send(data['data']) @@ -267,6 +274,8 @@ class WebTerminalHandler(tornado.websocket.WebSocketHandler): if not len(recv): return data += recv + if self.term.vim_flag: + self.term.vim_data += recv try: self.write_message(json.dumps({'data': data})) now_timestamp = time.time() @@ -290,4 +299,5 @@ if __name__ == '__main__': server.bind(options.port, options.host) # server.listen(options.port) server.start(num_processes=1) + print "Run server on %s:%s" % (options.host, options.port) tornado.ioloop.IOLoop.instance().start()