Example #1
0
def create_repository(project_name, description, organization=None):
    if not have_credentials():
        puts('{0}. {1}'.format(colored.blue('octogit'),
            colored.red('in order to create a repository, you need to login.')))
        sys.exit(1)

    if local_already(project_name):
        sys.exit(1)
    post_dict = {'name': project_name, 'description': description, 'homepage': '', 'private': False, 'has_issues': True, 'has_wiki': True, 'has_downloads': True}
    if organization:
        post_url = 'https://api.github.com/orgs/{0}/repos'.format(organization)
    else:
        post_url = 'https://api.github.com/user/repos'
    r = requests.post(post_url, headers=get_headers(), data=json.dumps(post_dict))
    if r.status_code == 201:
        if organization:
            create_local_repo(organization, project_name)
        else:
            create_local_repo(get_username(), project_name)
    else:
        # Something went wrong
        post_response = json.loads(r.content)
        errors = post_response.get('errors')
        if errors and errors[0]['message'] == 'name already exists on this account':
            puts('{0}. {1}'.format(colored.blue('octogit'),
                colored.red('repository named this already exists on github')))
        else:
            puts('{0}. {1}'.format(colored.blue('octogit'),
                colored.red('something went wrong. perhaps you need to login?')))
            sys.exit(-1)
Example #2
0
    def _write_load_config_sh(self, environments_dir, quiet):
        puts(colored.blue("Let's get you set up to run commcare-cloud."))

        if not environments_dir:
            environments_dir = self._determine_environments_dir(quiet=quiet)

        commcare_cloud_dir = os.path.expanduser("~/.commcare-cloud")
        if not os.path.exists(commcare_cloud_dir):
            os.makedirs(commcare_cloud_dir)
        load_config_file = os.path.expanduser("~/.commcare-cloud/load_config.sh")
        if not os.path.exists(load_config_file) or \
                ask("Overwrite your ~/.commcare-cloud/load_config.sh?", quiet=quiet):
            with open(load_config_file, 'w') as f:
                f.write(textwrap.dedent("""
                    # auto-generated with `manage-commcare-cloud configure`:
                    export COMMCARE_CLOUD_ENVIRONMENTS={COMMCARE_CLOUD_ENVIRONMENTS}
                    export PATH=$PATH:{virtualenv_path}
                    source {PACKAGE_BASE}/.bash_completion
                """.format(
                    COMMCARE_CLOUD_ENVIRONMENTS=shlex_quote(environments_dir),
                    virtualenv_path=get_virtualenv_bin_path(),
                    PACKAGE_BASE=PACKAGE_BASE,
                )).strip())
        puts(colored.blue("Add the following to your ~/.bash_profile:"))
        puts(colored.cyan("source ~/.commcare-cloud/load_config.sh"))
        puts(colored.blue(
            "and then open a new shell. "
            "You should be able to run `commcare-cloud` without entering your virtualenv."))
Example #3
0
def get_gists(user):
	github_gists_url = 'https://api.github.com/users/%s/gists' % (user)
	gists = requests.get(github_gists_url)
	try:
		data = json.loads(gists.content)
	except ValueError:
		raise ValueError(gists.content)
	
	for gist in data:
		width = [[colored.yellow('#'+str(gist['id'])), 2],]
		width.append(['{0}'.format(gist['description']), 70])
	
		if len(gist['files']) == 1:
			for file in gist['files']:
				width.append([colored.blue("size:"), 6])
				width.append(["{0}".format(gist['files'][file]['size']), 8])
				width.append([colored.blue("language:"), 10])
				width.append(["{0}".format(gist['files'][file]['language']), 15])
	
		print columns(*width)
		
		if (len(gist['files']) != 1):
			for file in gist['files']:
				width = [["",2]]
				width.append([colored.blue("file:"), 6])
				width.append([file, 25])
				width.append([colored.blue("size:"), 6])
				width.append(["{0}".format(gist['files'][file]['size']), 6])
				width.append([colored.blue("language:"), 10])
				width.append(["{0}".format(gist['files'][file]['language']), 10])
				print columns(*width)
Example #4
0
 def stop(conn, selection):
     error = col.red('error')
     name = col.magenta(conn.get_robot_name())
     if selection:
         s = col.blue(selection)
     if ns.service:
         if conn.stop_service(selection):
             print('stopped {} service on {}'.format(s, name))
         else:
             print('{}: failed to stop service {} on {}'.
                   format(error, s, name))
     elif ns.behavior:
         if conn.stop_behavior(selection):
             print('stopped {} behavior on {}'.format(s, name))
         else:
             print('{}: {} is not installed on {}'.format(error, s, name))
     else:
         focused = conn.get_focused_activity()
         if not focused:
             print('{}: there is no focused activity on {}'.format(error, name))
         else:
             focused = col.blue(focused)
             if conn.life_stop_focus():
                 print('stopped {} on {}'.format(focused, name))
             elif conn.life_stop_focus():
                 print('stopped {} on {}'.format(focused, name))
             else:
                 print('{}: failed to stop focused activity on {}'.
                       format(error, name))
Example #5
0
 def download_jfsfile(remote_object, tofolder=None, checksum=False):
     'Helper function to get a jfsfile and store it in a local folder, optionally checksumming it. Returns boolean'
     if tofolder is None:
         tofolder = '.' # with no arguments, store in current dir
     total_size = remote_object.size
     if remote_object.state in (JFS.ProtoFile.STATE_CORRUPT, JFS.ProtoFile.STATE_INCOMPLETE):
         puts(colored.red('%s was NOT downloaded successfully - Incomplete file' % remote_file.name))
         return False
     topath = os.path.join(tofolder, remote_object.name)
     with open(topath, 'wb') as fh:
         bytes_read = 0
         puts(colored.white('Downloading: %s, size: %s \t' % (remote_object.name, 
                                                              print_size(total_size, humanize=True))))   
         with ProgressBar(expected_size=total_size) as bar:
             for chunk_num, chunk in enumerate(remote_object.stream()):
                 fh.write(chunk)
                 bytes_read += len(chunk)
                 bar.show(bytes_read)
     if checksum:
         md5_lf = JFS.calculate_md5(open(topath, 'rb'))
         md5_jf = remote_object.md5
         logging.info('%s - Checksum for downloaded file' % md5_lf)
         logging.info('%s - Checksum for server file' % md5_jf)
         if md5_lf != md5_jf:
             puts(colored.blue('%s - Checksum for downloaded file' % md5_lf))
             puts(colored.blue('%s - Checksum for server file' % md5_jf))
             puts(colored.red('%s was NOT downloaded successfully - cheksum mismatch' % remote_object.name))
             return False
         puts(colored.green('%s was downloaded successfully - checksum  matched' % remote_object.name))
     return True
Example #6
0
    def main(self, target):
        minions = self.parent.client.cmd(target, 'test.ping')

        if len(minions) == 0:
            puts(colored.red("No up minions matching, abort!"))
            sys.exit(1)

        for minion in minions:
            puts(colored.blue("=" * 10))
            puts(colored.blue("Minion: %s" % minion))

            puts(colored.blue("Starting healthchecks on %s" % minion))
            health_checks_result = self.parent.client.cmd(minion,
                    'state.top', 9999999999, 'healthcheck_top.sls')[minion]
            x = _format_host(minion, health_checks_result)
            print x[0]
            success = parse_result(health_checks_result)

            if not success:
                puts()
                puts(colored.red("Healthchecks has failed on minion %s"
                                 % minion))
            else:
                puts()
                puts(colored.green("Healthchecks success on minion %s"
                                   % minion))
Example #7
0
  def get_acc_balance(self):
    query_result = self.get_data(self.balance_url)
    # print json.dumps(query_result['response'], indent=2)
    print colored.blue('Account Balance')
    print 'Account value: \t' + query_result['response']['accountbalance']['accountvalue']
    print colored.yellow('securities:')
    # print json.dumps(query_result['response']['accountbalance']['securities'], indent=2)
    securities = query_result['response']['accountbalance']['securities']
    print 'total:   \t' + securities['total']
    print 'stocks:  \t' + securities['stocks']
    print 'options: \t' + securities['options']
    print colored.yellow('money:')
    # print json.dumps(query_result['response']['accountbalance']['money'], indent=2)
    money = query_result['response']['accountbalance']['money']
    print 'total:   \t' + money['total']
    print 'cash:    \t' + money['cash']
    print 'marginbalance: \t' + money['marginbalance']
    print colored.yellow('buyingpower:')
    if 'buyingpower' in query_result['response']['accountbalance']:
      # print json.dumps(query_result['response']['accountbalance']['buyingpower'], indent=2)
      buyingpower = query_result['response']['accountbalance']['buyingpower']
      print 'cash:    \t' + buyingpower['cashavailableforwithdrawal']
      print 'stock:   \t' + buyingpower['stock']
      print 'options: \t' + buyingpower['options']

    print '----------------------------------------------------------------'
    return
Example #8
0
 def get_acc_holdings(self):
   query_result = self.get_data(self.holdings_url)
   holdings = query_result['response']['accountholdings']['holding']
   print colored.blue('Account Holdings')
   unrealized_total_gl = 0
   # TODO bundle the data in JSON
   for holding in holdings:
     symbol = holding['instrument']['sym']
     costbasis = float(holding['costbasis'])
     marketvalue = float(holding['marketvalue'])
     quantity = int(float(holding['qty']))
     price = float(holding['price'])
     base_price = round((costbasis/quantity), 2)
     unrealized_gl = marketvalue-costbasis
     print colored.yellow(symbol)
     print 'cost-basis:  ',costbasis,'base price:   ', base_price,'shares:',quantity
     print 'market-value:',marketvalue,'current price:',price
     if (unrealized_gl >= 0):
       print 'gain/loss:   ', colored.green(unrealized_gl)
     else:
       print 'gain/loss:   ', colored.red(unrealized_gl)
     unrealized_total_gl += unrealized_gl
   if (unrealized_total_gl >= 0):
     print colored.yellow('Total unrealized gain/loss: '), colored.green(unrealized_total_gl)
   else:
     print colored.yellow('Total unrealized gain/loss: '), colored.red(unrealized_total_gl)
   print '----------------------------------------------------------------'
   return
Example #9
0
    def run_command(cls, *args):
        requested_keys = { k: True for k in args[0]}.keys()
        all_supported_keys = [x for x in requested_keys if x in supported_commands]

        if len(all_supported_keys):
            # command(s) specified, print help for specified command
            valid_help_keys = all_supported_keys

            print colored.magenta('Parameters can be specified in order they should appear')
            print colored.magenta('Arguments can be specified with "=" between key and value')
            print colored.magenta('\te.g.\tevents 12 venue.state=NY')
            print colored.magenta('\t[PARAMS]: 12 \t [ARGS]: { "venue.state": "NY" }')

            for key in valid_help_keys:
                if key == "help":
                    print colored.cyan('  [%s] takes any of the following arguments' % key)
                    all_args = [x for x in supported_commands.keys() if x != "help"]
                    pprint(all_args, indent=8)

                elif supported_commands[key]:
                    supported_commands[key].get_help_text(name=key)
        else:
            # print supported commands
            valid_help_keys = supported_commands.keys()

            print colored.blue('  Type `help [command1] [command2] ...` to get more information.\n  The following commands are supported:')
            for key in valid_help_keys:
                print colored.cyan('  [%s] - %s' % (key, supported_commands[key].get_info_text()))
Example #10
0
def _run_migration(migration, ansible_context, check_mode, no_stop):
    puts(colored.blue('Give ansible user access to couchdb files:'))
    user_args = "user=ansible groups=couchdb append=yes"
    run_ansible_module(
        migration.source_environment, ansible_context, 'couchdb2', 'user', user_args,
        True, None, False
    )

    file_args = "path={} mode=0755".format(migration.couchdb2_data_dir)
    run_ansible_module(
        migration.source_environment, ansible_context, 'couchdb2', 'file', file_args,
        True, None, False
    )

    puts(colored.blue('Copy file lists to nodes:'))
    rsync_files_by_host = prepare_to_sync_files(migration, ansible_context)

    if no_stop:
        stop_couch_context = noop_context()
    else:
        puts(colored.blue('Stop couch and reallocate shards'))
        stop_couch_context = stop_couch(migration.all_environments, ansible_context, check_mode)

    with stop_couch_context:
        execute_file_copy_scripts(migration.target_environment, list(rsync_files_by_host), check_mode)

    return 0
Example #11
0
def dispatch_task():
    puts('\n' + colored.blue('-' * 80) + '\n')
    puts(colored.green('Preference wizard supports the following tasks:\n', bold=True))
    option_descriptions = [
        'Connect a new OneDrive Personal Account',  # 0
        'Connect a new OneDrive for Business Account',  # 1
        'View / Delete connected OneDrive accounts',  # 2
        'Add a remote Drive to sync',  # 3
        'View / Edit / Delete existing Drives',  # 4
        'Edit global ignore list files',  # 5
        'Edit HTTPS proxies',  # 6
        'Configure synchronization workload (resync interval, etc.)',  # 7
        'Exit wizard'  # 8
    ]
    for i in range(0, len(option_descriptions)):
        puts('[{}] {}'.format(i, option_descriptions[i]))
    puts()
    task_id = prompt.query('Please enter the task index and hit [ENTER]: ',
                           validators=[
                               validators.IntegerValidator(),
                               validators.OptionValidator(range(len(option_descriptions)))])
    tasks = [
        add_personal_account,
        add_business_account,
        list_existing_accounts,
        add_new_drive,
        list_existing_drives,
        edit_default_ignore_list,
        edit_proxies,
        edit_sync_params,
        bye
    ]
    if task_id < len(option_descriptions) - 1:
        puts('\n' + colored.blue('-' * 80) + '\n')
    tasks[task_id]()
