How to use cmd_logs method in localstack

Best Python code snippet using localstack_python

interactive.py

Source:interactive.py Github

copy

Full Screen

1# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>2#3# This file is part of paramiko.4#5# Paramiko is free software; you can redistribute it and/or modify it under the6# terms of the GNU Lesser General Public License as published by the Free7# Software Foundation; either version 2.1 of the License, or (at your option)8# any later version.9#10# Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY11# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR12# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more13# details.14#15# You should have received a copy of the GNU Lesser General Public License16# along with Paramiko; if not, write to the Free Software Foundation, Inc.,17# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.18import socket19import sys20import select21from paramiko.py3compat import u22from modules import models23import datetime24# windows does not have termios...25try:26 import termios27 import tty28 has_termios = True29except ImportError:30 has_termios = False31def interactive_shell(chan,user_obj,bind_host_obj,cmd_logs,log_recording):32 if has_termios:33 posix_shell(chan,user_obj,bind_host_obj,cmd_logs,log_recording)34 else:35 windows_shell(chan)36def posix_shell(chan,user_obj,bind_host_obj,cmd_logs,log_recording):37 # 获取原tty属性38 oldtty = termios.tcgetattr(sys.stdin)39 try:40 # 为tty设置新属性41 # 默认当前tty设备属性:42 # 输入一行回车,执行43 # CTRL+C 进程退出,遇到特殊字符,特殊处理。44 # 这是为原始模式,不认识所有特殊符号45 # 放置特殊字符应用在当前终端,如此设置,将所有的用户输入均发送到远程服务器46 tty.setraw(sys.stdin.fileno())47 tty.setcbreak(sys.stdin.fileno())48 chan.settimeout(0.0)49 cmd = ''50 tab_key = False51 # 注意,下面循环其实是先循环 if sys.stdin in r:(用户先有输入),后面循环if chan in r:(放回结果,tab键补全的内容也是返回结果)52 while True:53 r, w, e = select.select([chan, sys.stdin], [], [])54 if chan in r:55 try:56 x = u(chan.recv(1024))57 # 如果用户上一次点击的是tab键,则获取返回的内容写入在记录中58 if tab_key:59 #if x not in ('\x07' , '\r\n'):60 cmd += x # 这里会记录一个tab键加上tab后面的stdout61 tab_key = False62 if len(x) == 0:63 sys.stdout.write('\r\n*** EOF\r\n')64 break65 sys.stdout.write(x)66 sys.stdout.flush()67 except socket.timeout:68 pass69 if sys.stdin in r:70 # 因为要使用tab键,所以一个字节一个字节的去读取数据71 x = sys.stdin.read(1)72 # 用户输入命令的时候没有输入回车,比如ifconfig,会依次循环收取i,f,c,o,n,此时再输入tab键,会循环到下面的if x == "\t":判断,tab键补全的内容就是标准输出了,stdout会走到上面的循环中去,if tab_key73 if x != "\r":74 cmd += x75 else: # 这里用户输入了回车,一条命令执行完毕76 log_item = models.AuditLog(user_id=user_obj.id,77 bind_host_id=bind_host_obj.id,78 action_type='cmd',79 cmd=cmd.replace("\t",""), #替换掉命令中的tab空格80 date=datetime.datetime.now()81 )82 cmd_logs.append(log_item)83 cmd = ""84 if len(cmd_logs)>= 10:85 #log_recording(user_obj,bind_host_obj,cmd_caches) #貌似user_obj,bind_host_obj和cmd_caches中的有些字段重复了86 log_recording(cmd_logs) # 记录用户日志,每十条写一次数据库87 cmd_logs = []88 if x == "\t": # 用户输入tab89 tab_key = True90 if len(x) == 0:91 break92 chan.send(x)93 finally:94 # 重新设置终端属性95 termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)96 97# thanks to Mike Looijmans for this code98def windows_shell(chan):99 import threading100 sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")101 102 def writeall(sock):103 while True:104 data = sock.recv(256)105 if not data:106 sys.stdout.write('\r\n*** EOF ***\r\n\r\n')107 sys.stdout.flush()108 break109 sys.stdout.write(data.decode())110 sys.stdout.flush()111 112 writer = threading.Thread(target=writeall, args=(chan,))113 writer.start()114 115 try:116 while True:117 d = sys.stdin.read(1)118 if not d:119 break120 chan.send(d)121 except EOFError:122 # user hit ^Z or F6...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

