Ejemplo n.º 1
0
    def child(kind):
        from blessed import Terminal
        term = Terminal(kind)
        test_right_string = term.blue(u"one" + term.move_right(5) + u"two")
        assert term.truncate(test_right_string, 9) == term.blue(u"one     t")

        test_bs_string = term.blue(u"one\b\b\btwo")
        assert term.truncate(test_bs_string, 3) == term.blue(u"two")
Ejemplo n.º 2
0
 def child(kind):
     from blessed import Terminal
     term = Terminal(kind)
     test = "Testing " + term.red("attention ") + term.blue("please.")
     trunc = term.truncate(test)
     assert term.length(trunc) <= term.width
     assert term.truncate(term.red('x' * 1000)) == term.red('x' * term.width)
Ejemplo n.º 3
0
    def child(kind):
        from blessed import Terminal
        term = Terminal(kind)

        test_string = term.red("Testing ") + term.yellow("makes ") +\
            term.green("me ") + term.blue("feel ") +\
            term.indigo("good") + term.normal
        stripped_string = term.strip_seqs(test_string)
        for i in range(len(stripped_string)):
            test_l = term.length(term.truncate(test_string, i))
            assert test_l == len(stripped_string[:i])
        test_nogood = term.red("Testing ") + term.yellow("makes ") +\
            term.green("me ") + term.blue("feel ") +\
            term.indigo("") + term.normal
        trunc = term.truncate(test_string, term.length(test_string) - len("good"))
        assert trunc == test_nogood
Ejemplo n.º 4
0
def day(args, *extra, **kwargs):
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'username',
        help='The MyFitnessPal username for which to delete a stored password.'
    )
    parser.add_argument(
        'date',
        nargs='?',
        default=datetime.now().strftime('%Y-%m-%d'),
        type=lambda datestr: dateparse(datestr).date(),
        help='The date for which to display information.'
    )
    args = parser.parse_args(extra)

    password = get_password_from_keyring_or_interactive(args.username)
    client = Client(args.username, password)
    day = client.get_date(args.date)

    t = Terminal()

    print(t.blue(args.date.strftime('%Y-%m-%d')))
    for meal in day.meals:
        print(t.bold(meal.name.title()))
        for entry in meal.entries:
            print('* {entry.name}'.format(entry=entry))
            print(
                t.italic_bright_black(
                    '  {entry.nutrition_information}'.format(entry=entry)
                )
            )
        print('')

    print(t.bold("Totals"))
    for key, value in day.totals.items():
        print(
            '{key}: {value}'.format(
                key=key.title(),
                value=value,
            )
        )
    print("Water: {amount}".format(amount=day.water))
    if day.notes:
        print(t.italic(day.notes))
Ejemplo n.º 5
0
def day(args, *extra, **kwargs):
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'username',
        help='The MyFitnessPal username for which to delete a stored password.'
    )
    parser.add_argument('date',
                        nargs='?',
                        default=datetime.now().strftime('%Y-%m-%d'),
                        type=lambda datestr: dateparse(datestr).date(),
                        help=u'The date for which to display information.')
    args = parser.parse_args(extra)

    password = get_password_from_keyring_or_interactive(args.username)
    client = Client(args.username, password)
    day = client.get_date(args.date)

    t = Terminal()

    print(t.blue(args.date.strftime('%Y-%m-%d')))
    for meal in day.meals:
        print(t.bold(meal.name.title()))
        for entry in meal.entries:
            print(u'* {entry.name}'.format(entry=entry))
            print(
                t.italic_bright_black(
                    u'  {entry.nutrition_information}'.format(entry=entry)))
        print(u'')

    print(t.bold("Totals"))
    for key, value in day.totals.items():
        print(u'{key}: {value}'.format(
            key=key.title(),
            value=value,
        ))
    print(u'Water: {amount}'.format(amount=day.water))
    if day.notes:
        print(t.italic(day.notes))
Ejemplo n.º 6
0
import random

from blessed import Terminal

# CONSTANTS
COLUMNS = 7
ROWS = 6

# Terminal
t = Terminal()

# Player colors
# 0 is empty
pcolor = {
    0: lambda x: t.white(x),
    1: lambda x: t.blue(x),
    2: lambda x: t.red(x)
}


