修改run_websocket

pull/26/head
ibuler 9 years ago
parent 47ace5d654
commit eb779e5bf6

@ -19,7 +19,7 @@ import struct, fcntl, signal, socket, select
os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings' os.environ['DJANGO_SETTINGS_MODULE'] = 'jumpserver.settings'
if django.get_version() != '1.6': if django.get_version() != '1.6':
django.setup() 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 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 jperm.perm_api import gen_resource, get_group_asset_perm, get_group_user_perm
from jumpserver.settings import LOG_DIR from jumpserver.settings import LOG_DIR
@ -69,6 +69,8 @@ class Tty(object):
self.connect_info = None self.connect_info = None
self.login_type = 'ssh' self.login_type = 'ssh'
self.vim_flag = False self.vim_flag = False
self.ps1_pattern = re.compile('\[.*@.*\][\$#]')
self.vim_data = ''
@staticmethod @staticmethod
def is_output(strings): def is_output(strings):
@ -161,27 +163,6 @@ class Tty(object):
else: else:
return '' 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): def get_log(self):
""" """
Logging user command and output. Logging user command and output.
@ -312,9 +293,7 @@ class SshTty(Tty):
log_file_f, log_time_f, log = self.get_log() log_file_f, log_time_f, log = self.get_log()
old_tty = termios.tcgetattr(sys.stdin) old_tty = termios.tcgetattr(sys.stdin)
pre_timestamp = time.time() pre_timestamp = time.time()
pattern = re.compile('\[.*@.*\][\$#]')
data = '' data = ''
chan_str = ''
input_mode = False input_mode = False
try: try:
tty.setraw(sys.stdin.fileno()) tty.setraw(sys.stdin.fileno())
@ -333,7 +312,7 @@ class SshTty(Tty):
if len(x) == 0: if len(x) == 0:
break break
if self.vim_flag: if self.vim_flag:
chan_str += x self.vim_data += x
sys.stdout.write(x) sys.stdout.write(x)
sys.stdout.flush() sys.stdout.flush()
now_timestamp = time.time() now_timestamp = time.time()
@ -352,21 +331,20 @@ class SshTty(Tty):
if sys.stdin in r: if sys.stdin in r:
x = os.read(sys.stdin.fileno(), 1) x = os.read(sys.stdin.fileno(), 1)
input_mode = True input_mode = True
if str(x) in ['\r', '\n', '\r\n']: if str(x) in ['\r', '\n', '\r\n']:
if self.vim_flag: if self.vim_flag:
match = pattern.search(chan_str) match = self.ps1_pattern.search(self.vim_data)
if match: if match:
self.vim_flag = False self.vim_flag = False
data = self.deal_command(data) data = self.deal_command(data)[0:200]
if len(data) > 0: if len(data) > 0:
TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save()
else: else:
data = self.deal_command(data) data = self.deal_command(data)[0:200]
if len(data) > 0: if len(data) > 0:
TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save() TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save()
data = '' data = ''
chan_str = '' self.vim_data = ''
input_mode = False input_mode = False
if len(x) == 0: if len(x) == 0:

@ -20,15 +20,9 @@ from tornado.websocket import WebSocketClosedError
from tornado.options import define, options from tornado.options import define, options
from pyinotify import WatchManager, Notifier, ProcessEvent, IN_DELETE, IN_CREATE, IN_MODIFY, AsyncNotifier from pyinotify import WatchManager, Notifier, ProcessEvent, IN_DELETE, IN_CREATE, IN_MODIFY, AsyncNotifier
import select
# from gevent import monkey from connect import Tty, User, Asset, PermRole
# 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 TtyLog, Log from connect import TtyLog, Log
try: try:
@ -217,7 +211,10 @@ class WebTerminalHandler(tornado.websocket.WebSocketHandler):
username = self.get_argument('username', '') username = self.get_argument('username', '')
token = self.get_argument('token', '') token = self.get_argument('token', '')
print asset_name, username, 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.get_connection()
self.term.channel = self.term.ssh.invoke_shell(term='xterm') self.term.channel = self.term.ssh.invoke_shell(term='xterm')
WebTerminalHandler.tasks.append(MyThread(target=self.forward_outbound)) WebTerminalHandler.tasks.append(MyThread(target=self.forward_outbound))
@ -236,7 +233,17 @@ class WebTerminalHandler(tornado.websocket.WebSocketHandler):
if data.get('data'): if data.get('data'):
self.term.input_mode = True self.term.input_mode = True
if str(data['data']) in ['\r', '\n', '\r\n']: 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.data = ''
self.term.input_mode = False self.term.input_mode = False
self.term.channel.send(data['data']) self.term.channel.send(data['data'])
@ -267,6 +274,8 @@ class WebTerminalHandler(tornado.websocket.WebSocketHandler):
if not len(recv): if not len(recv):
return return
data += recv data += recv
if self.term.vim_flag:
self.term.vim_data += recv
try: try:
self.write_message(json.dumps({'data': data})) self.write_message(json.dumps({'data': data}))
now_timestamp = time.time() now_timestamp = time.time()
@ -290,4 +299,5 @@ if __name__ == '__main__':
server.bind(options.port, options.host) server.bind(options.port, options.host)
# server.listen(options.port) # server.listen(options.port)
server.start(num_processes=1) server.start(num_processes=1)
print "Run server on %s:%s" % (options.host, options.port)
tornado.ioloop.IOLoop.instance().start() tornado.ioloop.IOLoop.instance().start()

Loading…
Cancel
Save