Example #12
0
def get_issues(user, repo):
    url = ISSUES_ENDPOINT % (user, repo)
    github_issues_url = ISSUES_PAGE %  (user, repo)

    if valid_credentials():
        connect = requests.get(url, auth=(get_username(), get_password()))
    else:
        connect = requests.get(url)

    json_data = simplejson.loads(connect.content)

    try:
        json_data['message']
        puts('{0}. {1}'.format(colored.blue('octogit'),
            colored.red('Do you even have a Github account? Bad Credentials')))
        return
    except:
        pass
    if len(json_data) == 0 :
        puts('{0}. {1}'.format(colored.blue('octogit'),
            colored.cyan('Looks like you are perfect welcome to the club.')))
        return
    get_number_issues(json_data)
    puts('link. {0} \n'.format(colored.green(github_issues_url)))
    puts('listing all {0} issues.'.format(colored.red(get_number_issues(json_data))))
    for issue in json_data:
        #skip pull requests
        if issue['pull_request']['html_url'] != None:
            continue
        width = [[colored.yellow('#'+str(issue['number'])), 5],]
        width.append(['{0}'.format(issue['title']), 70])
        width.append([colored.red('('+ issue['user']['login']+')'), None])
        puts(columns(*width))
 def print_shell(self, *args):
     try:
         for arg in args:
             arg = str(arg)
             if isinstance(type(args), types.NoneType):
                 continue
             if self.color == 'true':
                 if str(arg).count(self.ruler) == len(str(arg)):
                     print colored.green(arg),
                 elif 'Error' in arg:
                     print colored.red(arg),
                 elif ":\n=" in arg:
                     print colored.red(arg),
                 elif ':' in arg:
                     print colored.blue(arg),
                 elif 'type' in arg:
                     print colored.green(arg),
                 elif 'state' in arg or 'count' in arg:
                     print colored.magenta(arg),
                 elif 'id =' in arg:
                     print colored.yellow(arg),
                 elif 'name =' in arg:
                     print colored.cyan(arg),
                 else:
                     print arg,
             else:
                 print arg,
         print
     except Exception, e:
         print colored.red("Error: "), e
Example #14
0
    def main(self, templates_directory):
        templates_directory = abspath(templates_directory)
        puts(colored.blue("Looking in %s for templates" % templates_directory))

        # Check for VagrantFile template file
        vagrantfile_template = join(templates_directory, 'Vagrantfile.template')
        if isfile(vagrantfile_template):
            puts(colored.blue("Found a Vagrantfile template: %s" % vagrantfile_template))

            self.parent.config.setdefault('vagrantfiles', {})['default'] = vagrantfile_template
        else:
            puts(colored.yellow("No Vagrantfile template found: %s" % vagrantfile_template))

        # Check for minions configurations
        minions_conf = join(templates_directory, 'minions_configurations')
        if isdir(minions_conf):
            logging.info("Found a minion configuration directory: %s" % minions_conf)

            for filename in listdir(minions_conf):
                filepath = join(minions_conf, filename)
                puts(colored.blue("Found minion conf: %s" % filepath))

                self.parent.config.setdefault('minion_conf', {})[filename] = filepath
        else:
            puts(colored.yellow("No minion configuration directory found: %s" % minions_conf))

        # Write config file
        self.parent.write_config_file()
Example #15
0
File: core.py Project: T2BE/gordon
    def delete(self):

        if self.dry_run:
            self.puts(
                colored.yellow(
                    ("\nYou are trying to delete this project's resources!\n"
                     "By default this command runs in dry-run mode. If you are ok \n"
                     "with the following resources being deleted, you can run this\n"
                     "command with --confirm to do the actual deletion.\n"
                     "\nNOTHING IS GOING TO BE DELETED!\n")
                )
            )
            self.puts(colored.blue("The following resources would be deleted..."))
        else:
            self.puts(colored.blue("Deleting project resources..."))

        context = self.get_initial_context()

        with indent(2):
            self.puts(colored.magenta("\nRegion:{Region}\nStage: {Stage}\n".format(**context)))

        for (number, name, filename, template_type) in self.steps():
            with indent(2):
                self.puts(colored.cyan("{} ({})".format(filename, template_type)))
            with indent(4):
                if self.debug:
                    self.puts(colored.white(u"✸ Delete template {} with context {}".format(filename, context)))
                getattr(self, 'delete_{}_template'.format(template_type))(name, filename, context)
Example #16
0
def main():

    packages = []
    args = sys.argv[1:]

    try:
        opts, pkgs = getopt(args, "vhr:u:e", ["version", "help", "requirement",
                                              "user", "errors-only"])
    except GetoptError as e:
        puts(str(e), stream=STDERR)
        usage(error=True)
        sys.exit(2)

    packages += pkgs
    packages += process_options(opts)
    packages += get_packages_from_stdin()
    show_only_errors = ('-e', '') in opts or ('--errors-only', '') in opts

    if not packages:
        # Return error if no packages found
        usage(error=True)
        sys.exit(2)

    for package in packages:
        if valid_package(package):
            urls = get_urls(package)
            symbol = red('\u2717') if urls else green('\u2713')
            msg = "%s %s: %s URLs" % (symbol, blue(package), len(urls))
            if urls or not show_only_errors:
                print(msg)
        else:
            print("%s %s: not found on PyPI" % (red('\u26a0'), blue(package)),
                  file=sys.stderr)
Example #17
0
def main():
    git.exit_if_cwd_not_git_repo()
    git.dotfiles_private_pull_latest()

    profile_name = profiles.get_current_name(exit_if_not_set=True)
    workspace = os.path.basename(
        os.path.abspath(os.path.join(os.curdir, os.pardir)))
    dirname = os.path.basename(os.path.abspath(os.curdir))

    puts(colored.blue('Profile: %s' % profile_name))
    puts(colored.blue('Workspace: %s' % workspace))
    puts(colored.blue('Repo: %s' % dirname))
    answers = prompt([
        {
            'name': 'name',
            'type': 'input',
            'message': 'Remote name to remove:',
        }
    ])
    if 'name' not in answers:
        exit(1)

    remote_name = answers['name']

    git.remove_remote(remote_name, exit_on_error=True)
    profiles.update_profile_git_workspace_remove_git_remote(
        profile_name, workspace, dirname, remote_name)
    git.dotfiles_private_commit_and_push_changes(
        'Git Remote: %s > %s > %s' % (workspace, dirname, remote_name))
Example #18
0
def main():
    # Standard non-empty input
    #name = prompt.query("What's your name?")

    # Set validators to an empty list for an optional input
    #language = prompt.query("Your favorite tool (optional)?", validators=[])

    # Shows a list of options to select from
    inst_options = [{'selector':'1','prompt':'iSCSI','return':connector.ISCSI},
                    {'selector':'2','prompt':'FibreChannel','return':connector.FIBRE_CHANNEL},
                   ]
    inst = prompt.options("Select Volume transport protocol", inst_options)

    if inst == connector.ISCSI:
        connection_info = iscsi_func()
    elif inst == connector.FIBRE_CHANNEL:
        connection_info = fc_func()

    # Use a default value and a validator
    #path = prompt.query('Installation Path', default='/usr/local/bin/', validators=[validators.PathValidator()])

    #puts(colored.blue('Hi {0}. Install {1} {2} to {3}'.format(name, inst, language or 'nothing', path)))   
    puts(colored.blue('Attempting to attach to  {0} volume'.format(inst)))
    puts(colored.blue('Using {0}'.format(connection_info)))

    do_attach(connection_info)
Example #19
0
def main():
    h = HTMLParser.HTMLParser()
    oldest_id = long(args.id) if args.id else sys.maxint
    try:
        for item in tweepy.Cursor(api.user_timeline).items(2000):
            if item.id >= oldest_id:
                print "seen this tweet already"
                continue
            if not hasattr(item, 'retweeted_status'):
                continue
            username = item.retweeted_status.user.screen_name
            tweet = h.unescape(item.retweeted_status.text)
            if 'http://' in tweet:
                continue
            if username == 'fanfiction_txt':
                continue
            print colored.red('@{}'.format(username))
            print colored.blue(tweet)
            print "Add this tweet?"
            answer = raw_input()
            if answer == 'y' or answer == '':
                add_tweet(username, tweet)
    except:
        if 'item' in locals():
            print "Current tweet ID is {}".format(item.id)
        raise
