本文整理汇总了Python中ui.color.colorize函数的典型用法代码示例。如果您正苦于以下问题:Python colorize函数的具体用法?Python colorize怎么用?Python colorize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了colorize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __call__
def __call__(self, pattern=""):
"""Nicely display self dict's items as a formatted
multiline string array.
The optionnal argument `pattern` can be used to limit
item display to keys whose name starts with it's value.
"""
# get matching vars list
if not self.keys():
raise ValueError("No such " + self.title)
keys = [k for k in self.keys() if k.startswith(pattern)]
if not keys:
msg = "No such {} matching «{}»"
raise ValueError(msg.format(self.title, pattern))
# process formatted string
tpl = (" {:%s} {}\n") % max(8, len(max(keys, key=len)))
buffer = self.title + "\n" + ("=" * len(self.title)) + "\n\n"
buffer += tpl.format("Variable", "Value")
buffer += tpl.format("--------", "-----")
for id, key in enumerate(sorted(keys)):
buffer += colorize(["%Reset", "%Reset"][id % 2],
tpl.format(key, self[key]))
return "\n" + buffer + colorize("%Reset")
示例2: doc_help
def doc_help(docLines):
"""print the formated command's docstring"""
# reject empty docstrings (description + empty line)
if len(docLines) < 2:
return False
docLines.pop(0) # remove the description line
while not docLines[0].strip():
docLines.pop(0) # remove heading empty lines
# remove junk leading spaces (due to python indentation)
trash = len(docLines[0]) - len(docLines[0].lstrip())
docLines = [line[trash:].rstrip() for line in docLines]
# hilight lines with no leading spaces (man style)
result = str()
for line in docLines:
if line == line.lstrip():
line = colorize("%BoldWhite", line)
elif line.startswith(" * "):
line = colorize(" * ", "%Yellow", line[6:])
elif line.startswith(" > "):
line = colorize(" > ", "%Cyan", line[6:])
result += line + "\n"
print(result)
示例3: __str__
def __str__(self):
low, big = [str(x).rstrip('0').rstrip('.') for x in self]
main = colorize('%Bold', '%s', '%Basic')
if low == big:
text = main %low
comment = '(fixed interval)'
else:
text = ' <= '.join((low, main %'x', big))
comment = '(random interval)'
return colorize('%Pink', text, " ", '%DimWhite', comment)
示例4: print_node
def print_node(node):
if 'dn' in node:
print(colorize('%BlueBold', node['dn']))
else:
print(colorize('%BlueBold', '----------------------'))
for key, val in node.items():
if isinstance(val, dict):
del val['count']
line = " %s : %s" % (colorize('%Bold', "%20s" % key), ' | '.join(val.values()))
print(line)
print()
示例5: debug_cmdrepr
def debug_cmdrepr(argv):
"""Returns a nice representation of given command arguments
"""
cmdrepr = []
for arg in argv:
if not isinstance(arg, str):
continue
argrepr = repr(arg)
sep = argrepr[0], argrepr[-1]
argrepr = argrepr[1:-1].join(colorize("%DimCyan", "%Reset"))
cmdrepr.append(sep[0] + argrepr + sep[1])
args = " ".join(cmdrepr)
return colorize("%BoldCyan", "CMD(", "%Reset", args, "%BoldCyan", ")")
示例6: default_console
def default_console(self):
print(colorize("%BoldWhite", self.banner))
while True:
try:
exec(input("> "))
except EOFError:
return 0
except SystemExit as err:
if err.code is not None:
print(err.code)
return int(bool(err.code))
except BaseException as e:
e = traceback.format_exception(type(e), e, e.__traceback__)
e.pop(1)
print(colorize("%Red", "".join(e)))
示例7: run
def run(self, argv):
from api import server
try:
ExecPlugin(self)
except KeyboardInterrupt:
raise KeyboardInterrupt
except SystemExit as e:
retval = e.args[0] if e.args else e.code
if not isinstance(retval, int):
lines = self.help.splitlines()
if len(lines) > 1 and str(retval) == self.help:
print()
print("[*] %s: %s" % (self.name, lines.pop(0)))
for line in lines:
if line == line.lstrip():
line = colorize("%BoldWhite", line)
print(line)
print()
else:
print("[-] %s: %s" % (self.name, retval))
retval = 1
return retval
except server.payload.PayloadError as err:
print("[-] %s: %s" % (self.name, err))
return 64
except BaseException as err:
msg = "Python runtime error (exception occured)"
print("[-] %s: %s:" % (self.name, msg))
raise err
示例8: __str__
def __str__(self):
"""Return a color string representation of the setting var object.
If the buffer has no multiple lines, single choice's string
representation is returned. Otherwise, the multi line choices
buffer is represented.
>>> str( RandLineBuffer("singleChoice") )
'singleChoice'
>>> str( RandLineBuffer("file:///etc/passwd") )
'<[email protected]/etc/passwd (24 choices)>'
>>> str( RandLineBuffer("choice1\\nchoice2") )
'<RandLine (2 choices)>'
"""
# if buffer have one line only, return line string's obj repr
if not self.file and len(self.buffer.splitlines()) == 1:
return str(self._getobj(self.buffer.strip()))
# objID is file path OR buffer's md5sum
if self.file:
objID = self.file
else:
objID = hashlib.md5(self.buffer.encode('utf-8')).hexdigest()
# choices is the string that show available choices
num = len(self.choices())
choices = " (%s choice%s)" % (num, ('', 's')[num > 1])
return colorize("%BoldBlack", "<", "%BoldBlue", "RandLine",
"%BasicCyan", "@", "%Bold", objID, "%BasicBlue",
choices, "%BoldBlack", ">")
示例9: diff
def diff(self, file, display_diff=False):
"""This function returns True is the given `file` is
a phpsploit session which differs from current session.
Otherwise, False is returned.
Additionally, if `display_diff` is set, the session
differences will be displayed in common unix `diff` style.
"""
# non-failing copy.deepcopy(self) equivalent:
diff = self._obj_value(self._raw_value(self))
diff.update(file)
diff = decolorize(diff).splitlines()
orig = decolorize(self).splitlines()
retval = diff != orig
if display_diff:
color = {' ': '%Reset', '-': '%Red', '+': '%Green', '?': '%Pink'}
for line in difflib.Differ().compare(orig, diff):
# dont be too much verbose...
if line.startswith('?'):
continue
print(colorize(color[line[0]], line))
return retval
示例10: diff
def diff(self, file=None, display_diff=False):
"""This function returns True is the given `file` is
a phpsploit session which differs from current session.
Otherwise, False is returned.
Additionally, if `display_diff` is set, the session
differences will be displayed in common unix `diff` style.
"""
if isinstance(file, Session):
diff = self.deepcopy(file)
else:
if file is None:
diff = Session()
diff.File = self.File
else:
diff = self.deepcopy()
diff.update(file)
diff = decolorize(diff).splitlines()
orig = decolorize(self).splitlines()
if display_diff:
color = {' ': '%Reset', '-': '%Red', '+': '%Green', '?': '%Pink'}
if file is None:
difflines = difflib.Differ().compare(diff, orig)
else:
difflines = difflib.Differ().compare(orig, diff)
for line in difflines:
# dont be too much verbose...
if line.startswith('?'):
continue
print(colorize(color[line[0]], line))
return diff != orig
示例11: build_forwarder
def build_forwarder(self, method, decoder):
"""build the effective payload forwarder, which is in fact
a header using the PASSKEY setting as name.
The payload forwarder is called by the remote backdoor, and then
formats the final payload if necessary before executing it.
"""
decoder = decoder % "$x"
template = self.forwarder_template[method]
template = template.replace('%%PASSKEY%%', self.passkey)
rawForwarder = template % decoder
b64Forwarder = base64.b64encode(rawForwarder.encode()).decode()
# here we delete the ending "=" from base64 payload
# because if the string is not enquoted it will not be
# evaluated. on iis6, apache2, php>=4.4 it dont seem
# to return error, and is a hacky solution to eval a payload
# without quotes, preventing header quote escape by server
# eg: "eval(base64_decode(89jjLKJnj))"
b64Forwarder = b64Forwarder.rstrip('=')
hdr_payload = self.header_payload
forwarder = hdr_payload % b64Forwarder
if not self.is_first_payload:
# if the currently built request is not the first http query
# sent to the server, it means that it works as it is. Therefore,
# additionnal payload warnings and verifications are useless.
return {self.passkey: forwarder}
err = None
# if the base64 payload is not enquoted by REQ_HEADER_PAYLOAD
# setting and contains non alpha numeric chars (aka + or /),
# then warn the user in case of bad http response.
if "'%s'" not in hdr_payload and \
'"%s"' not in hdr_payload and \
not b64Forwarder.isalnum():
# create a visible sample of the effective b64 payload
oneThirdLen = float(len(forwarder) / 3)
oneThirdLen = int(round(oneThirdLen + 0.5))
sampleSeparator = colorize("%Reset", "\n[*]", "%Cyan")
lineList = [''] + split_len(forwarder, oneThirdLen)
showForwarder = sampleSeparator.join(lineList)
# set the payload forwarder error
err = ("[*] do not enquotes the base64 payload which"
" contains non alpha numeric chars (+ or /),"
" blocking execution:" + showForwarder)
# if the current request is not concerned by the previous case
# an other kind of error may happen because the contents of
# the header that forwards the payload contains quotes.
elif '"' in hdr_payload or \
"'" in hdr_payload:
err = ("[*] contains quotes, and some http servers "
"defaultly act escaping them in request headers.")
self.payload_forwarder_error = err
return {self.passkey: forwarder}
示例12: ipython_console
def ipython_console(self):
"""IPython console interpreter
https://ipython.org/
"""
# pylint: disable=import-error
import IPython
print(colorize("%BoldWhite", self.banner))
IPython.embed()
return 0
示例13: __str__
def __str__(self):
"""Get a nice string representation of current session
"""
title = "PhpSploit session dump ({})".format(self.File)
# deco = "\n" + colorize("%Blue", "=" * len(title)) + "\n"
deco = "\n" + colorize("%Blue", "=" * 68) + "\n"
data = deco + title + deco
ordered_keys = ["Conf", "Env", "Alias"]
for name in ordered_keys:
if self[name]:
data += str(self[name]) + "\n"
return data
示例14: default_console
def default_console(self):
"""Simple python console interpreter
Used as fallback when neither of other consoles are available
It basically consists in an exec(input("> ")) loop
"""
print(colorize("%BoldWhite", self.banner))
while True:
try:
# pylint: disable=exec-used
exec(input("> "))
except EOFError:
print()
return 0
except SystemExit as e:
if e.code is not None:
print(e.code)
return int(bool(e.code))
except BaseException as e:
e = traceback.format_exception(type(e), e, e.__traceback__)
e.pop(1)
print(colorize("%Red", "".join(e)))
示例15: do_exploit
def do_exploit(self, argv):
"""Spawn a shell from target server
SYNOPSIS:
exploit [--get-backdoor]
DESCRIPTION:
This command send an HTTP request to the remote server
url (defined by the $TARGET setting).
If $TARGET is correctly backdoored with the
phpsploit backdoor, the request remotely executes
the session opener in order to retrieve environment
variables, and spawn the phpsploit remote shell.
OPTIONS:
--get-backdoor
Only display current backdoor, as it should be
injected on the current or future target url.
NOTE: The $TARGET setting should be a valid http(s) url,
previously infected with the phpsploit backdoor.
"""
obj = str(session.Conf.BACKDOOR(call=False))
obj = obj.replace("%%PASSKEY%%", session.Conf.PASSKEY().upper())
if len(argv) > 1:
if argv[1] == "--get-backdoor":
print(obj)
return True
else:
self.interpret("help exploit")
return False
print("[*] Current backdoor is: " + obj + "\n")
if tunnel:
m = ("[*] Use `set TARGET <VALUE>` to use another url as target."
"\n[*] To exploit a new server, disconnect from «{}» first.")
print(m.format(session.Env.HOST))
return False
elif session.Conf.TARGET() is None:
m = ("To run a remote tunnel, the backdoor shown above must be\n"
"manually injected in a remote server executable web page.\n"
"Then, use `set TARGET <BACKDOORED_URL>` and run `exploit`.")
print(colorize("%BoldCyan", m))
return False
else:
return tunnel.open() # it raises exception if fails