From eb779e5bf64a3c153fb5160a27644898a895cd1d Mon Sep 17 00:00:00 2001 From: ibuler Date: Sun, 22 Nov 2015 21:59:07 +0800 Subject: [PATCH] =?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()