示例#1
0
    def post(self, key, **data):
        link = None
        form = None
        method = 'post'
        id = None
        for i, f in enumerate(self.forms):
            if f.action.find(key) != -1 and f.method.lower() == 'post':
                link = f.action
                form = f
                id = i
                break

        if not link:
            L.err("no search form action be found !", txt_color='red')
            L.i('type search("xxx", key="[ here]")',
                tag="only found 'key' :\n")
            for i, v in enumerate(self.forms):
                L.i(v.action, tag=i)
            return None

        data = self.form_check(id, data)
        with show_pro('loging', link):
            res = to(urljoin(self.url, link),
                     session=self.session,
                     data=data,
                     agent=True,
                     method=method)
        return Analyze(res, session=self.session)
示例#2
0
 def __repr__(self):
     attrs = self._res.attrs
     attrs.update({"name": self._res.name})
     for attr in attrs:
         L.i(attrs[attr], tag=attr)
     print(" ------------------------------------ ")
     return ''
示例#3
0
    def ex(self):
        # print(self.options)
        if self.options['Editor']:
            os.system("vi %s" % J(MODULE_PATH, self.module_name + '.py'))
            raise SystemExit("0")

        if self.options['thread'] > 1:
            self.exe = Exe(self.options['thread'])

            LogControl.i('thread: %d' % self.options['thread'], txt_color='blue')

        if self.options['add_data']:
            self.add_res(self.options['add_data'])
            raise SystemExit("0")

        if self.options['delete_data']:
            self.del_res()
            raise SystemExit("0")        

        self.parser()
        try:

            if not isinstance(self.payloads, (list, dict, tuple,)):
                # LogControl.wrn("check here")
                self.run(self.options)
                # LogControl.wrn("check here1")
                raise SystemExit(0)

            for payload in self.payloads:
                self.options['payload'] = payload
                LogControl.title("load payload: ", colored(payload, attrs=['underline', 'bold']) , txt_color="blue",end="\r")
                self.run(self.options)
        except (KeyboardInterrupt, InterruptedError):
            LogControl.i("~~bye")
            raise SystemExit(0)
示例#4
0
 def __repr__(self):
     if isinstance(self._res, list):
         for i, v in enumerate(self._res):
             L.i(v, tag=i)
     elif isinstance(self._res, dict):
         for k in self._res:
             v = self._res[k]
             L.i(v, tag=k)
     return ''
示例#5
0
    def do_list(self, name):
        data_tmp = SOCIAL[name]
        cols = list(data_tmp.keys())
        res = self.db.search(name, *cols)

        for i in res:
            v = dict(zip(cols, i))
            for k in v:
                print("\t", end='')
                v[k] = v[k][:90] + '...' if len(v[k]) > 90 else v[k]
                LogControl.i(v[k], tag=k, txt_color='yellow')
            print( "---------------------")
示例#6
0
 def do_setting(self, args):
     for k in SOCIAL:
         LogControl.i(k, txt_color='red')
     m = dict_cmd({"which table":None})
     for k in SOCIAL[m["which table"]]:
         LogControl.i(k, txt_color='red', tag=m["which table"])
     res = dict_cmd({
         'Title': None,
         'Value': None,
     })
     new_cols = {res['Title']: res['Value']}
     self.db.alter(m["which table"], **new_cols)
示例#7
0
def upload_history(sh=SHELL, debug=False):
    """
    find cmd in sh's history

    @sh='zsh' / can choose bash
    """

    history_file = J(ENV("HOME"), '.%s_history' % sh)
    keys_dict = dict()
    with open(history_file, 'rb') as fp:
        for line in fp:

            
            # filter some unused cmd
            try:
                # remove prompt and decode as utf-8

                # zsh
                if sh == 'zsh':
                    cmd_str = line.decode('utf8').split(";")[1]
                # bash
                else:
                    cmd_str = line.decode('utf8')
                    
                args = cmd_str.split()

                # count cmd
                cmd_title = args[0]
                if cmd_title not in keys_dict:
                    keys_dict.setdefault(cmd_title, 1)
                else:
                    keys_dict[cmd_title] += 1
                
                ID = keys_dict[cmd_title]
                
                if len(cmd_title) > 20:
                    continue
                if cmd_title.find("/") != -1:
                    continue
            except IndexError as e:
                LogControl.err(e, '\n', '\t', line)
                continue
            except UnicodeDecodeError as e:
                continue


            redis(cmd_title, ID, cmd_str)
            LogControl.i(cmd_title, end='\r')
            sys.stdout.flush()
    redis.redis.save()