1"""2This file is a part of the source code for the KithscordBot.3This project has been licensed under the MIT license.4Copyright (c) 2021-present Kithare Organization5This file is the main file of kithscord subdir6"""7import io8import signal9import sys10import discord11from kithscord import commands, common, routine12from kithscord.utils import utils13is_init = False14async def _init():15 """16 Startup call helper for kithscord bot17 """18 if not common.LOCAL_TEST:19 sys.stdout = sys.stderr = common.stdout = io.StringIO()20 print("The KithscordBot is now online!")21 print("Server(s):")22 for server in common.bot.guilds:23 prim = ""24 if common.guild is None and server.id == common.SERVER_ID:25 prim = "| Primary Guild"26 common.guild = server27 print(" -", server.name, "| Number of channels:", len(server.channels), prim)28 for channel in server.channels:29 if channel.id == common.LOG_CHANNEL_ID:30 common.log_channel = channel31 elif channel.id == common.CONSOLE_CHANNEL_ID:32 common.console_channel = channel33async def init():34 """35 Startup call helper for kithscord bot36 """37 global is_init38 if is_init:39 return40 try:41 await _init()42 except Exception:43 # error happened in the first init sequence. report error to stdout/stderr44 # note that the chances of this happening are pretty slim, but you never know45 sys.stdout = sys.__stdout__46 sys.stderr = sys.__stderr__47 raise48 if not common.LOCAL_TEST:49 routine.handle_console.start()50 await utils.setup_kcr()51 if common.guild is None:52 raise RuntimeWarning(53 "Primary guild was not set. Some features of bot would not run as usual."54 " People running commands via DMs might face some problems"55 )56 is_init = True57async def message_delete(msg: discord.Message):58 """59 This function is called for every message deleted by user.60 """61 if msg.id in common.cmd_logs:62 del common.cmd_logs[msg.id]63 elif msg.author.id == common.bot.user.id:64 for log, logmsg in common.cmd_logs.items():65 if logmsg.id == msg.id:66 del common.cmd_logs[log]67 return68async def message_edit(_: discord.Message, new: discord.Message):69 """70 This function is called for every message edited by user.71 """72 if not new.content.startswith(common.PREFIX):73 return74 try:75 if new.id in common.cmd_logs:76 await commands.handle(new, common.cmd_logs[new.id])77 except discord.HTTPException:78 pass79async def handle_message(msg: discord.Message):80 """81 Handle a message posted by user82 """83 if msg.channel.id in common.NO_TALK_CHANNELS and msg.author.id != common.BOT_ID:84 await msg.delete()85 return86 if not msg.content.startswith(common.PREFIX):87 return88 ret = await commands.handle(msg)89 if ret is not None:90 common.cmd_logs[msg.id] = ret91 if len(common.cmd_logs) > 100:92 del common.cmd_logs[list(common.cmd_logs)[0]]93def cleanup(*_):94 """95 Call cleanup functions96 """97 common.bot.loop.run_until_complete(common.bot.close())98 common.bot.loop.close()99def run():100 """101 Does what discord.Client.run does, except, handles custom cleanup functions102 """103 # use signal.signal to setup SIGTERM signal handler, runs after event loop104 # closes105 signal.signal(signal.SIGTERM, cleanup)106 try:107 common.bot.loop.run_until_complete(common.bot.start(common.TOKEN))108 except KeyboardInterrupt:109 # Silence keyboard interrupt traceback (it contains no useful info)110 pass111 finally:...

Full Screen

Full Screen

logging_commands.py

Source:logging_commands.py Github

copy

Full Screen

...8async def setup(bot: commands.Bot):9 bot.add_command(cmd_logs)10@commands.command(name="logs")11@commands.has_guild_permissions(manage_guild=True)12async def cmd_logs(context: commands.Context):13 last_logs = datamanagement.getLastLogs(guild=context.guild, limit=10)14 if not last_logs:15 embed = discord.Embed(16 title="No logs found",17 color=discord.Color.orange()18 )19 else:20 embed = discord.Embed(21 color=discord.Color.green()22 )23 for log in last_logs:24 embed.add_field(25 name=str(log.timestamp),26 value=f"```txt\n{log.message}```",...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful