Пример #1
0
async def exec_command(*args):
    debug("[command] start run cmd")

    buffer = bytearray()
    debug("[command] ebook-meta ", *args)

    cmd_process = asyncio.create_subprocess_exec(
        "ebook-meta", *args, stdout=asyncio.subprocess.PIPE)
    proc = await cmd_process

    while True:
        line = await proc.stdout.readline()
        # debug("[command] r: ", line[0:-1].decode("gbk"))
        if not line:
            break

        buffer.extend(line)

    await proc.wait()

    return_code = proc.returncode
    debug("[command] return code: ", return_code)

    if not return_code:
        cmd_output = bytes(buffer).decode("gbk")
        term.writeLine("\n书籍元数据信息如下:", term.green, term.bold)
        print("====" * 30)
        term.write(cmd_output, term.bgwhite, term.bold, term.black)
        print("====" * 30)

    return return_code
Пример #2
0
def main():
	
	device_ids = ('773497',)  #if you have more device ids, you can add here as a tuple     
	headers = {'api-key':'1qHWLbTgkOUbQdpgE2zm26V0nc4='}
	client = OneNetClient('api.heclouds.com', *device_ids, **headers)
	
	options = ('off', 'on', 'check', 'quit')
	user = User()
	while(True):
		user_input = raw_input('>>>>').split()
		if user_input[0].lower() not in options:
			term.writeLine('Damn it! Wrong command. "quit" to exit', term.red, term.bold)
			continue

		elif len(user_input) > 1:
			arg = tuple(user_input[1:])
			body = user.on_or_off(options.index(user_input[0].lower()), *arg)
			client.send_cmd_to_device(0, body)			
		
		elif user_input[0].lower() == options[2]:
			re_value = client.get_single_device_datastreams(0)   # return response message body(str)
			user.check(re_value)

		else:	
			if user.quit():
				client.con_close()
			break
	
	term.writeLine('Have A Good Living, Dear User', term.red, term.reverse)
Пример #3
0
 def handle(self):
     term.writeLine("[*]New connection: {client}".format(client=self.client_address),term.green)
     self._get_token()
     while True:
         data = self.request.recv(1024)
         if not data:break
         try:
             data = struct.unpack(">200s200s200sLHH",data)
             # print(data)
             options = {}
             str_json = data[1].decode('UTF-8')
             str_json = str_json.strip('\x00')
             # print("Options : %s size : %d",str_json,len(str_json))
             for x in str_json.split(','):
                 k,v = x.split('=',2)
                 # print(k,":",v)
                 options.update({k.strip():v.strip()})
             payload = data[0].decode('UTF-8')
             payload = payload.strip('\x00')
             # print("Payload : %s Options : %s " % (payload,options['LHOST']))
             recv_payload = self.__send_payload(payload,options)
             # print("Send ..  %s ",recv_payload)
             payload_size = len(recv_payload[b'payload'])
             self.request.send(payload_size.to_bytes(4,byteorder='little',signed=False))
             self.request.send(recv_payload[b'payload'])
             self.request.close()
         except Exception as e:
             term.writeLine("[!]{error}".format(error=str(e)),term.red)
             pass
         finally:
             break
Пример #4
0
	def check(self, value):
		root = ast.literal_eval(value)
		term.writeLine('led_id\tstatus', term.yellow)
		for item in root["data"]:
			try:
				print item['id'], "\t", item['current_value']
			except:
				print "analysis error"
Пример #5
0
 def __send_payload(self, options):
     term.writeLine(
         "[*]PAYLOAD: {payload}".format(payload=options['payload']),
         term.green)
     pack_data = [
         "module.execute", self.token, "payload", options['payload'],
         options
     ]
     return self._request(pack_data)
Пример #6
0
	def __help(self):
		help_doc = '''So far, we just need to control the led on or off. Here are four operations:on, off, quit, and check.
on(*arg): you can turn on one or more led lights simultaneously. eg, on id1 id2 id3 ...
off(*arg): this method for turning off one or more lights. eg, off id1 id2 id3 ...
check(): for getting the status of all the lights in room. eg, check
quit(): to quit the interface and end the application, eg, quit
'''	
		term.clear()
		term.writeLine(help_doc, term.cyan, term.blink)
