def __init__(self, p):
super(readkbd, self).__init__(p)
self.prompt = p
self.controlc = None
# we want readline completer to give us the "/" as well!
readline.set_completer_delims( readline.get_completer_delims().replace("/", "").replace("-","") )
print "+++++++++++++++++++++ Welcome to cli +++++++++++++++++++"
print "$Id: command.py,v 1.16 2015-11-04 13:30:10 jive_cc Exp $"
print " 'exit' exits, 'list' lists, 'help' helps "
# add the iterator protocol (the context protocol is supplied by newhistory)
python类set_completer_delims()的实例源码
def choice():
global name
global module
try:
if module == "":
readline.set_completer(completer)
readline.set_completer_delims('')
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
raw_choice = raw_input(" >> [" + name + "]# ")
choice = raw_choice
exec_menu(choice)
else:
readline.set_completer(completer)
readline.set_completer_delims('')
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
raw_choice = raw_input(" >> [" + name + "][" + module + "]# ")
choice = raw_choice
exec_menu(choice)
except EOFError:
pass
except KeyboardInterrupt:
exec_menu('exit')
def __enter__(self):
self._original_completer = readline.get_completer()
self._original_delims = readline.get_completer_delims()
readline.set_completer(self.complete)
readline.set_completer_delims(' \t\n;')
# readline can be implemented using GNU readline or libedit
# which have different configuration syntax
if 'libedit' in readline.__doc__:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
def __exit__(self, unused_type, unused_value, unused_traceback):
readline.set_completer_delims(self._original_delims)
readline.set_completer(self._original_completer)
def run(self, line):
def _formatOutput(res):
if isinstance(res, str):
return res
else:
try:
return "\n".join(_formatOutput(r) for r in res)
except TypeError:
return str(res)
ishellCompleter = readline.get_completer()
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)
filePath = raw_input("Please specify a path to the output file: ").strip()
readline.set_completer(ishellCompleter)
if os.path.isfile(filePath):
confirm = raw_input("File already exists and will be overwritten, confirm? [y/N] ")
if confirm is "" or confirm[0] not in ("y", "Y"):
print "Canceled."
return
with open(filePath, "w+") as handle:
handle.write(_formatOutput(feathermodules.results))
def InitReadline(complete_cb):
home_dir = os.environ.get('HOME')
if home_dir is None:
home_dir = util.GetHomeDir()
if home_dir is None:
print("Couldn't find home dir in $HOME or /etc/passwd", file=sys.stderr)
return
history_filename = os.path.join(home_dir, 'oil_history')
try:
readline.read_history_file(history_filename)
except IOError:
pass
atexit.register(readline.write_history_file, history_filename)
readline.parse_and_bind("tab: complete")
# How does this map to C?
# https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#SEC45
readline.set_completer(complete_cb)
# NOTE: This apparently matters for -a -n completion -- why? Is space the
# right value?
# http://web.mit.edu/gnu/doc/html/rlman_2.html#SEC39
# "The basic list of characters that signal a break between words for the
# completer routine. The default value of this variable is the characters
# which break words for completion in Bash, i.e., " \t\n\"\\'`@$><=;|&{(""
#
# Hm I don't get this.
readline.set_completer_delims(' ')
def Init(pool, builtins, mem, funcs, comp_lookup, status_out, ev):
aliases_action = WordsAction(['TODO:alias'])
commands_action = ExternalCommandAction(mem)
builtins_action = WordsAction(builtins.GetNamesToComplete())
keywords_action = WordsAction(['TODO:keywords'])
funcs_action = LiveDictAction(funcs)
first_chain = ChainedCompleter([
aliases_action, commands_action, builtins_action, keywords_action,
funcs_action
])
# NOTE: These two are the same by default
comp_lookup.RegisterEmpty(first_chain)
comp_lookup.RegisterFirst(first_chain)
# NOTE: Need set_completer_delims to be space here? Otherwise you complete
# as --a and --n. Why?
comp_lookup.RegisterName('__default__', WordsAction(['-a', '-n']))
A1 = WordsAction(['foo.py', 'foo', 'bar.py'])
A2 = WordsAction(['m%d' % i for i in range(5)], delay=0.1)
C1 = ChainedCompleter([A1, A2])
comp_lookup.RegisterName('grep', C1)
var_comp = VarAction(os.environ, mem)
root_comp = RootCompleter(pool, ev, comp_lookup, var_comp)
complete_cb = ReadlineCompleter(root_comp, status_out)
InitReadline(complete_cb)
def __init__(self, lhost, lport):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.lhost = lhost
self.lport = lport
self.framework = Framework(self.send_command, self.check_command, self.get_response)
self.command_definition = {}
self.credentials = []
self.fast_load = False
self.prompt = ""
self.os_target = None
# Define command behavior
self.command_definition["Local-Invoke"] = lambda x: self.psh_Local_Invoke(x[len("Local-Invoke"):].strip())
self.command_definition["Local-Import-Module"] = lambda x: self.psh_Local_Invoke(x[len("Local-Import-Module"):].strip(), True)
self.command_definition["Local-Set-Width"] = lambda x: self.psh_Local_Set_Width(x[len("Local-Set-Width"):].strip())
self.command_definition["Local-Upload"] = lambda x: self.psh_Local_Upload(x[len("Local-Upload"):].strip())
self.command_definition["Local-Download"] = lambda x: self.psh_Local_Download(x[len("Local-Download"):].strip())
self.command_definition["Local-Download-Commands"] = lambda x: self.psh_Local_Download_Commands()
self.command_definition["Local-Enumerate-System"] = lambda x: self.psh_Local_Enumerate_System()
self.command_definition["Local-Check-Status"] = lambda x: self.psh_Local_Check_Status()
self.command_definition["Local-Spawn-Meterpreter"] = lambda x: self.psh_Local_Spawn_Shell(conf_name.METERPRETER)
self.command_definition["Local-Spawn-Reverse-Shell"] = lambda x: self.psh_Local_Spawn_Shell(conf_name.REVERSE_SHELL)
self.command_definition["Local-Credential-Create"] = lambda x: self.psh_Local_Credential(True)
self.command_definition["Local-Credential-List"] = lambda x: self.psh_Local_Credential()
self.command_definition["clear"] = lambda x: self.psh_Local_Clear()
# Define autocomplete
readline.parse_and_bind("tab: complete")
readline.set_completer(self.cmd_complete)
readline.set_completion_display_matches_hook(self.cmd_match_display_hook)
readline.set_completer_delims("")
def set_completer_delims(self, s):
"""
Set the completer delimiters--the characters that delimit tokens
that are eligible for completion.
:Parameters:
s : str
The delimiters
"""
pass
def set_completer_delims(self, s):
readline.set_completer_delims(s)
def set_completer_delims(self, s):
readline.set_completer_delims(s)
def completer():
# source: https://gist.github.com/iamatypeofwalrus/5637895
class tabCompleter(object):
def pathCompleter(self,text,state):
line = readline.get_line_buffer().split()
return [x for x in glob(text+'*')][state]
def createListCompleter(self,ll):
pass
def listCompleter(text,state):
line = readline.get_line_buffer()
if not line:
return None
else:
return [c + " " for c in ll if c.startswith(line)][state]
self.listCompleter = listCompleter
t = tabCompleter()
# tool command
t.createListCompleter(["clear", "exit", "banner","exec","restart", "upgrade", 'search'
# modules
# auxiliary modules
,"use auxiliary/gather/ip_gather","use auxiliary/gather/ip_lookup", "use auxiliary/core/pyconverter"
# exploit modules
,"use exploit/windows/ftp/ftpshell_overflow", "use exploit/android/login/login_bypass", "use exploit/windows/http/oracle9i_xdb_pass"])
readline.set_completer_delims('\t')
readline.parse_and_bind("tab: complete")
readline.set_completer(t.listCompleter)
def cmdloop(self, intro=None):
try:
import readline
readline.set_completer_delims(' ')
super(Console, self).cmdloop()
except (KeyboardInterrupt, EOFError):
print('')
self.cmdloop()
def launch_ui(args):
# Setup tab completion
try:
import readline
except ImportError:
print('%s[!] Module \'readline\' not available. Tab complete disabled.%s' % (Colors.R, Colors.N))
else:
import rlcompleter
if 'libedit' in readline.__doc__:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
readline.set_completer_delims(re.sub('[/-]', '', readline.get_completer_delims()))
# Instantiate the UI object
x = cli.CLI(cli.Mode.CONSOLE)
# check for and run version check
if args.check:
if not x.version_check(): return
# Check for and run script session
if args.script_file:
x.do_resource(args.script_file)
# Run the UI
try:
x.cmdloop()
except KeyboardInterrupt:
print('')
# ======================================================================================================================
# MAIN
# ======================================================================================================================
def __enter__(self):
try:
import readline
self.readline = readline
except ImportError:
return
else:
readline.parse_and_bind('tab: complete')
readline.set_completer_delims('')
readline.set_completer(partial(self.complete, self.ma))
def __init__( self, beachConfig = None, token = None, hbsKey = None, logFile = None, callbackDomain1 = None, callbackDomain2 = None ):
self.histFile = os.path.expanduser( '~/.lc_history' )
self.logFile = logFile
if self.logFile is not None:
self.logFile = open( self.logFile, 'w', 0 )
cmd.Cmd.__init__( self, stdout = ( self.logFile if self.logFile is not None else sys.stdout ) )
self.be = None
self.user = None
self.hbsKey = None
self.aid = None
self.investigationId = None
self.tags = Symbols()
self.cbDomain1 = callbackDomain1
self.cbDomain2 = callbackDomain2
readline.set_completer_delims(":;'\"? \t")
readline.set_history_length( 100 )
try:
readline.read_history_file( self.histFile )
except:
self.outputString( 'Failed to load history file' )
open( self.histFile, 'w' ).close()
if beachConfig is not None:
self.connectWithConfig( beachConfig, token )
if hbsKey is not None:
self.loadKey( hbsKey )
def __init__(self,cmdcomplete,init_flag=True):
self.text = ""
self.matches = []
self.cmdcomplete = cmdcomplete
self.symbols = []
self.index = 0
self.cleanup_flag = True
self.init_flag = init_flag
self.session_start_index = 0
self.HISTLEN = 2000
self.HISTFILE = ".atrophy-history"
self.DEFAULT_HIST_DISPLAY_LEN = 20
self.delims = readline.get_completer_delims()
readline.set_completer_delims(self.delims.replace("/",''))
self.delims = readline.get_completer_delims()
readline.set_completer_delims(self.delims.replace("?",''))
self.delims = readline.get_completer_delims()
readline.set_completer_delims(self.delims.replace("@",''))
readline.parse_and_bind('tab: complete')
readline.set_completer(self.complete)
# persistant commands that actually affect a session
# (e.g. breakpoints, mem writes, comments)
self.project_cmds = [ "sd", "b", "db", "sb","#", "//" ]
if self.init_flag == True:
self.init_flag = False
try:
readline.read_history_file(self.HISTFILE)
self.session_start_index = readline.get_current_history_length()
readline.set_history_length(self.HISTLEN)
except Exception as e:
pass
atexit.register(self.on_exit,self.HISTFILE)
def preloop(self):
cmd.Cmd.preloop(self)
readline.set_completer_delims(' ')
def setup_readline():
"""Sets up the readline module and completion supression, if available."""
global RL_COMPLETION_SUPPRESS_APPEND, RL_LIB, RL_CAN_RESIZE
if RL_COMPLETION_SUPPRESS_APPEND is not None:
return
try:
import readline
except ImportError:
return
import ctypes
import ctypes.util
readline.set_completer_delims(' \t\n')
if not readline.__file__.endswith('.py'):
RL_LIB = lib = ctypes.cdll.LoadLibrary(readline.__file__)
try:
RL_COMPLETION_SUPPRESS_APPEND = ctypes.c_int.in_dll(
lib, 'rl_completion_suppress_append')
except ValueError:
# not all versions of readline have this symbol, ie Macs sometimes
RL_COMPLETION_SUPPRESS_APPEND = None
RL_CAN_RESIZE = hasattr(lib, 'rl_reset_screen_size')
env = builtins.__xonsh_env__
# reads in history
readline.set_history_length(-1)
ReadlineHistoryAdder()
# sets up IPython-like history matching with up and down
readline.parse_and_bind('"\e[B": history-search-forward')
readline.parse_and_bind('"\e[A": history-search-backward')
# Setup Shift-Tab to indent
readline.parse_and_bind('"\e[Z": "{0}"'.format(env.get('INDENT')))
# handle tab completion differences found in libedit readline compatibility
# as discussed at http://stackoverflow.com/a/7116997
if readline.__doc__ and 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")