def put_disc(board, player, column):
    """
    Puts a disc of player `player` in column `column`.
    Returns `False` if the column is full.
    """
    row = -1
    column -= 1
    while board[row][column]:
        row -= 1
        if row < -ROWS:
            return False
Ejemplo n.º 7
0
        return text


try:
    from blessed import Terminal
except ImportError, exc:
    Terminal = FakeTerminal


TERMINAL = Terminal()
FLAGS = {
    'done': TERMINAL.green('done'),
    'orphan': TERMINAL.standout(TERMINAL.red('ORPHAN')),
    'outdated_fs_version': TERMINAL.standout(
        TERMINAL.red('FS-VERSION-OUTDATED')),
    'deferrable': TERMINAL.standout(TERMINAL.blue('DEFERRABLE')),
    'proposed': TERMINAL.blue('proposed')}


def print_table(data, titles=None, colspace=1):
    if titles:
        data.insert(0, map(TERMINAL.bright_black, titles))

    column_lengths = map(max, zip(*map(
                lambda row: map(TERMINAL.length, row), data)))
    for row in data:
        for col_num, cell in enumerate(row):
            print TERMINAL.ljust(cell, column_lengths[col_num] + colspace),
        print ''

Ejemplo n.º 8
0
try:
    from blessed import Terminal
except ImportError, exc:
    import sys
    print >>sys.stderr, 'WARNING: Terminal colorization disabled' + \
        ' because of ImportError: {0}'.format(exc)
    Terminal = FakeTerminal


TERMINAL = Terminal()
FLAGS = {
    'done': TERMINAL.green('done'),
    'orphan': TERMINAL.standout(TERMINAL.red('ORPHAN')),
    'outdated_fs_version': TERMINAL.standout(
        TERMINAL.red('FS-VERSION-OUTDATED')),
    'proposed': TERMINAL.blue('proposed')}


def print_table(data, titles=None, colspace=1):
    if titles:
        data.insert(0, map(TERMINAL.bright_black, titles))

    column_lengths = map(max, zip(*map(
                lambda row: map(TERMINAL.length, row), data)))
    for row in data:
        for col_num, cell in enumerate(row):
            print TERMINAL.ljust(cell, column_lengths[col_num] + colspace),
        print ''


def upgrade_id_with_flags(upgrade, omit_flags=()):
Ejemplo n.º 9
0
 def child(kind):
     from blessed import Terminal
     term = Terminal(kind)
     assert term.truncate("", 4) == ""
     test_string = term.blue(u"one\x01two")
     assert term.truncate(test_string, 4) == term.blue(u"one\x01t")
Ejemplo n.º 10
0
class UI():
    def __init__(self):
        self.term = Terminal()
        self.choice = None
    def drawtop(self):
        print(self.term.green('=============================='))
        print(self.term.green('       HUNT THE WUMPUS'))
        print(self.term.green('=============================='))
        
    def mainmenu(self):
        print('\nPRESS ANY KEY + INTRO TO START:')
        input()
        self.clear_screen()
    
    def ingame(self, player):
        print('I am in row %d and column number %d' % \
              (player.row_position, player.column_position))
        if player.orientation == 1:
            print('I am looking up.')
        elif player.orientation == 2:
            print('I am looking to the right.')
        elif player.orientation == 3:
            print('I am looking down.')
        elif player.orientation == 4:
            print('I am looking to the left.')
        print('I have %d arrows' % player.n_arrows)
        if player.wumpus_alive:
            print('The Wumpus is still alive')
        else:
            print(self.term.green('The Wumpus is dead.'))
        if player.gold_in_bag:
            print(self.term.yellow('I have a piece of gold.'))
        
        exit_position = player.row_position == 0 and player.column_position == 0
        self.choice = None
        while self.choice is None:
            if exit_position and player.gold_in_bag:
                print('What should I do now? I can "MOVE" fordward, turn "CLOCKWISE", turn "COUNTERCLOCKWISE",\
                  "SHOOT" or "EXIT"')
            else:    
                print('What should I do now? I can "MOVE" fordward, turn "CLOCKWISE", turn "COUNTERCLOCKWISE",\n \
                  or "SHOOT"')
            self.choice = input('Type an action: ')
            print(self.choice)
            if self.choice in actions_list:
                return self.choice
            elif self.choice == 'EXIT':
                if exit_position and player.gold_in_bag:
                    self.game_won()
                else:
                    self.choice = None
                    print(self.term.yellow('I can`t exit now. I must be in the initial position with the gold.'))
            else:
                self.choice = None
                print('I don`t understand!')
               
        
    def sensing_info(self, sensing_data):
        for data in sensing_data:
            if data == 1:
                print(self.term.blue(sense_msg['wumpus_close']))
            elif data == 2:
                print(self.term.blue(sense_msg['gold_close']))
            elif data == 3:
                print(self.term.blue(sense_msg['hole_close']) )
    
    def display_msg(self, msg_ref):
        print(self.term.yellow(sense_msg[msg_ref]))
        
    def game_won(self):
        print(self.term.green('CONGRATULATIONS YOU PASS DE THE LEVEL\nPRESS ANY KEY + INTRO TO EXIT:'))
        input()
        os.exit()
        
    def game_over(self, circumstance):
        if circumstance == 1:
            print(self.term.red(sense_msg['wumpus_death']))
        else:
            print(self.term.red(sense_msg['hole_death']))   
        print(self.term.red('\nPRESS ANY KEY + INTRO TO EXIT:'))
        input()
        os.exit()
    
    def clear_screen(self):
        os.system('cls' if os.name=='nt' else 'clear')
        self.drawtop()
Ejemplo n.º 11
0
    def __call__(self, text):
        return text


try:
    from blessed import Terminal
except ImportError, exc:
    Terminal = FakeTerminal

TERMINAL = Terminal()
FLAGS = {
    'done': TERMINAL.green('done'),
    'orphan': TERMINAL.standout(TERMINAL.red('ORPHAN')),
    'outdated_fs_version':
    TERMINAL.standout(TERMINAL.red('FS-VERSION-OUTDATED')),
    'proposed': TERMINAL.blue('proposed')
}


def print_table(data, titles=None, colspace=1):
    if titles:
        data.insert(0, map(TERMINAL.bright_black, titles))

    column_lengths = map(
        max, zip(*map(lambda row: map(TERMINAL.length, row), data)))
    for row in data:
        for col_num, cell in enumerate(row):
            print TERMINAL.ljust(cell, column_lengths[col_num] + colspace),
        print ''

Ejemplo n.º 12
0
    def __call__(self, text):
        return text


try:
    from blessed import Terminal
except ImportError, exc:
    Terminal = FakeTerminal


TERMINAL = Terminal()
FLAGS = {
    "done": TERMINAL.green("done"),
    "orphan": TERMINAL.standout(TERMINAL.red("ORPHAN")),
    "outdated_fs_version": TERMINAL.standout(TERMINAL.red("FS-VERSION-OUTDATED")),
    "proposed": TERMINAL.blue("proposed"),
}


def print_table(data, titles=None, colspace=1):
    if titles:
        data.insert(0, map(TERMINAL.bright_black, titles))

    column_lengths = map(max, zip(*map(lambda row: map(TERMINAL.length, row), data)))
    for row in data:
        for col_num, cell in enumerate(row):
            print TERMINAL.ljust(cell, column_lengths[col_num] + colspace),
        print ""


def upgrade_id_with_flags(upgrade, omit_flags=()):
Ejemplo n.º 13
0
def threaded_sniff():
    q = Queue()
    sniffer = Thread(target = threaded_sniff_target, args = (q,))
    sniffer.daemon = True
    sniffer.start()
    time.sleep(1)
    t = Terminal()
    pkt_type = ""
    ip_src = None
    
    while True:
        try:
            pkt = q.get(timeout = 1)
            if pkt.haslayer(Ether):
                ethsrc = pkt.getlayer(Ether).src
                ethdst = pkt.getlayer(Ether).dst
            else:
                # Skip non-Ethernet packets
                pass
            if pkt.haslayer(IP):
                ipsrc = pkt.getlayer(IP).src
                ipdst = pkt.getlayer(IP).dst
                ttl = pkt.getlayer(IP).ttl
            else:
                # Skip non-IP packets
                pass
            if pkt.haslayer(TCP):
                sport = pkt.getlayer(TCP).sport
                dport = pkt.getlayer(TCP).dport
                pkt_type = "TCP"
            elif pkt.haslayer(UDP):
                sport = pkt.getlayer(UDP).sport
                dport = pkt.getlayer(UDP).dport
                pkt_type = "UDP"
                
            if pkt.haslayer(DNS):
                pkt_type = "DNS"

            if pkt.haslayer(NTP):
                pkt_type = "NTP"
                
            if pkt.haslayer(ICMP):
                pkt_type = "ICMP"
                
            if pkt.haslayer(http.HTTP):
                pkt_type = "HTTP"
                
            if pkt.haslayer(TLS):
                pkt_type = "TLS"
                
            if not dbconn.isipaddrindb(ipsrc):
                # OS detection based on TTL
                ret_ttl = getttl(ttl)
                if ret_ttl is None:
                    if pkt.haslayer(TCP) or pkt.haslayer(UDP):
                        print "T", t.blue("%s" % datetime.datetime.now().strftime('%H:%M:%S')), t.bold_magenta("{:>4}".format(pkt_type)), "MAC src addr", t.cyan("%s" % ethsrc), "MAC dst addr", t.cyan("%s" % ethdst), "TTL", t.red("{:>7}".format(ttl)), "IP src addr", t.green("{:>15}".format(ipsrc)), "IP dst addr", t.green("{:>15}".format(ipdst)), "src port", t.yellow("{:>5}".format(sport)), "dst port",  t.yellow("{:>5}".format(dport))
                    elif pkt.haslayer(ICMP):
                        print "T", t.blue("%s" % datetime.datetime.now().strftime('%H:%M:%S')), t.bold_magenta("{:>4}".format(pkt_type)), "MAC src addr", t.cyan("%s" % ethsrc), "MAC dst addr", t.cyan("%s" % ethdst), "TTL", t.red("{:>7}".format(ttl)), "IP src addr", t.green("{:>15}".format(ipsrc)), "IP dst addr", t.green("{:>15}".format(ipdst))
                        if pkt.getlayer(ICMP).type == 0x08:
                            print t.move_right, t.move_right, t.move_right, t.move_right, "ICMP Message type", t.green("Echo request"), "Sequence number", t.cyan("%s" % pkt.getlayer(ICMP).seq)
                        elif pkt.getlayer(ICMP).type == 0x00:
                            print t.move_right, t.move_right,t.move_right, t.move_right, "ICMP Message type", t.green("Echo response"), "Sequence number", t.cyan("%s" % pkt.getlayer(ICMP).seq)
                else:
                    if pkt.haslayer(TCP) or pkt.haslayer(UDP):
                        print "T", t.blue("%s" % datetime.datetime.now().strftime('%H:%M:%S')), t.bold_magenta("{:>4}".format(pkt_type)), "MAC src addr", t.cyan("%s" % ethsrc), "MAC dst addr", t.cyan("%s" % ethdst), "OSv", t.red("%s" % ret_ttl), "IP src addr", t.green("{:>15}".format(ipsrc)), "IP dst addr", t.green("{:>15}".format(ipdst)), "src port", t.yellow("{:>5}".format(sport)), "dst port",  t.yellow("{:>5}".format(dport))
                    elif pkt.haslayer(ICMP):                        
                        print "T", t.blue("%s" % datetime.datetime.now().strftime('%H:%M:%S')), t.bold_magenta("{:>4}".format(pkt_type)), "MAC src addr", t.cyan("%s" % ethsrc), "MAC dst addr", t.cyan("%s" % ethdst), "OSv", t.red("%s" % ret_ttl), "IP src addr", t.green("{:>15}".format(ipsrc)), "IP dst addr", t.green("{:>15}".format(ipdst))
                        if pkt.getlayer(ICMP).type == 0x08:
                            print t.move_right, t.move_right,t.move_right, t.move_right, "ICMP Message type", t.green("Echo request"), "Sequence number", t.cyan("%s" % pkt.getlayer(ICMP).seq)
                        elif pkt.getlayer(ICMP).type == 0x00:
                            print t.move_right, t.move_right,t.move_right, t.move_right, "ICMP Message type", t.green("Echo response"), "Sequence number", t.cyan("%s" % pkt.getlayer(ICMP).seq)
                # Print out additional information if the packet contains HTTP requests or responses
                if pkt.haslayer(DNS):
                    dns_layer = pkt.getlayer(DNS)
                    if 'an' in dns_layer.fields:
                        if dns_layer.fields['an'] is not None:
                            if dns_layer.fields['an'].fields['type'] == 0x01:
                                print t.move_right, t.move_right, "DNS response", t.yellow("A"), "record for hostname", t.cyan("%s" % dns_layer.fields['an'].fields['rrname'][:-1]), "has IP address", t.green("%s" % str(dns_layer.fields['an'].fields['rdata']))
                        elif 'qd' in dns_layer.fields:
                            if dns_layer.fields['qd'].fields['qtype'] == 0x01:
                                print t.move_right, t.move_right, "DNS request", t.yellow("A"), "record for hostname", t.cyan("%s" % dns_layer.fields['qd'].fields['qname'][:-1])

                # Print out additional information if the packet contains HTTP requests or responses
                if pkt.haslayer(http.HTTPRequest):
                    http_pkt = pkt.getlayer(http.HTTPRequest)
                    print t.move_right, t.move_right, "HTTP Method", t.yellow("%s" % http_pkt.fields['Method']), "Host", t.cyan("%s" % http_pkt.fields['Host']), "Path", t.green("%s" % http_pkt.fields['Path']),"User-Agent", t.blue("%s" % http_pkt.fields['User-Agent'])
                elif pkt.haslayer(http.HTTPResponse):
                    http_pkt = pkt.getlayer(http.HTTPResponse)
                    try:
                        print t.move_right, t.move_right, "HTTP Response from", t.green("%s" % http_pkt.fields['Server']), "Date", t.yellow("%s" % http_pkt.fields['Date'])
                    except:
                        pass
                        
                # Print out additional information if the packet is part of a TLS connection
                if pkt.haslayer(TLS):
                    try:
                        tls_packet = pkt.getlayer(TLS)
                        tls_record = tls_packet.fields['records'][0]
                        tls_record_type = tls_packet.fields['records'][0].fields['content_type']
                        if tls_record_type == 0x17:
                            try:
                                tls_version = tls_record['TLS Record'].fields['version']
                                if tls_version == 0x303:
                                    print t.move_right, t.move_right,t.move_right, t.move_right, "Application Data from TLS version", t.yellow("v1.2")
                                elif tls_version == 0x302:
                                    print t.move_right, t.move_right,t.move_right, t.move_right, "Application Data from TLS version", t.yellow("v1.1")
                                elif tls_version == 0x301:
                                    print t.move_right, t.move_right,t.move_right, t.move_right, "Application Data from TLS version", t.yellow("v1.0")
                                elif tls_version == 0x300:
                                    print t.move_right, t.move_right,t.move_right, t.move_right, "Application Data from SSL version", t.yellow("v3.0")
                            except:
                                pass
                        elif tls_record_type == 0x16:
                            for rec in tls_packet.fields['records']:
                                try:
                                    # ClientHello
                                    if rec['TLS Handshake'].fields['type'] == 1:
                                        #print rec['TLS Client Hello'].fields['version']
                                        tls_clienthello_version = tls_record['TLS Client Hello'].fields['version']
                                        if tls_clienthello_version == 0x303:
                                            print t.move_right, t.move_right, "Client Hello version", t.yellow("v1.2")
                                        elif tls_clienthello_version == 0x302:
                                            print t.move_right, t.move_right, "Client Hello version", t.yellow("v1.1")
                                        elif tls_clienthello_version == 0x301:
                                            print t.move_right, t.move_right, "Client Hello version", t.yellow("v1.0")
                                        elif tls_clienthello_version == 0x300:
                                            print t.move_right, t.move_right, "Client Hello version", t.yellow("v3.0")
                                    # ServerHello
                                    elif rec['TLS Handshake'].fields['type'] == 2:
                                        #print rec['TLS Server Hello'].fields['version']
                                        tls_serverhello_version = tls_record['TLS Server Hello'].fields['version']
                                        if tls_serverhello_version == 0x303:
                                            print t.move_right, t.move_right, "Server Hello version", t.yellow("v1.2")
                                        elif tls_serverhello_version == 0x302:
                                            print t.move_right, t.move_right, "Server Hello version", t.yellow("v1.1")
                                        elif tls_serverhello_version == 0x301:
                                            print t.move_right, t.move_right, "Server Hello version", t.yellow("v1.0")
                                        elif tls_serverhello_version == 0x300:
                                            print t.move_right, t.move_right, "Server Hello version", t.yellow("v3.0")
                                except:
                                    pass
                    except:
                        pass
            else:
                dbconn.refreshtimestamp(ethsrc)
        except Empty:
            pass