Пример #7
0
    def _get_token(self):
        options = ["auth.login", self.username, self.password]

        result = self._request(options)
        self.token = str(result[b'token'], encoding="utf8")
        term.writeLine(
            "[*]Token: {token} Username : {username} Password : {password}".
            format(token=self.token,
                   username=self.username,
                   password=self.password), term.green)
Пример #8
0
def main():
    example = 'Example:\n\n$ python3 server.py -U msf -P msf -v -s -l 4444'
    args = ArgumentParser(prog='Cooolis-ms', epilog=example)
    args.add_argument('-U',
                      '--username',
                      help='Metasploit web service username',
                      required=True)
    args.add_argument('-P',
                      '--password',
                      help='Metasploit web service password',
                      required=True)
    args.add_argument('-H',
                      '--host',
                      help='Metasploit web service host',
                      default='localhost')
    args.add_argument('-p',
                      '--port',
                      help='Metasploit RPC service port',
                      default=55553,
                      type=int)
    args.add_argument('-S',
                      '--server',
                      help='Payload sender listen host',
                      default='localhost')
    args.add_argument('-l',
                      '--listen',
                      help='Payload listen port',
                      default=1111,
                      type=int)
    args.add_argument('-u',
                      '--uri',
                      help='Metasploit RPC service uri',
                      default='/api/1.0/')
    args.add_argument('-t',
                      '--type',
                      help='Payload Type',
                      choices=('exe', 'ruby', 'c', 'dll', 'vbs', 'powershell'))
    args.add_argument('-s',
                      '--ssl',
                      help='Enable ssl',
                      action="store_true",
                      default=True)
    args.add_argument('-v',
                      '--versobe',
                      help='Enable debug',
                      action="store_true")
    parser = args.parse_args()
    term.writeLine(
        "[*]Server Host : {host} , Server Port : {port}".format(
            host=parser.server, port=parser.port), term.green)
    server = ThreadingTCPServer((parser.server, parser.listen),
                                Metasploit_RPC.Creator(parser))
    server.serve_forever()
Пример #9
0
 def _request(self,options):
     try:
         term.writeLine("[*]API URL : {url} , Method : {method}".format(url=self.url,method=options[0]), term.green)
         options = self.__pack(options)
         req  = requests.post(self.url,verify=False,headers=self.headers,data=options)
         result = self.__unpack(req.content)
         if b'error' in result:
             print("Error : %s" % str(result[b'error_message']),encoding = "utf8")
         else:
             return result
     except Exception as e:
         sys.stderr.write(str(e)+"\nRef:https://metasploit.help.rapid7.com/docs/standard-api-methods-referenc\n")
Пример #10
0
def execute(targets, args):
    execute_argparser = argparse.ArgumentParser(
        'execute a command on target of machines')
    execute_argparser.add_argument('-t',
                                   '--timeout',
                                   help='timeout to execute commands. ',
                                   default='2m')
    execute_argparser.add_argument('command')
    execute_argparser.add_argument('args', nargs=argparse.REMAINDER)
    args = execute_argparser.parse_args(args)
    timeout = timeparse(args.timeout)
    if args.args:
        cmd = convert_list_command_to_str([args.command, *args.args])
    else:
        cmd = args.command

    l = Lock()
    for target in targets:
        print(f'Start executing on {target}')

    def exec(i):
        target = targets[i]
        ret = None
        try:
            log_path = os.path.join(config.logs_dir, str(target))
            log = open(log_path, 'w')
            proc = target.run(cmd, timeout=timeout, stdout=log, stderr=log)
            if proc.returncode == 0:
                output = f'{term.green}SUCCESS{term.off} on {target}'
            else:
                output = f'{term.red}FAIL{term.off} on {target}. Exit code: {proc.returncode}'
            ret = proc
        except RunException as e:
            output = f'{term.red}FAIL{term.off} on {target}. Timeout'
            ret = e
        output += f'. Log: file://{log_path}'
        with l:
            term.saveCursor()
            term.up(len(targets) - i)
            term.clearLine()
            term.writeLine(output)
            term.restoreCursor()
        return ret

    results = pmap(exec, range(len(targets)))
    if all(
            map(lambda r: isinstance(r, RunResult) and r.returncode == 0,
                results)):
        term.writeLine('All execution succeeded', term.green)
        exit(0)
    else:
        term.writeLine('Some execution failed', term.red)
        exit(1)