Example #20
0
def processManifest(args):
    manifestPath = os.path.join(args.baseDir, "sprites.mf")
    if not os.path.exists(manifestPath):
        raise Usage("Manifest not found at %s." % (red(manifestPath, bold=True)), (manifestPath,))
    lineCount = len(open(manifestPath).readlines())

    manifest = csv.DictReader(open(manifestPath), skipinitialspace=True)
    manifest.fieldnames = ["filename", "spritesheet"]
    spritesheets = {}

    for line in progress.bar(manifest, label="Reading Manifest: ", expected_size=lineCount):
        sheet = line["spritesheet"]
        image = line["filename"]
        imagePath = os.path.join(args.baseDir, image)
        if not os.path.exists(imagePath):
            raise Usage(
                "Image not found at %s from %s, %s."
                % (
                    red(imagePath, bold=True),
                    blue(manifestPath, bold=True),
                    blue("line " + str(manifest.line_num), bold=True),
                ),
                (imagePath, manifestPath, manifest.line_num),
            )
        spritesheets.setdefault(sheet, Spritesheet(sheet)).addImage(image)
    return spritesheets.values()
Example #21
0
def main():

    packages = []
    args = sys.argv[1:]
    input_lines = None and piped_in()

    try:
        opts, pkgs = getopt(args, "vhr:u:", ["version", "help", "requirement", "user"])
    except GetoptError as e:
        puts(str(e), stream=STDERR)
        usage(error=True)
        sys.exit(2)

    packages += pkgs
    packages += process_options(opts)

    if input_lines is not None:
        # Add packages found from standard input
        packages += get_pypi_packages(input_lines)
    elif not args:
        # Return error if no arguments given
        usage(error=True)
        sys.exit(2)

    for package in packages:
        if valid_package(package):
            links = get_links(package)
            symbol = red('\u2717') if links else green('\u2713')
            msg = "%s %s: %s links" % (symbol, blue(package), len(links))
            print(msg)
        else:
            symbol = red('\u2717')
            print("%s %s: not found on PyPI" % (symbol, blue(package)),
                  file=sys.stderr)
Example #22
0
def dispatch_task():
    puts("\n" + colored.blue("-" * 80) + "\n")
    puts(colored.green("Preference wizard supports the following tasks:\n", bold=True))
    option_descriptions = [
        "Connect a new OneDrive Personal Account",  # 0
        "Connect a new OneDrive for Business Account",  # 1
        "View / Delete connected OneDrive accounts",  # 2
        "Add a remote Drive to sync",  # 3
        "View / Edit / Delete existing Drives",  # 4
        "Edit global ignore list files",  # 5
        "Edit HTTPS proxies",  # 6
        "Configure synchronization workload (resync interval, etc.)",  # 7
        "Exit wizard",  # 8
    ]
    for i in range(0, len(option_descriptions)):
        puts("[{}] {}".format(i, option_descriptions[i]))
    puts()
    task_id = prompt.query(
        "Please enter the task index and hit [ENTER]: ",
        validators=[validators.IntegerValidator(), validators.OptionValidator(range(len(option_descriptions)))],
    )
    tasks = [
        add_personal_account,
        add_business_account,
        list_existing_accounts,
        add_new_drive,
        list_existing_drives,
        edit_default_ignore_list,
        edit_proxies,
        edit_sync_params,
        bye,
    ]
    if task_id < len(option_descriptions) - 1:
        puts("\n" + colored.blue("-" * 80) + "\n")
    tasks[task_id]()
 def print_shell(self, *args):
     try:
         for arg in args:
             arg = str(arg)
             if isinstance(type(args), types.NoneType):
                 continue
             if self.color == "true":
                 if str(arg).count(self.ruler) == len(str(arg)):
                     print colored.green(arg),
                 elif "Error" in arg:
                     print colored.red(arg),
                 elif ":\n=" in arg:
                     print colored.red(arg),
                 elif ":" in arg:
                     print colored.blue(arg),
                 elif "type" in arg:
                     print colored.green(arg),
                 elif "state" in arg or "count" in arg:
                     print colored.magenta(arg),
                 elif "id =" in arg:
                     print colored.yellow(arg),
                 elif "name =" in arg:
                     print colored.cyan(arg),
                 else:
                     print arg,
             else:
                 print arg,
         print
     except Exception, e:
         print colored.red("Error: "), e
Example #24
0
 def __init__(self,
              verb,  # verbose print function
              hostname=None,  # ip/hostname
              port='9559',
              username='******',
              password='******',
              ssh=True,  # create SSH tunnel?
              qi_session=True):  # create qi session?
     self.verb = verb
     if not hostname:
         try:
             self.hostname = str(config.read_field('hostname'))
         except IOError:
             raise RuntimeError('%s: Connect to a hostname first with "qidev connect"' %
                                col.red('ERROR'))
     else:
         self.hostname = hostname
     verb('Connect to {}'.format(self.hostname))
     self.user = username
     self.pw = password
     self.virtual = False
     self.ssh = None
     self.scp = None
     if qi_session:
         verb('Create qi session')
         try:
             self.session = qi.Session()
             self.session.connect(self.hostname)
         except RuntimeError:
             raise RuntimeError('%s: could not establish connection to %s' %
                                (col.red('ERROR'), col.blue(self.hostname)))
     else:
         self.session = None
     if ssh:
         verb('Establish connection via SSH')
         try:
             self.ssh = paramiko.SSHClient()
             self.ssh.load_system_host_keys()
             # accept unknown keys
             self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
             self.ssh.connect(self.hostname,
                              # port=self.port,
                              username=self.user,
                              password=self.pw,
                              allow_agent=False,
                              look_for_keys=False)  # have pw, don't look for private keys
             self.scp = SCPClient(self.ssh.get_transport())
         except socket.gaierror as e:
             raise RuntimeError('{}: {} ... for hostname: {}'.format(col.red('ERROR'), e,
                                                                     col.blue(self.hostname)))
         except socket.error as e:
             verb('Virtual robot detected')
             self.virtual = True  # assuming this is a virtual bot... kind of a hack?
     if self.virtual:
         self.install_path = os.path.expanduser('~')
     else:
         self.install_path = '/home/nao/'  # always linux
     self.install_path = os.path.join(self.install_path,
                                      '.local', 'share', 'PackageManager', 'apps')
Example #25
0
 def pretty_print(self):
     """
     Print the error message to stdout with colors and borders
     """
     print colored.blue("-" * 40)
     print colored.red("datacats: problem was encountered:")
     print self.message
     print colored.blue("-" * 40)
Example #26
0
    def execute_vagrant_command_on_minion(self, project_name, command):
        minion_path = self.parent.config['minions'][project_name]
        vagrant = Vagrant(minion_path, quiet_stdout=False, quiet_stderr=False)

        puts(colored.blue("Execute vagrant %s on minion %s" % (command, project_name)))
        getattr(vagrant, command)()

        puts(colored.blue("Done"))