示例#8
0
def show_pro(sta, text):
    try:
        L.save()
        L.loc(0, 0, True)
        L.i(text,
            tag=sta,
            end='\r',
            tag_color='green',
            txt_color='yellow',
            txt_attr=['underline'])
        yield
    finally:
        print('\r')
        L.load()
示例#9
0
def main():
    cmd_str = ' '.join(sys.argv[1:])
    if '--help' in sys.argv:
        L.i(DOC, tag="help")
        sys.exit(0)
    if ',,' in cmd_str:
        fuzz, cmd = cmd_str.split(",,")
    else:
        cmd = cmd_str
        fuzz = input_default(colored('Host run:', "blue"), "")

    choose_hosts(fuzz)

    try:
        for h in env.hosts:
            env.host_string = h
            shell(cmd, h)
    except (KeyboardInterrupt, InterruptedError) as e:
        L.ok("Bye~")
示例#10
0
    def do_search(self, name):
        data_tmp = SOCIAL[name]
        tmp = {
            "set search key": str,
        }
        tmp = dict_cmd(tmp)

        keys = dict.fromkeys(tmp['set search key'].split(',') if tmp['set search key'].find(",") != -1 else tmp['set search key'].split() )
        keys = dict_cmd(keys)
        cols = input_default("which interesting?\n %s\n>" % ' '.join([colored(i, attrs=['underline']) for i in data_tmp.keys() ]) )
        if 'all' in cols:
            cols = ' '.join(list(data_tmp.keys()))
        cols = cols.split(",") if cols.find(",") != -1 else cols.split()
        res = self.db.search(name, *cols, **keys)
        for i in res:

            v = dict(zip(cols, i))
            for k in v:
                print("\t", end='')
                v[k] = v[k][:90] + '...' if len(v[k]) > 90 else v[k]
                LogControl.i(v[k], tag=k, txt_color='yellow')
示例#11
0
def execute(cmd, help=False, console=False, **args):
    LogControl.ok('\n')
    t_dir = dir_gen()
    try:
        os.makedirs(t_dir)
    except Exception as e:
        pass
    DB_Handler = SqlEngine(database=DB_PATH)
    cmds = []
    options = set()
    for i in DB_Handler.select("templates", 'cmd', 'keys', 'output', group_key=cmd):
        cmds.append([i[0], i[2]])
        [ options.add(m) for m in i[1].split()]
    
    if help:
        LogControl.i("need to set options: ", options)
        for cmd, out in cmds:
            LogControl.i(cmd, ' -> ', out, txt_color='yellow')
        return True

    else:
        for cmd, out in cmds:
            try:
                rrun(cmd.format(**args), t_dir, out)
            except Exception as e:
                LogControl.err(e,cmd)
                LogControl.i("need to set options: ", options)
                continue

        if console:
            try:
                os.system('sleep 2 && tail -f %s/*' % t_dir)
            except KeyboardInterrupt as e:
                LogControl.info("~bye")
示例#12
0
def delete_mode():
    """
    delete some cmds.
    """
    while 1:
        c = dinput("[l:list all comba-cmds, q:exit, s:search cmd, d xxx :delete xxx comba cmd] \n>", default='q')
        if c == 'q':
            LogControl.i('~ by')
            break
        elif c == 'l':
            for m,res in search_comba_cmds():
                LogControl.i(m, res)
        else:
            if c[0] == 's':
                cc = ''
                try:
                    cc = c.split()[1]
                except Exception as e:
                    LogControl.err(e)
                    continue
                for m,res in search_comba_cmds(cc):
                    LogControl.i(m, res)

            elif c[0] == 'd':
                cc = ''
                try:
                    cc = c.split()[1]
                except Exception as e:
                    LogControl.err(e)
                    continue

                delete_template_in_sqlite_db(cc)
                LogControl.ok("delete it.")
            else:
                continue