Пример #11
0
 def print_stats(self):
     """ Display statistics of current request """
     if not self.queryset_stats:
         return
     term.writeLine("\n\t ERASERHEAD STATS \n", term.bold, term.reverse)
     for queryset_storage in self.queryset_stats:
         queryset_storage.print_stats()
     print()
     term.write("\t TOTAL WASTED MEMORY: ", term.bold, term.reverse)
     term.write(
         "  {}".format(humanfriendly.format_size(self.total_wasted_memory)),
         term.red)
     print()
Пример #12
0
		def output(item):
			author = re.search(r'<h2>(.*?)</h2>', item[0], re.S)
			#text = re.search(r'(.*)', item[1], re.S)
			text = item[1]
			other_info = re.findall(r'<i.+?number">(\d+)</i>\s(\S+?)\s?<', item[2], re.S)
			
			term.writeLine(author.group(1), term.green, term.blink)
			term.writeLine(text.replace('<br/>', '\n').strip(), term.yellow)
			# do like this in case of no fun or comment
			for info in other_info:
				term.write(info[0]+info[1]+'\t', term.blue)
			else:
				print '\n'
Пример #13
0
def init_db():
    dsn = 'postgresql://{user}:{password}@{host}/{database}'.format(
        user=settings.DB_USER,
        database=settings.DATABASE,
        host=settings.DB_HOST,
        password=settings.DB_PASSWORD
    )
    term.writeLine('Creating all tables on {dsn}'.format(dsn=dsn), term.bold)
    engine = sa.create_engine(dsn)

    metadata.create_all(engine)
    term.writeLine('{count} tables are successfully '
                   'created!'.format(count=len(metadata.tables)),
                   term.green)
Пример #14
0
 def end_time(self):
     self.stop = True
     end_time_show = time.asctime()
     end_time = time.monotonic()
     execution_time = (timedelta(seconds=end_time - self.start_time))
     print(self.blue("End time ==> ") + self.white(end_time_show))
     print(
         self.blue("Execution time ==> ") +
         self.white(str(execution_time)) + "\n")
     term.saveCursor()
     term.pos(7, 15)
     term.writeLine("ok", term.green, term.blink)
     term.restoreCursor()
     exit(0)
Пример #15
0
        def output(item):
            author = re.search(r'<h2>(.*?)</h2>', item[0], re.S)
            #text = re.search(r'(.*)', item[1], re.S)
            text = item[1]
            other_info = re.findall(r'<i.+?number">(\d+)</i>\s(\S+?)\s?<',
                                    item[2], re.S)

            term.writeLine(author.group(1), term.green, term.blink)
            term.writeLine(text.replace('<br/>', '\n').strip(), term.yellow)
            # do like this in case of no fun or comment
            for info in other_info:
                term.write(info[0] + info[1] + '\t', term.blue)
            else:
                print '\n'
Пример #16
0
 def handle(self):
     term.writeLine(
         "[*]New connection: {client}".format(client=self.client_address),
         term.green)
     self._get_token()
     while True:
         data = self.request.recv(1024)
         if not data: break
         data = data.decode()
         data = json.loads(data)
         payload = self.__send_payload(data)
         term.writeLine(
             "[*]PAYLOAD size: {size}".format(
                 size=len(payload[b'payload'])), term.green)
         self.request.send(payload[b'payload'])
Пример #17
0
class BeautyCLI(Cursor):

    def __init__(self, clear=True):
        if clear:
            tm.sleep(.25)
            self.cls()


    cls = lambda self: trm.clear()
    cls_ln = lambda self: trm.clearLine()
    fmt = lambda self, *args, **kwargs: trm.format(*args, **kwargs)
    wrt = lambda self, *args, **kwargs: trm.write(*args, **kwargs)
    wln = lambda self, *args, **kwargs: trm.writeLine(*args, **kwargs)
    right = lambda self, t: trm.right(t)
    center = lambda self, t: trm.center(t)


    def echo(self, text, row=None, col=None, align='left', *args):
        formated_text = text

        if align in 'right':
            formated_text = self.right(formated_text)
        elif align in 'center':
            formated_text = self.center(formated_text)

        if row is not None and col is not None:
            self.pos(row, col)
        elif row is not None and row is None:
            self.pos(row, 1)
        elif col is not None and row is None:
            self.pos(1, col)

        self.wln(formated_text, *args)