Example #27
0
def mod(gfile):
  '''For each of the files to process either rotate, move, copy, or
  replicate the code.  General idea:
    read in ascii
    Process into a toolpath list.
    modify.
    Write out toolpath.'''

  start = datetime.now()
  puts(colored.blue('Modifying file: %s\n Started: %s'%(gfile.name,datetime.now())))

  # Parse the gcode.
  gcode = GCode(gfile)
  gcode.parseAll()

  # Create a toolpath from the gcode
  # add in the index so that we can match it to the gcode


  out = []
  if args.move:
    loc = parse(args.move, getUnits=True) # only one move at a time.
    puts(colored.blue('Moving!\n    (0,0) -> (%.3f,%.3f)'%(loc[0],loc[1])))
    tool = Tool()
    # is the addIndex atribut even used any longer?
    tool.build(gcode, addIndex=True)
    tool.move(loc) # ok well this should work
    gcode.update(tool)
    out.append([loc,gcode])

  if args.copy:
    locs = parse(args.copy, getUnits=True)
    puts(colored.blue('Copying!'))
    for loc in locs:
      puts(colored.blue('    (0,0) -> (%.3f,%.3f)'%(loc[0],loc[1])))
      gc = gcode.copy()
      tool = Tool()
      # is the addIndex atribut even used any longer?
      tool.build(gc, addIndex=True)
      tool.move(loc)
      gc.update(tool)
      out.append([loc,gc])

  # if args.replicate:
  #   nxy = map(int,parse(args.replicate)[0]) # ensure int, and only one
  #   puts(colored.blue('Replicating!\n     nx=%i, ny=%i)'%(nxy[0],nxy[1])))

  output = ''.join([o.getGcode(tag=args.name,start=l) for l,o in out])

  outfile = FILEENDING.join(os.path.splitext(gfile.name))
  puts(colored.green('Writing: %s'%outfile))
  with open(outfile,'w') as f:
    f.write(output)

  # how long did this take?
  puts(colored.green('Time to completion: %s'%(deltaTime(start))))
  print
Example #28
0
def begin():
    if os.path.exists(config_file):
        pass
    else:
        #make config file
        make_config()
        write_config()

    if args.get(0) is None:
        show_help()

    elif args.flags.contains(('--help', '-h')) or args.get(0) == 'help':
        show_help()
        sys.exit(0)

    elif args.flags.contains(('--login', '-l')) or args.get(0) == 'login':
        username = args.get(1)
        if username is None:
            username = raw_input("Github username: "******"{0}. {1}".format(
                    colored.blue("pygist"),
                    colored.red("Username was blank")))

        password = args.get(2)
        if password is None:
            import getpass
            password = getpass.getpass("Password: ")

        login(username, password)

    elif args.get(0) == 'delete':
        if args.get(1) is None:
            puts('{0}. {1}'.format(colored.blue('pygist'),
                 colored.red('You need to pass a gist number to delete')))
        else:
            gist_id = args.get(1)
            delete_gist(gist_id)

    elif args.get(0) == 'create':
        if args.get(1) == 'paste':
            description = args.get(2) or ''
            create_gist(paste=True, description=description)
        elif not args.files:
            puts('{0}. {1}'.format(colored.blue('pygist'),
                 colored.red('You need to pass file as well to create a gist')))
        else:
            description = args.not_files.get(1) or ''
            files = args.files
            create_gist(files=files, description=description)

    else:
        show_help()
        sys.exit(0)
Example #29
0
File: core.py Project: T2BE/gordon
 def __init__(self, *args, **kwargs):
     self.applications = []
     self._in_project_resource_references = {}
     self._in_project_cf_resource_references = {}
     BaseProject.__init__(self, *args, **kwargs)
     self.puts(colored.blue("Loading project resources"))
     BaseResourceContainer.__init__(self, *args, **kwargs)
     self.puts(colored.blue("Loading installed applications"))
     self._load_installed_applications()
     for resource_type in AVAILABLE_RESOURCES:
         for resouce in self.get_resources(resource_type):
             resouce.validate()
Example #30
0
def delete_gist(gist_id):
    delete_url = 'https://api.github.com/gists/%s' % (gist_id)
    username = get_username()
    password = get_password()

    r = requests.delete(delete_url, auth=(username, password))
    if r.status_code == 204:
        puts('{0}. {1}'.format(colored.blue('octogit'),
            colored.green('gist: %s deleted successfully' % gist_id)))
    else:
        puts('{0}. {1}'.format(colored.blue('octogit'),
            colored.red("You either passed a gist that isn't yours or you need to login silly.")))
        sys.exit(-1)
Example #31
0
    def main(self, project_name):
        # Check directory
        project_path = abspath(project_name)
        if isdir(project_path):
            puts(
                colored.red("The directory %s already exists, abort" %
                            project_path))
            sys.exit(1)

        # Choose minion configuration
        if len(self.parent.config.get('minion_conf', [])) == 0:
            puts(
                colored.red(
                    "You must register at least one minion configuration,"
                    "use register_dir command to do so."))
            sys.exit(1)
        if len(self.parent.config.get('minion_conf', [])) == 1:
            minion_conf = self.parent.config['minion_conf'].values()[0]
        else:
            minion_list = sorted(self.parent.config['minion_conf'].keys())
            while True:
                puts(colored.blue("Please choose a minion configuration:"))
                for i, minion in enumerate(minion_list):
                    print "%s) %s" % (i, minion)
                try:
                    minion_conf = minion_list[int(raw_input("Your choice: "))]
                    break
                except IndexError, ValueError:
                    continue

            minion_conf = self.parent.config['minion_conf'][minion_conf]
Example #32
0
def yandex(phone_number):
    global name
    global yandex_load_balancer
    yandex_load_balancer=True
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('disable-infobars')
    options.add_experimental_option('prefs', {'intl.accept_languages': 'en,en_US'})
    options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36")
    loc=os.getcwd()
    driver = uc.Chrome(options=options)
    driver.get("https://passport.yandex.com/auth/add")
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "login"))).send_keys(phone_number)
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div/div/div/div[2]/div/div/div[2]/div[3]/div/div/div/div[1]/form/div[3]/button'))).click()

    #/html/body/div[1]/div[3]/div[1]/div/div/form/div/div[2]/ul/li[1]/div/table/tbody/tr/td[1]/div/div/div/div[2]/div[1]
    try:

        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, 'passwd'))).click()

        name="This Phone Number Is Connected To A Yandex Account!"
        print(colored.green("[+]")+colored.blue(name))
       

    except:
        name="This Phone Number Is Not Connected To Any Yandex Account!"
        print(colored.magenta("[-]")+colored.red(name))
    yandex_load_balancer=False
    driver.quit()
Example #33
0
    def process(self, tool):
        '''Mill out a toolpath.  Currently etch-only - assume v-bit, i.e. depth=width and draw lines of the appropriate width to simulate etching'''
        puts(colored.blue('Processing toolpath for drawing:'))

        # we assume that we are starting with a g0x0y0z0
        last_cmd = 0
        last_z = 0

        for i, t in enumerate(progress.bar(tool)):
            cmd = t.cmd
            z = t.z
            if t.x > self.bounds['xmax']: self.bounds['xmax'] = t.x
            if t.y > self.bounds['ymax']: self.bounds['ymax'] = t.y

            # if we are doing something different or we are done:
            if cmd != last_cmd or last_z != z or i == len(tool) - 1:
                if last_cmd == 0 or last_z >= 0:
                    # draw thin grey lines for movement
                    self.ps += "0.1 setlinewidth 0.5 0.5 0.5 setrgbcolor stroke\n"
                elif last_cmd == 1:
                    self.ps += "{} setlinewidth 0 1 0 setrgbcolor stroke\n".format(
                        last_z * -72)
                elif last_cmd in (2, 3):
                    puts(
                        colored.red('um... don\'t know how to draw arcs yet!'))

                # move instead of drawing a line to the new point
                self.ps += "{0} {1} moveto\n{0} {1} lineto\n".format(
                    t.x * 72, t.y * 72)
                # then update the last_cmd and last_z params
                last_cmd = cmd
            else:
                self.ps += "{} {} lineto\n".format(t.x * 72, t.y * 72)

            last_z = z