示例#13
0
def choose_hosts(fuzz=None):
    # print(fuzz)
    res = list(get_records(fuzz.strip()))
    # print(res)
    roles = []
    passwd = {}
    if res:
        for I, i in enumerate(res):
            L.i(i[0], tag=I)

        for i in par(input_default(colored("exm: 1,2-4 >>", "cyan"), '0')):
            if isinstance(i, tuple):
                for m in i:
                    roles.append(res[m][0] + ":" + res[m][1])
                    passwd[res[m][0] + ":" + res[m][1]] = res[m][2]
            else:
                roles.append(res[i][0] + ":" + res[i][1])
                passwd[res[i][0] + ":" + res[i][1]] = res[i][2]
    else:
        r = dict_cmd({
            "user": None,
            "host": None,
            "port": None,
            "passwd": None,
        })

        roles = [r['user'] + "@" + r['host'] + ":" + r['port']]
        if not roles:
            L.i("nil.")
            return None
        sql.insert("host", ['login', 'port', 'passwd'],
                   r['user'] + "@" + r['host'], r['port'], r['passwd'])
        passwd[roles[0]] = r['passwd']
    print(roles)
    res = {"t": roles}
    env.roledefs.update(res)

    env.hosts = res['t']

    env.passwords = passwd
示例#14
0
    def show(self, t='c'):
        """
        t == 'c':
            show in console
        t == 'b':
            show in browser
        """
        if t == 'c':
            L.i(self.link,
                tag=self.title,
                txt_color='yellow',
                txt_attr=['underline'])
            if self.time:
                L.i(self.time, tag='T', txt_attr=['bold'])
            if self.img:
                L.i(self.img, tag='img')
            L.i(self.doc, tag='doc', end='\n' + '-' * (L.SIZE[1] - 10) + '\n')

        else:
            pass
示例#15
0
    def del_res(self):

        """
        delete some cmds.
        """
        while 1:
            c = dinput("[l:list all res, q:exit, s:search cmd, d xxx :delete xxx comba cmd] \n>", default='q')
            if c == 'q':
                LogControl.i('~ by')
                break
            elif c == 'l':
                for res in self.get_res():
                    LogControl.i(res[0], res[1:])
            else:
                if c[0] == 's':
                    cc = ''
                    try:
                        cc = c.split()[1]
                    except Exception as e:
                        LogControl.err(e)
                        continue
                    for res in self.get_res(grep=cc):
                        LogControl.i(res[0], res[1:])

                elif c[0] == 'd':
                    cc = ''
                    try:
                        cc = c.split()[1]
                    except Exception as e:
                        LogControl.err(e)
                        continue

                    self.db.delete(self.table, id=cc)
                    LogControl.ok("delete it.")
                else:
                    continue
示例#16
0
def shell(cmd, h):
    output = run(cmd, quiet=True)
    L.i('\n' + output, tag=h)
示例#17
0
    def search(self, search_str, key='search'):
        link = None
        form = None
        method = None
        id = None

        for i, f in enumerate(self.forms):
            if not hasattr(f, 'method'):
                f.method = 'get'  # just for js's search form

            if f.action.find(key) != -1:
                link = f.action
                form = f
                id = i
                break

        # find GET form as search form
        for i, f in enumerate(self.forms):
            if f.method.lower() == 'get':
                link = f.action
                form = f
                id = i
                break

        if not link:
            L.err("no search form action be found !", txt_color='red')
            L.i('type search("xxx", key="[ here]")',
                tag="only found 'key' :\n")
            for i, v in enumerate(self.forms):
                L.i(v.action, tag=i)
            return None

        method = form.method.lower()
        f_table = {}
        for name in form.names():
            i = form[name]['value']
            if not i:
                f_table[name] = search_str
            else:
                f_table[name] = i

        if method == 'get':
            link += "?%s" % urlencode(f_table)

            return Analyze(urljoin(self.url, link),
                           show_process=self.show_process,
                           session=self.session,
                           method=method)
        else:
            res = to(link, method=method, session=self.session, data=f_table)

            if res.headers['Content-Type'].find("json") != -1:
                return res.json()
            elif res.headers['Content-Type'].find('ml') != -1:
                return Analyze(res,
                               session=self.session,
                               show_process=self.show_process)
            else:
                L.err("return res is not json or xml",
                      res.headers['Content-Type'])
                return None
示例#18
0
 def __repr__(self):
     for i, f in enumerate(self._res):
         m = f.method if hasattr(f, 'method') else 'no method'
         L.i(f.action, m, tag=i)
     return ''
示例#19
0
def rrun(cmd, dir, output, **options):
    cmd_str = cmd + ' 1> %s/%s  2> %s/error.log'  % (dir, output, dir)
    LogControl.i(cmd_str)
    return os.popen(cmd_str, **options)