Пример #18
0
async def choose_book(books, book_file_path):
    def print_book(i, book):
        text = term.format("图书序号:", term.cyan, term.bold) \
               + term.format(i, term.red, term.bold) \
               + term.format(", 书名:%s" % book["title"], term.yellow, term.bold)
        print("====" * 10 + "<<<" * 3, text, ">>>" * 3 + "====" * 10)
        term.writeLine("||  title: %s" % book["title"], term.red)
        term.writeLine("||  subtitle: %s" % book["subtitle"], term.red)
        term.writeLine("||  authors: %s" % book["authors"], term.red)
        term.writeLine("||  tags: %s" % book["tags"], term.red)
        term.writeLine("||  rating: %s" % book["rating"], term.magenta)
        term.writeLine("||  star: %s" % book["star"], term.magenta)
        term.writeLine("||  num: %s" % book["num"], term.magenta)
        term.writeLine("||  price: %s" % book["price"], term.blue)
        term.writeLine("||  isbn: %s" % book["isbn"], term.blue)
        term.writeLine("||  publisher: %s" % book["publisher"], term.yellow)
        term.writeLine("||  date: %s" % book["date"], term.yellow)
        term.writeLine("||  series: %s" % book["series"], term.yellow)
        term.writeLine("||  comments: %s" % book["comments"], term.white)
        print("\n")

    # 打印书籍信息
    for i in range(len(books)):
        print_book(i, books[i])

    # 显示元数据信息
    return_code = await exec_command(book_file_path)
    debug("[choose book] 返回码: ", return_code)

    if return_code != 0:
        return None

    # 选择图书信息
    index = 0
    if len(books) > 0:
        text = term.format("\n\n请选择书籍元数据", term.red, term.bold) \
               + term.format("[0-%s]" % len(books), term.yellow, term.bold) \
               + term.format("之间的数字: ", term.red, term.bold)
        term.writeLine(text)
        index = int(input())
    book = books[index]

    term.writeLine("你选择了书籍:%s" % book["title"], term.blue, term.bold)
    print_book(index, book)

    return book
Пример #19
0
def show_images_statistics():
    """
    Iterate through all articles and find img tags in them
    """
    def find_missing(files):
        missing = []
        for filename in files:
            path_to_file = os.path.expanduser(
                    os.path.join(config.STATIC_FOLDER,
                                 filename.lstrip(os.path.sep)))
            if not os.path.exists(path_to_file):
                missing.append(filename)
        return missing

    all_posts = Post.select()
    parser = ImgParser()
    posts_affected = 0
    images_to_restore = 0
    for post in all_posts:
        parser.feed(post.post_text)
        if parser._captured_tags:
            images_in_post = len(parser._captured_tags)
            missing_images = len(find_missing(parser._captured_tags))
            term.write('Post #{post_id} has {images_count} images '.format(
                post_id=post.post_id,
                images_count=images_in_post
            ))
            if missing_images:
                term.writeLine('/ {missing_count} missing'.format(
                        missing_count=missing_images), term.yellow)
            else:
                term.writeLine('OK', term.green)
            parser.clear()
            posts_affected += 1
            images_to_restore += missing_images

    term.writeLine('Total posts with images %d' % posts_affected, term.bold)
    if images_to_restore:
        term.writeLine('Total images to restore %d' % images_to_restore,
                       term.red)
    else:
        term.writeLine('All posts are in good shape!', term.green)
Пример #20
0
def show_images_statistics():
    """
    Iterate through all articles and find img tags in them
    """
    def find_missing(files):
        missing = []
        for filename in files:
            path_to_file = os.path.expanduser(
                os.path.join(config.STATIC_FOLDER,
                             filename.lstrip(os.path.sep)))
            if not os.path.exists(path_to_file):
                missing.append(filename)
        return missing

    all_posts = Post.select()
    parser = ImgParser()
    posts_affected = 0
    images_to_restore = 0
    for post in all_posts:
        parser.feed(post.post_text)
        if parser._captured_tags:
            images_in_post = len(parser._captured_tags)
            missing_images = len(find_missing(parser._captured_tags))
            term.write('Post #{post_id} has {images_count} images '.format(
                post_id=post.post_id, images_count=images_in_post))
            if missing_images:
                term.writeLine(
                    '/ {missing_count} missing'.format(
                        missing_count=missing_images), term.yellow)
            else:
                term.writeLine('OK', term.green)
            parser.clear()
            posts_affected += 1
            images_to_restore += missing_images

    term.writeLine('Total posts with images %d' % posts_affected, term.bold)
    if images_to_restore:
        term.writeLine('Total images to restore %d' % images_to_restore,
                       term.red)
    else:
        term.writeLine('All posts are in good shape!', term.green)
