def run(self): #while (not self._stop_event.is_set()): #text = self.queue.get_message() #if text: #if isinstance(data,(list,tuple)): #if data[0] == 'close': #self.stop() from webterminal.asgi import channel_layer with self.read_lock: #self.pending_read_request.clear() while True: instruction = self.client.receive() if instruction: channel_layer.send(self.message.reply_channel.name, {"text": instruction}) else: break #if self.pending_read_request.is_set(): #logger.info('Letting another request take over.') #break # End-of-instruction marker channel_layer.send(self.message.reply_channel.name, {"text": '0.;'})
def run(self): from webterminal.asgi import channel_layer with self.read_lock: while True: try: instruction = self.client.receive() if instruction: if instruction.startswith('bytearray(b'): instruction = instruction.rsplit( "bytearray(b'")[1].rsplit("')")[0] channel_layer.send(self.message.reply_channel.name, {"text": instruction}) # with open(os.path.join(self.recording_path,self.message.reply_channel.name),'ab+') as f: # f.write(instruction) else: break except timeout: queue = get_redis_instance() queue.pubsub() queue.publish(self.message.reply_channel.name, '10.disconnect;') # End-of-instruction marker channel_layer.send(self.message.reply_channel.name, {"text": '0.;'})
def posix_shell(chan, channel): from webterminal.asgi import channel_layer try: chan.settimeout(0.0) while True: try: x = u(chan.recv(1024)) if len(x) == 0: channel_layer.send( channel, { 'text': json.dumps([ 'disconnect', smart_unicode('\r\n*** EOF\r\n') ]) }) break channel_layer.send( channel, {'text': json.dumps(['stdout', smart_unicode(x)])}) except socket.timeout: pass except Exception, e: channel_layer.send( channel, { 'text': json.dumps([ 'stdout', 'A bug find,You can report it to me' + smart_unicode(e) ]) }) finally: pass
def _print_exec_out(cmd, out_buf, err_buf, exit_status, channel_name=None): from webterminal.asgi import channel_layer channel_layer.send(channel_name, {'text': json.dumps( ['stdout', smart_unicode('command executed: {}'.format(cmd))])}) logger.debug('command executed: {}'.format(cmd)) logger.debug('STDOUT:') channel_layer.send(channel_name, {'text': json.dumps( ['stdout', smart_unicode('STDOUT:')])}) for line in out_buf: logger.debug(line, "end=") channel_layer.send(channel_name, {'text': json.dumps( ['stdout', smart_unicode(line.strip('\n'))])}) channel_layer.send(channel_name, {'text': json.dumps( ['stdout', smart_unicode('end of STDOUT')])}) logger.debug('end of STDOUT') channel_layer.send(channel_name, {'text': json.dumps( ['stdout', smart_unicode('STDERR:')])}) logger.debug('STDERR:') for line in err_buf: logger.debug(line, "end=") channel_layer.send(channel_name, {'text': json.dumps( ['stdout', smart_unicode(line, "end=")])}) channel_layer.send(channel_name, {'text': json.dumps( ['stdout', smart_unicode('end of STDERR')])}) logger.debug('end of STDERR') channel_layer.send(channel_name, {'text': json.dumps( ['stdout', smart_unicode('finished with exit status: {}'.format(exit_status))])}) logger.debug('finished with exit status: {}'.format(exit_status)) channel_layer.send(channel_name, {'text': json.dumps( ['stdout', smart_unicode('------------------------------------')])}) logger.debug('------------------------------------')
def posix_shell(chan, channel, log_name=None, width=90, height=40, elementid=None): from webterminal.asgi import channel_layer stdout = list() begin_time = time.time() last_write_time = {'last_activity_time': begin_time} command = list() if elementid: logobj = Log.objects.get(channel=elementid) else: logobj = Log.objects.get(channel=channel) vim_flag = False vim_data = '' try: chan.settimeout(0.0) while True: try: x = u(chan.recv(1024)) if len(x) == 0: if elementid: channel_layer.send( channel, { 'text': json.dumps([ 'disconnect', smart_unicode('\r\n*** EOF\r\n'), elementid.rsplit('_')[0] ]) }) else: channel_layer.send( channel, { 'text': json.dumps([ 'disconnect', smart_unicode('\r\n*** EOF\r\n') ]) }) break now = time.time() delay = now - last_write_time['last_activity_time'] last_write_time['last_activity_time'] = now if x == "exit\r\n" or x == "logout\r\n" or x == 'logout': chan.close() else: if vim_flag: vim_data += x logger.debug('raw data {0}'.format(command)) if '\r\n' not in x: command.append(x) else: command = CommandDeal().deal_command(''.join(command)) if len(command) != 0: #vim command record patch logger.debug('command {0}'.format(command)) if command.strip().startswith( 'vi') or command.strip().startswith('fg'): CommandLog.objects.create(log=logobj, command=command) vim_flag = True else: if vim_flag: if re.compile('\[.*@.*\][\$#]').search( vim_data): vim_flag = False vim_data = '' else: CommandLog.objects.create(log=logobj, command=command) command = list() if isinstance(x, unicode): stdout.append([delay, x]) else: stdout.append([ delay, codecs.getincrementaldecoder('UTF-8')( 'replace').decode(x) ]) if isinstance(x, unicode): if elementid: channel_layer.send( channel, { 'text': json.dumps( ['stdout', x, elementid.rsplit('_')[0]]) }) else: channel_layer.send(channel, {'text': json.dumps(['stdout', x])}) else: if elementid: channel_layer.send( channel, { 'text': json.dumps([ 'stdout', smart_unicode(x), elementid.rsplit('_')[0] ]) }) else: channel_layer.send( channel, {'text': json.dumps(['stdout', smart_unicode(x)])}) #send message to monitor group if log_name: channel_layer.send_group( u'monitor-{0}'.format(log_name.rsplit('/')[1]), {'text': json.dumps(['stdout', smart_unicode(x)])}) except socket.timeout: pass except Exception, e: logger.error(traceback.print_exc()) if elementid: channel_layer.send( channel, { 'text': json.dumps([ 'stdout', 'A bug find,You can report it to me' + smart_unicode(e), elementid.rsplit('_')[0] ]) }) else: channel_layer.send( channel, { 'text': json.dumps([ 'stdout', 'A bug find,You can report it to me' + smart_unicode(e) ]) }) finally: attrs = { "version": 1, "width": width, #int(subprocess.check_output(['tput', 'cols'])), "height": height, #int(subprocess.check_output(['tput', 'lines'])), "duration": round(time.time() - begin_time, 6), "command": os.environ.get('SHELL', None), 'title': None, "env": { "TERM": os.environ.get('TERM'), "SHELL": os.environ.get('SHELL', 'sh') }, 'stdout': list(map(lambda frame: [round(frame[0], 6), frame[1]], stdout)) } mkdir_p('/'.join(os.path.join(MEDIA_ROOT, log_name).rsplit('/')[0:-1])) with open(os.path.join(MEDIA_ROOT, log_name), "a") as f: f.write( json.dumps(attrs, ensure_ascii=True, cls=CustomeFloatEncoder, indent=2)) if elementid: audit_log = Log.objects.get(channel=elementid, log=log_name.rsplit('/')[-1]) else: audit_log = Log.objects.get(channel=channel, log=log_name.rsplit('/')[-1]) audit_log.is_finished = True audit_log.end_time = timezone.now() audit_log.save() #hand ssh terminal exit queue = get_redis_instance() redis_channel = queue.pubsub() queue.publish(channel, json.dumps(['close']))
def posix_shell(chan,channel,log_name=None,width=90,height=40): from webterminal.asgi import channel_layer stdout = list() begin_time = time.time() last_write_time = {'last_activity_time':begin_time} try: chan.settimeout(0.0) while True: try: x = u(chan.recv(1024)) if len(x) == 0: channel_layer.send(channel, {'text': json.dumps(['disconnect',smart_unicode('\r\n*** EOF\r\n')]) }) break now = time.time() delay = now - last_write_time['last_activity_time'] last_write_time['last_activity_time'] = now if x == "exit\r\n" or x == "logout\r\n" or x == 'logout': chan.close() else: if isinstance(x,unicode): stdout.append([delay,x]) else: stdout.append([delay,codecs.getincrementaldecoder('UTF-8')('replace').decode(x)]) if isinstance(x,unicode): channel_layer.send(channel, {'text': json.dumps(['stdout',x]) }) else: channel_layer.send(channel, {'text': json.dumps(['stdout',smart_unicode(x)]) }) #send message to monitor group if log_name: channel_layer.send_group(u'monitor-{0}'.format(log_name.rsplit('/')[1].rsplit('.json')[0]), {'text': json.dumps(['stdout',smart_unicode(x)]) }) except socket.timeout: pass except Exception,e: print traceback.print_exc() channel_layer.send(channel, {'text': json.dumps(['stdout','A bug find,You can report it to me' + smart_unicode(e)]) }) finally: attrs = { "version": 1, "width": width,#int(subprocess.check_output(['tput', 'cols'])), "height": height,#int(subprocess.check_output(['tput', 'lines'])), "duration": round(time.time()- begin_time,6), "command": os.environ.get('SHELL',None), 'title':None, "env": { "TERM": os.environ.get('TERM'), "SHELL": os.environ.get('SHELL','sh') }, 'stdout':list(map(lambda frame: [round(frame[0], 6), frame[1]], stdout)) } mkdir_p('/'.join(os.path.join(MEDIA_ROOT,log_name).rsplit('/')[0:-1])) with open(os.path.join(MEDIA_ROOT,log_name), "a") as f: f.write(json.dumps(attrs, ensure_ascii=True,cls=CustomeFloatEncoder,indent=2)) audit_log=SshLog.objects.get(channel=channel,log=log_name.rsplit('/')[-1].rsplit('.json')[0]) audit_log.is_finished = True audit_log.end_time = timezone.now() audit_log.save() #hand ssh terminal exit queue = get_redis_instance() redis_channel = queue.pubsub() queue.publish(channel, json.dumps(['close']))