Example #34
0
 def normalize_network_scan(self, input):
     print(colored.blue("{:<20} {:<30}".format(
         'IP Address', 'Open Ports')))
     for key, val in input.iteritems():
         print ("{:<20} {:<30}".format(
             key,
             " ".join(map(str,val))))
Example #35
0
def print_containers(containers, to_json=False):
    containers = sorted(containers, key=lambda c: c.name)

    if to_json:
        d = [c.to_dict() for c in containers]
        puts(json.dumps(d, indent=2, sort_keys=True, separators=(',', ': ')))

    else:
        puts(
            colored.blue(
                columns(["NODE", 15], ["CONTAINER ID", 15], ["STATUS", 7],
                        ["IP", 15], ["NETWORK", 10], ["PARTITION", 10])))

        def partition_label(c):
            if c.holy:
                return "H"
            elif c.partition:
                if c.neutral:
                    return str(c.partition) + " [N]"
                else:
                    return str(c.partition)
            elif c.neutral:
                return "N"
            else:
                return ""

        for container in containers:
            puts(
                columns([container.name, 15],
                        [container.container_id[:12], 15],
                        [container.status, 7],
                        [container.ip_address or "", 15],
                        [container.network_state, 10],
                        [partition_label(container), 10]))
Example #36
0
def main(gfile, args=None):
    start = datetime.now()
    name = gfile if isinstance(gfile, str) else gfile.name
    puts(
        colored.blue('Visualizing the file: %s\n Started: %s' %
                     (name, datetime.now())))

    # Read in the gcode
    gcode = GCode(gfile, limit=None)
    gcode.parse()

    # parse the code into an array of tool moves
    tool = Tool(gcode)
    tool.uniq()
    box = tool.boundBox()

    # proces and save image
    ext = args.ext if args is not None else '.pdf'
    outfile = os.path.splitext(gfile.name)[0] + FILEENDING + ext
    print box
    print box[0:2]
    image = Image(outfile, gridsize=box[0:2])
    image.process(tool)
    image.save()

    # how long did this take?
    puts(colored.green('Time to completion: %s' % (deltaTime(start))))
    print
Example #37
0
def parse(historial):
    agriculture_scrapper = ScrapperMarketAgriculture(is_historic=historial)
    livestock_scrapper = ScrapperMarketLiveStock(is_historic=historial)

    total_records = 0
    total_inserted = 0

    puts(
        colored.green(
            "Iniciando scrapeo de Precios de Central de Abastos".upper()))
    with indent(4, quote='>>>>'):
        # puts(colored.blue(" Scrapper: Productos Agricolas"))
        # agriculture_scrapper.scraping()

        # with indent(4, quote='>>>>'):
        #     puts(colored.green(" Resultados"))
        #     puts(colored.green(" Registros Totales: {}".format(agriculture_scrapper.total_records)))
        #     puts(colored.green(" Registros Insertados: {}".format(agriculture_scrapper.inserted_records)))
        #     puts(colored.red(" Registros Incorrectos:{} ".format(agriculture_scrapper.total_records - agriculture_scrapper.inserted_records)))

        puts(colored.blue(" Scrapper: Productos a base de carne"))
        livestock_scrapper.scraping()
        with indent(4, quote='>>>>'):
            puts(colored.green(" Resultados"))
            puts(
                colored.green(" Registros Totales: {}".format(
                    livestock_scrapper.total_records)))
            puts(
                colored.green(" Registros Insertados: {}".format(
                    livestock_scrapper.inserted_records)))
            puts(
                colored.red(" Registros Incorrectos:{} ".format(
                    livestock_scrapper.total_records -
                    livestock_scrapper.inserted_records)))
Example #38
0
    def copy_template(self):
        '''Moves template into current working dir.'''

        with indent(4, quote=' >'):
            puts(blue('Copying template to Project Path'))

        if os.path.isdir(self.config._tpl):
            if self.make_project_dir():
                for file in os.listdir(self.config._tpl):
                    path = os.path.join(self.config._tpl, file)
                    dirs = path.split('/')
                    exclude = False
                    for dir in dirs:
                        if dir in self.exclude_dirs:
                            exclude = True
                    if not exclude:
                        if os.path.isdir(path):
                            copytree(path,
                                     os.path.join(self.project_root, file))
                        else:
                            copy(path, self.project_root)
            self.swap_placeholders()
        else:
            self.config._error('Unable to copy template, directory does not '
                               'exist')

        if self.is_vcs_template:
            rmtree(self.config._tpl)
Example #39
0
def main():
    try:
        banner = r"""
	    __               __
	   / /_  ____ ______/ /__
	  / __ \/ __ `/ ___/ //_/
	 / /_/ / /_/ / /__/ ,<
	/_.___/\__,_/\___/_/|_|_____
	                     /_____/music player
	                     version : v0.1 (beta)
	        """
        with indent(4, quote='>>>'):
            puts(colored.red(banner))
        parser = argparse.ArgumentParser(
            description='play background music from your terminal.')
        parser.add_argument('url',
                            metavar='url',
                            type=str,
                            nargs='+',
                            help='Youtube url or local_file location')
        args = parser.parse_args()
        with indent(4, quote='>>>'):
            puts(colored.yellow("Playing now => " + args.url[0]))
        os.system("nohup python3 " +
                  os.path.dirname(os.path.abspath(__file__)) + "/player.py " +
                  args.url[0] + " >/dev/null 2>&1 &")
        with indent(4, quote='>>>'):
            puts(colored.blue("To stop music press ctrl + shift + #"))
    except Exception as e:
        print(e)
Example #40
0
def view_entry(entry, password):  # pylint: disable=inconsistent-return-statements
    title = entry.title
    data = crypto.decrypt(entry.content, password)
    if entry.sync:
        clear_screen()
        print("Checking for updates on note with Google Drive......")
        download_drive(entry, title, data, password)
        # entry = m.Note.get(m.Note.title == title)
        # data = decrypt(entry.content, password)

    clear_screen()
    puts(colored.yellow(title))
    puts(colored.blue("=" * len(title)))
    puts(colored.yellow(data))

    puts(colored.cyan('e) edit entry'))
    puts(colored.cyan('d) delete entry'))
    puts(colored.cyan('v) view previous versions'))
    puts(colored.cyan('q) to return to view entries'))

    next_action = input('Action: [e/d/v/q] : ').lower().strip()
    if next_action == 'd':
        return delete_entry(entry)
    if next_action == 'e':
        return edit_entry_view(entry, password)
    if next_action == 'v':
        return view_previous_versions(entry, password)
    if next_action == 'q':
        return False