Пример #21
0
def init_logging(config_service):
    log = logging.getLogger('my5t3ry.main')
    logging.basicConfig(level=logging.INFO)
    output = term.format(
        '=============================================      ', term.green
    ) + term.format('imFbAdapter 0.1', term.blue, term.bold) + term.format(
        '      =============================================\n\n ', term.green)
    term.writeLine(output)
    log.info("  === imgur root gallery: '" +
             str(config_service.config.get("rootImgurGallery")) + "' ===")
    log.info("  === facebook user: '******' ===")
    log.info("  === facebook post path: '" +
             str(config_service.config.get("postPath")) + "' ===")
    log.info("  === current pile consists of '" +
             str(len(os.listdir(config_service.config.get("tmpPicDir")))) +
             "' items ===")
    log.info("  === press ctrl + D to shutdown threads ===>")
    log.info("  === dump the shit away ===>\n\n")
    spinner = SpinnerService()
    spinner.start()
Пример #22
0
def create_tables():
    module_name = 'app.models'

    module_info = pyclbr.readmodule(module_name)
    db_models = []
    for value in module_info.itervalues():
        base = value.super[0]
        if hasattr(base, 'name') and base.name == 'BaseModel':
            db_models.append((value.lineno, value.name))

    # it is important to preserve order as declared in module
    # to prevent integrity errors
    for _, model in sorted(db_models):
        model_class = getattr(models, model)
        try:
            model_class.create_table()
            term.writeLine('Table for %s created.' %
                           model, term.green)
        except peewee.OperationalError as e:
            if e.args[0] == 1050:
                term.writeLine('%s already exists, skipping...' %
                               model, term.bold)
            else:
                raise e
    term.writeLine('Database successfully initialized for %s '
                   'models.' % len(db_models), term.green)
Пример #23
0
async def create_demo_users(loop=None):
    dbengine = await create_engine(user=settings.DB_USER,
                                   password=settings.DB_PASSWORD,
                                   database=settings.DATABASE,
                                   host=settings.DB_HOST)

    term.writeLine('Inserting users into database...')
    async with dbengine.acquire() as conn:
        await conn.execute(users.insert().values(
            id=1, login='******', password='******', is_superuser=True
        ))

        await conn.execute(users.insert().values(
            id=2, login='******', password='******'
        ))

        await conn.execute(users.insert().values(
            id=3, login='******', password='******'
        ))

    term.writeLine('Setting permissions on users...')
    async with dbengine.acquire() as conn:
        await conn.execute(permissions.insert().values(
            user_id=2, perm_name='protected'
        ))
        await conn.execute(permissions.insert().values(
            user_id=2, perm_name='public'
        ))
        await conn.execute(permissions.insert().values(
            user_id=3, perm_name='public'
        ))

    term.writeLine('All data has been inserted!', term.green)
Пример #24
0
 def validate(self):
     term.writeLine('Validating imgur media dump ...', term.green)
     try:
         str(len(os.listdir(self.config.get("tmpPicDir"))))
         term.writeLine('OK', term.green)
     except Exception as e:
         term.writeLine('Media folder not readable', term.red)
Пример #25
0
 def exec(i):
     target = targets[i]
     ret = None
     try:
         log_path = os.path.join(config.logs_dir, str(target))
         log = open(log_path, 'w')
         proc = target.run(cmd, timeout=timeout, stdout=log, stderr=log)
         if proc.returncode == 0:
             output = f'{term.green}SUCCESS{term.off} on {target}'
         else:
             output = f'{term.red}FAIL{term.off} on {target}. Exit code: {proc.returncode}'
         ret = proc
     except RunException as e:
         output = f'{term.red}FAIL{term.off} on {target}. Timeout'
         ret = e
     output += f'. Log: file://{log_path}'
     with l:
         term.saveCursor()
         term.up(len(targets) - i)
         term.clearLine()
         term.writeLine(output)
         term.restoreCursor()
     return ret
Пример #26
0
 def validate(self):
     term.writeLine('Validating Facebook credentials...', term.green)
     try:
         self.graph.get(self.config.get("postPath"))
         term.writeLine('OK', term.green)
     except:
         term.writeLine(
             'Facebook credentials and/or auth_token invalid. No facebook posts possible. Check => https://developers.facebook.com/tools/accesstoken/',
             term.red)
Пример #27
0
def create_folders(folders_list, base=''):
    for folder in folders_list:
        folder_path = folder['path']
        full_folder_path = os.path.join(base, folder_path)
        term.write('%s ' % full_folder_path)
        if not os.path.exists(folder_path):
            if folder.get('create'):
                os.makedirs(full_folder_path)
                term.writeLine('CREATED', term.yellow)
            else:
                term.writeLine('MISSING', term.red)
        else:
            term.writeLine('OK', term.green)
Пример #28
0
def create_folders(folders_list, base=''):
    for folder in folders_list:
        folder_path = folder['path']
        full_folder_path = os.path.join(base, folder_path)
        term.write('%s ' % full_folder_path)
        if not os.path.exists(folder_path):
            if folder.get('create'):
                os.makedirs(full_folder_path)
                term.writeLine('CREATED', term.yellow)
            else:
                term.writeLine('MISSING', term.red)
        else:
            term.writeLine('OK', term.green)
Пример #29
0
def report(graph, solutions):
    solution = solutions['solution']
    customer_solution_len = 0

    table_data = [[
        term.format('server', term.bold),
        term.format('level', term.bold),
        term.format('is_customer', term.bold),
        term.format('request', term.bold),
        term.format('degree', term.bold),
        term.format('cap / cost', term.bold),
    ]]

    for s in solution:
        if (graph.nodes[s[0]].request > 0):
            customer_solution_len = customer_solution_len + 1

        table_data.append([
            s[0], s[1], "yes" if graph.nodes[s[0]].request > 0 else "no",
            "%d (%d)" % (graph.nodes[s[0]].request,
                         graph.request_level(graph.nodes[s[0]].request))
            if graph.nodes[s[0]].request > 0 else 0,
            "%d / %d" % (len(graph.nodes[s[0]].edges), graph.max_degree),
            "%f (%d / %d)" %
            (float(graph.nodes[s[0]].cap_div_cost) /
             float(graph.max_cap_div_cost), graph.nodes[s[0]].cap_div_cost,
             graph.max_cap_div_cost)
        ])
    table = AsciiTable(table_data)

    term.writeLine('Statistical report for ' +
                   term.format(solutions['name'], term.green))
    term.writeLine('The optimum is ' +
                   term.format(solutions['optimum'], term.red, term.bold))
    term.writeLine('Customer server number: ' + term.format("%f ( %d / %d )" % \
     (float(customer_solution_len)/ float(len(solution)), customer_solution_len, len(solution)), term.red, term.bold))
    term.writeLine(table.table)
Пример #30
0
 def print_stats(self):
     term.writeLine("\n\tQuerySet #{}".format(self.queryset_id), term.bold)
     self._print_named_value("Instances created", self.instances_count)
     self._print_named_value("Model", self.model_name)
     self._print_fields_usage(self._wrapped_model_instances)
     self._print_traceback()
Пример #31
0
 def _print_named_value(self, label, value):
     term.write('\t')
     term.write(label + ':', term.underscore)
     term.writeLine(" {}".format(value))
Пример #32
0
poem = '''
这是一个喧嚣的世界
我从未感觉她安静过
她的繁荣 昌盛
给我们带来更多的疲惫和抱怨
我堵住双耳
不去听她疲惫 抱怨
也不去看她的饭桶 昌盛
我以为我的世界从此就安静了
可是
总有那么一个人
尽管她不曾对你有过一言一语
你却能听见她的声音
因为
她让你对明天有所期待
'''

import term 
import random

for line in poem.split('\n'):
    colors = [term.red,term.green,term.yellow,term.blue]
    mode = [term.bold,term.dim,term.underscore,term.blink,term.reverse]
    term.writeLine(line.strip(),random.choice(colors),random.choice(mode))