Example #41
0
File: utils.py Project: jal2/mech
def init_box(name, version, force=False, save=True, requests_kwargs={}):
    if not os.path.exists('.mech'):
        name_version_box = add_box(name,
                                   name=name,
                                   version=version,
                                   force=force,
                                   save=save,
                                   requests_kwargs=requests_kwargs)
        if not name_version_box:
            return
        name, version, box = name_version_box
        # box = locate(os.path.join(*filter(None, (HOME, 'boxes', name, version))), '*.box')

        puts_err(colored.blue("Extracting box '{}'...".format(name)))
        os.makedirs('.mech')
        if os.name == 'posix':
            proc = subprocess.Popen(['tar', '-xf', box], cwd='.mech')
            if proc.wait():
                puts_err(colored.red("Cannot extract box"))
                sys.exit(1)
        else:
            tar = tarfile.open(box, 'r')
            tar.extractall('.mech')

        if not save and box.startswith(tempfile.gettempdir()):
            os.unlink(box)

    vmx = get_vmx()

    update_vmx(vmx)

    return vmx
Example #42
0
def listAnimes(args):
    name = "%" + " ".join(args) + "%"
    animeExists = searchEntry(name, ANIME_DB, False)

    print("")
    puts(colored.blue(ANIME_DB + "\n"))

    if (animeExists == True):
        conn = sqlite3.connect(DATABASE_URL)
        c = conn.cursor()
        t = (name, )
        sql = 'SELECT * from {tn} WHERE Name LIKE ? ORDER BY Name'.format(
            tn=ANIME_DB)
        for row in c.execute(sql, t):
            name = row[0]
            episode = str(row[1])
            puts(colored.magenta("Name: %s" % (name)))
            puts(colored.green("Episode: %s\n" % (episode)))
        conn.close()

    else:
        if name == "":
            puts(colored.red("No Animes on the database\n"))
        else:
            puts(colored.red("No Animes with that name\n"))
def main_menu():
    puts(
        colored.blue("""
  _____ ____  _____ _  __                        
 | ____| __ )| ____| |/ /                        
 |  _| |  _ \|  _| | ' /                         
 | |___| |_) | |___| . \  (EternalBlue-EK)       
 |_____|____/|_____|_|\_\__  __                  
 |  \/  | __ _(_)_ __   |  \/  | ___ _ __  _   _ 
 | |\/| |/ _` | | '_ \  | |\/| |/ _ \ '_ \| | | |
 | |  | | (_| | | | | | | |  | |  __/ | | | |_| |
 |_|  |_|\__,_|_|_| |_| |_|  |_|\___|_| |_|\__,_|
	"""))
    print("""                                        
 PussyCat: [email protected]

	1. Verify SMB Pipes
	2. Exploit Mode
	3. Exit

	""")
    ans = raw_input(" Please choose an option: ")
    if ans == "1":
        verify_pipe()
    elif ans == "2":
        print("")
        target = raw_input(" Target IP: ")
        pipe_name = raw_input(" SMB Pipe Name: ")
        exploit(target, pipe_name)
    elif ans == "3":
        print(" Exiting...")
        exit()
    else:
        print(" Please choose one of the real options! ....")
        main_menu()
Example #44
0
    def handle_noargs(self, **options):
        # Inspired by Postfix's "postconf -n".
        from django.conf import settings

        # Because settings are imported lazily, we need to explicitly load them.
        settings._setup()

        user_settings = module_to_dict(settings._wrapped)

        opts = Options()
        pformat = "%-25s = %s"
        puts('')
        for section in opts.sections:
            puts(colored.green("[%s]" % section))
            for key, kaio_value in opts.items(section):
                keycolor = colored.magenta(key)
                if key in user_settings:
                    keycolor = colored.blue(key)

                default_value = opts.options[key].default_value
                value = kaio_value or default_value

                if sys.version_info[0] < 3:
                    value = unicode(value).encode('utf8')
                else:
                    value = str(value)

                try:
                    puts(pformat % (keycolor, value))
                except Exception as e:
                    raise e
            puts('')
Example #45
0
def deep_one(phone_number):
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('disable-infobars')
    options.add_experimental_option('prefs',
                                    {'intl.accept_languages': 'en,en_US'})
    options.add_argument(
        "user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"
    )
    loc = os.getcwd()
    serv = Service("%s/path/chromedriver" % loc)
    driver = webdriver.Chrome(options=options, service=serv)
    driver.get("https://www.duckduckgo.com/")
    WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable(
            (By.XPATH, "/html/body/div/div[2]/div/div[1]/div[2]/form/input[1]"
             ))).send_keys(phone_number)
    WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((
            By.XPATH,
            '/html/body/div/div[2]/div/div[1]/div[2]/form/input[2]'))).click()
    try:
        for x in range(0, 30):
            xpath = '//*[@id="r1-%s"]/div/div[1]/div/a' % x
            name = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, xpath))).text
            print(colored.green(
                "[+]This Link Could Be Relevant With Your Number:"),
                  end="")
            print(colored.blue(name))
    except:
        pass
Example #46
0
    def run_for_celery(self, service_group, action, args, unknown_args):
        exit_code = 0
        service = "celery"
        if action == "status" and not args.only:
            args.shell_command = "supervisorctl %s" % action
            args.inventory_group = self.get_inventory_group_for_service(service, args.service_group)
            exit_code = RunShellCommand(self.parser).run(args, unknown_args)
        else:
            workers_by_host = self.get_celery_workers_to_work_on(args)
            puts(colored.blue("This is going to run the following"))
            for host, workers in workers_by_host.items():
                puts(colored.green('Host: [' + host + ']'))
                puts(colored.green("supervisorctl %s %s" % (action, ' '.join(workers))))

            if not ask('Good to go?', strict=True, quiet=args.quiet):
                return 0  # exit code

            for host, workers in workers_by_host.items():
                args.inventory_group = self.get_inventory_group_for_service(service, args.service_group)
                # if not applicable for all hosts then limit to a host
                if host != "*":
                    unknown_args.append('--limit=%s' % host)
                args.shell_command = "supervisorctl %s %s" % (action, ' '.join(workers))
                for service in self.services(service_group, args):
                    exit_code = RunShellCommand(self.parser).run(args, unknown_args)
                    if exit_code is not 0:
                        return exit_code
        return exit_code
Example #47
0
def print_banner(text="", font='slant', colour=colours.colour_white):
    result = Figlet(font=font)

    if colour == colours.colour_white:
        print(colored.white(result.renderText(text)))
    elif colour == colours.colour_blue:
        print(colored.blue(result.renderText(text)))
Example #48
0
 def show_hacked_data(self, input):
     print(colored.blue("{:<25} {:<25}".format(
         'Network', 'Password')))
     for key, val in input.items():
         print ("{:<25} {:<25}".format(
             key,
             val))
Example #49
0
    def set_project_root(self):
        '''Set project root, based on working dir and project name.'''

        self.project_root = os.path.join(self.working_dir,
                                         self.config.project_name)
        with indent(4, quote=' >'):
            puts(blue('Project path: {0}'.format(self.project_root)))
Example #50
0
    def visit_url(self, website_url):
        '''
        Visit URL. Download the Content. Initialize the beautifulsoup object. Call parsing methods. Return Series object.
        '''
        if not self.validate_url(website_url):
            print(
                colored.red("Invalid Url: {}".format(
                    colored.blue(website_url))))
            sys.exit(0)

        print(colored.yellow("Scraping URL: {}".format(website_url)))

        headers = {
            'User-Agent':
            'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'
        }
        content = requests.get(website_url, headers=headers,
                               timeout=10).content

        # lxml is apparently faster than other settings.
        soup = BeautifulSoup(content, "lxml")
        result = {
            "website_url": website_url,
            "website_name": self.get_website_name(website_url),
            "title_tag_content": self.get_html_title_tag(soup),
            "meta_tag_content": self.get_html_meta_tags(soup),
            "headings_content": self.get_html_heading_tags(soup),
            "html_text_content": self.get_text_content(soup)
        }
        # get_tag_count returns a dictionary that has a key value pair of tag and its frequency count.
        # The tags are not always the same so that is why we update the dictionary with a separate update command.
        result.update(self.get_tag_count(soup))

        # Convert to pandas Series object and return
        return pd.Series(result)