Пример #33
0
 def print_book(i, book):
     text = term.format("图书序号:", term.cyan, term.bold) \
            + term.format(i, term.red, term.bold) \
            + term.format(", 书名:%s" % book["title"], term.yellow, term.bold)
     print("====" * 10 + "<<<" * 3, text, ">>>" * 3 + "====" * 10)
     term.writeLine("||  title: %s" % book["title"], term.red)
     term.writeLine("||  subtitle: %s" % book["subtitle"], term.red)
     term.writeLine("||  authors: %s" % book["authors"], term.red)
     term.writeLine("||  tags: %s" % book["tags"], term.red)
     term.writeLine("||  rating: %s" % book["rating"], term.magenta)
     term.writeLine("||  star: %s" % book["star"], term.magenta)
     term.writeLine("||  num: %s" % book["num"], term.magenta)
     term.writeLine("||  price: %s" % book["price"], term.blue)
     term.writeLine("||  isbn: %s" % book["isbn"], term.blue)
     term.writeLine("||  publisher: %s" % book["publisher"], term.yellow)
     term.writeLine("||  date: %s" % book["date"], term.yellow)
     term.writeLine("||  series: %s" % book["series"], term.yellow)
     term.writeLine("||  comments: %s" % book["comments"], term.white)
     print("\n")
Пример #34
0
async def modify_meta(file, page):

    exception_files = []

    async def book_metadata(book_file, book_file_path):
        book_name = book_file.split(".")[0]

        books = await request_book(book_name, page)
        if not books:
            exception_files.append(book_file_path)
            return None

        book = await choose_book(books, book_file_path)
        debug("[modify meta] book: %s\n" % book)

        metadata = [
            "-t",
            book["title"],
            "-a",
            book["authors"],
            "-c",
            book["comments"],
            "-s",
            book["series"],
            "--identifier",
            "isbn:" + book["isbn"],
            "--isbn",
            book["isbn"],
            "--tags",
            book["tags"],
            "-p",
            book["publisher"],
            "-d",
            book["date"],
            "-r",
            str(int(book["star"]) * 0.1),
        ]
        return_code = await exec_command(book_file_path, *metadata)
        debug("[modify meta] 返回码: ", return_code)

        if return_code != 0:
            exception_files.append(book_file_path)
        else:
            info("[modify meta] 编辑图书元数据成功: ", book_file_path)
            rename_book({book_file_path: book})

    if not os.path.exists(file):
        info("[modify meta] 文件或目录不存在:", file)
    else:
        if os.path.isfile(file):
            await book_metadata(os.path.basename(file), file)
        else:
            for root, dirs, files in os.walk(file):
                for item in files:
                    term.writeLine("发现新文件: %s" % item, term.yellow,
                                   term.underscore)
                    file_path = os.path.join(root, item)
                    await book_metadata(item, file_path)
                    term.writeLine("\n\n\n" + "####" * 30, term.cyan)

    if exception_files:
        info("[modify meta] 元数据修改无效的图书: ", exception_files)
Пример #35
0
exchange = 'BTC'
coin = 'ETN'

symbol = '{}/{}'.format(coin, exchange)

# book = api.fetch_order_book(symbol, limit=10)
#
# asks, bids = book['asks'], book['bids']
# df_asks = pd.DataFrame(asks, columns=cols)
# df_bids = pd.DataFrame(bids, columns=cols)

tm.sleep(.25), trm.clear(), trm.pos(1, 1)
api = cryptopia()
while True:
    try:
        sep = lambda: trm.writeLine(trm.center('-' * 80), trm.dim, trm.cyan)
        book = api.fetch_order_book(symbol, limit=5)

        asks, bids = book['asks'], book['bids']
        df_asks = pd.DataFrame(asks, columns=cols)
        df_bids = pd.DataFrame(bids, columns=cols)
        df_asks['amount'] = df_asks['amount'].apply(
            lambda v: '{: >16.2f}'.format(v))
        df_asks['price'] = df_asks['price'].apply(
            lambda v: '{: >16.8f}'.format(v))
        df_bids['amount'] = df_bids['amount'].apply(
            lambda v: '{: >16.2f}'.format(v))
        df_bids['price'] = df_bids['price'].apply(
            lambda v: '{: >16.8f}'.format(v))
        book_join = [[*ask, *bid]
                     for ask, bid in zip(df_bids.values, df_asks.values)]