Example #51
0
File: utils.py Project: mt08xx/mech
def init_box(name, version, force=False, save=True, requests_kwargs={}):
    if not locate('.mech', '*.vmx'):
        name_version_box = add_box(name, name=name, version=version, force=force, save=save, requests_kwargs=requests_kwargs)
        if not name_version_box:
            puts_err(colored.red("Cannot find a valid box with a VMX file in it"))
            sys.exit(1)
        name, version, box = name_version_box
        # box = locate(os.path.join(*filter(None, (HOME, 'boxes', name, version))), '*.box')

        puts_err(colored.blue("Extracting box '{}'...".format(name)))
        makedirs('.mech')
        cmd = tar_cmd('-xf', box)
        if cmd:
            startupinfo = None
            if os.name == "nt":
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW
            proc = subprocess.Popen(cmd, cwd='.mech', startupinfo=startupinfo)
            if proc.wait():
                puts_err(colored.red("Cannot extract box"))
                sys.exit(1)
        else:
            tar = tarfile.open(box, 'r')
            tar.extractall('.mech')

        if not save and box.startswith(tempfile.gettempdir()):
            os.unlink(box)

    vmx = get_vmx()

    update_vmx(vmx)

    return vmx
Example #52
0
    def printColor(self, msg, index=0):
        idx = int(int(self.id) % 7)
        preText = '   -[' + str(self.id) + ']'
        postText = ''
        colors = ['magenta', 'cyan', 'green', 'yellow', 'blue', 'red', 'white']

        if idx == 0:
            print(colored.magenta(preText + msg + postText))
        elif idx == 1:
            print(colored.cyan(preText + msg + postText))

        elif idx == 2:
            print(colored.green(preText + msg + postText))

        elif idx == 3:
            print(colored.yellow(preText + msg + postText))

        elif idx == 4:
            print(colored.blue(preText + msg + postText))

        elif idx == 5:
            print(colored.red(preText + msg + postText))

        elif idx == 6:
            print(colored.white(preText + msg + postText))
Example #53
0
 def normalize_network_map(self, input):
     print(colored.blue("{:<20} {:<20}".format(
         'IP Address', 'Mac Address')))
     for el in input:
         print ("{:<20} {:<20}".format(
             el[0],
             el[1]))
Example #54
0
def listSeries(args):
    name = "%" + " ".join(args) + "%"
    seriesExists = searchEntry(name, SERIES_DB, False)

    puts(colored.blue(SERIES_DB) + "\n")

    if (seriesExists == True):
        conn = sqlite3.connect(DATABASE_URL)
        c = conn.cursor()
        t = (name, )
        sql = 'SELECT * from {tn} WHERE Name LIKE ? ORDER BY Name'.format(
            tn=SERIES_DB)
        for row in c.execute(sql, t):
            name = row[0]
            season = str(row[1])
            episode = str(row[2])
            puts(colored.magenta("Name: %s" % (name)))
            puts(colored.cyan("Season: %s" % (season)))
            puts(colored.green("Episode: %s\n" % (episode)))
        conn.close()
    else:
        if name == "":
            puts(colored.red("No TV Shows on the database\n"))
        else:
            puts(colored.red("No TV Shows with that name\n"))
Example #55
0
 def OpenLinks(self, user):
     for social_account_name in self.data:
         try:
             r = requests.get(
                 self.CleanedLink(self.data[social_account_name], user))
             if r.status_code == 200:
                 puts(
                     colored.green(
                         self.notification(1) + social_account_name +
                         self.notification(2)))
                 webbrowser.open(self.CleanedLink(
                     self.data[social_account_name], user),
                                 new=1)
                 puts(
                     colored.green(social_account_name + ": ") +
                     colored.blue(
                         self.CleanedLink(self.data[social_account_name],
                                          user)))
             elif r.status_code == 404:
                 puts(
                     colored.red(social_account_name +
                                 self.notification(3)))
             r.close()
         except Exception as e:
             print(e)
Example #56
0
def get_layout():
    custom_data.clear_screen()
    new_list = [layout_options[x:x + 1] for x in range(0, len(layout_options), 1)]
    print(tabulate(new_list,
                   showindex=range(1, len(layout_options)+1),
                   headers=['No', 'Layout'],
                   tablefmt="psql"
                   ))
    while True:
        s = list(range(1, len(layout_options)+1))
        s = [str(a) for a in s]
        TabCompleter(s)
        selected_layout = input(colored.blue("Enter a No: ")).strip()
        TabCompleter([])
        try:
            return layout_options[int(selected_layout)-1]
        except Exception as e:
            if selected_layout == 'nsi':

            if selected_layout == "b":
                custom_data.clear_screen()
                print("Exiting stack ...")
                exit()
            print(e)
        continue
Example #57
0
def menu():
    print ""
    print colored.yellow("################")
    print colored.yellow("##### IPTV #####")
    print colored.yellow("##### v" + cr.version + " ###")
    print colored.yellow("################")
    print ""
    print colored.blue("Menu")
    print "0 - Exit"
    print "1 - Search for some Servers"
    print "2 - Look at the servers list"
    print "3 - Select language, default is Italian"
    print "4 - Brute force random server from the list"
    print "5 - Brute force specific server from the list"
    print "6 - Provide a random server to attack"
    print ""
Example #58
0
def showPath():
  index = 0
  pathList = PATH.split(':')
  for path in pathList:
    with indent(2, quote=colored.blue('> ')):
      puts(f'{colored.green(index)}: {path}')
    index += 1
Example #59
0
def update():
    '''Update the moveLength for each command'''
    # easier to store this way, but unzip to make nice
    tmp = (('mm', 1.0 / 25.4), ('inch', 1.0), ('mil', 1.0 / 1000.0))
    units, scales = zip(*tmp)

    # tell the user what is going on.
    puts(
        colored.green('''\
Current Nudge length: %.3f inch [Default: 20mil].  
  Example input: "0.020inch", "20mil", "30mm"
  Possible Units: %s''' % (moveLength, ', '.join(units))))

    # get the input and clean
    terminal.echo()
    userValue = raw_input('Update nudge length to: ')
    terminal.noEcho()
    value = re.sub(r'\s', '', userValue.strip())  # Remove Whitespace

    # match to units and values
    c = re.match(r'(?P<num>(?:\d*\.)?\d+)(?P<unit>' + '|'.join(units) + ')',
                 value, re.IGNORECASE)

    # if the user was bad just go back
    if not c or not c.group('unit') in units:
        puts(colored.red('Failed to update, try again with update key...'))
        return moveLength

    # Update the moveLength which is in inches by using the right scale for the unit
    newLength = float(c.group('num')) * scales[units.index(c.group('unit'))]
    puts(colored.blue(' > moveLength is now: %.3f inch\n' % newLength))
    return newLength
Example #60
0
 def clientConnectionLost(self, connector, reason):
     print(colored.blue(reason.getErrorMessage()))
     from twisted.internet import reactor, error
     try:
         reactor.stop()  # @UndefinedVariable
     except error.ReactorNotRunning:
         pass