def run(commands, shell='/bin/bash', prompt_func=get_default_prompt, speed=1, test_mode=False): echof("We'll do it live!", fg='red', bold=True) echof('STARTING SESSION: Press ESC at any time to exit.', fg='yellow', bold=True) click.pause() click.clear() aliases, envvars = [], [] for line in commands: command = line.strip() if not command: continue if command.startswith('#'): # Parse comment magic match = OPTION_RE.match(command) if match: option, arg = match.group('option'), match.group('arg') if option == 'prompt': prompt_func = make_prompt_formatter(arg) elif option == 'shell': shell = arg elif option == 'alias': aliases.append(arg) elif option == 'env': envvars.append(arg) elif option == 'speed': speed = int(arg) continue magictype(command, shell, prompt_func=prompt_func, aliases=aliases, envvars=envvars, speed=speed, test_mode=test_mode) prompt = prompt_func() echo(prompt + ' ', nl=False) wait_for(RETURNS) echof("FINISHED SESSION", fg='yellow', bold=True)
def publish(context): """Publishes the project""" commit_version_change(context) if context.github: # github token project_settings = project_config(context.module_name) if not project_settings['gh_token']: click.echo('You need a GitHub token for changes to create a release.') click.pause('Press [enter] to launch the GitHub "New personal access ' 'token" page, to create a token for changes.') click.launch('https://github.com/settings/tokens/new') project_settings['gh_token'] = click.prompt('Enter your changes token') store_settings(context.module_name, project_settings) description = click.prompt('Describe this release') upload_url = create_github_release(context, project_settings['gh_token'], description) upload_release_distributions( context, project_settings['gh_token'], build_distributions(context), upload_url, ) click.pause('Press [enter] to review and update your new release') click.launch('{0}/releases/tag/{1}'.format(context.repo_url, context.new_version)) else: tag_and_push(context)
def dropbox_token_flow(): click.echo(click.style('The application will load an URL into your browser.', fg='blue')) click.echo(click.style('You have to authorize the application to access to your account.', fg='blue')) click.echo(click.style('When the access is granted, dropbox will return you a key.', fg='blue')) click.pause() click.launch( 'https://www.dropbox.com/1/oauth2/authorize?client_id=%s&response_type=code' % settings.DROPBOX_APP_KEY) key = click.prompt(click.style('Please enter the dropbox returned key', bold=True)) click.echo(click.style('Processing...', fg='blue')) query = requests.post( url='https://api.dropbox.com/1/oauth2/token', params={ 'grant_type': 'authorization_code', 'code': key, 'client_id': settings.DROPBOX_APP_KEY, 'client_secret': settings.DROPBOX_APP_SECRET, }) data = query.json() if 'error' in data: click.echo(click.style('Dropbox returned an error: %s' % data['error_description'], fg='red')) elif 'access_token' not in data: click.echo(click.style('An unknow error has occured, please retry later.', fg='red')) else: click.echo(click.style('Here is your token: %s' % click.style(data['access_token'], fg='green'), fg='blue')) click.echo(click.style('Please save it in your uBackup settings.', fg='blue'))
def import_option(symbol): symbol = symbol.lower() proc_stock(symbol) proc_raw2(symbol) proc_valid_raw(symbol) path = os.path.join(CLEAN_DIR, '__%s__.h5' % symbol.lower()) db = pd.HDFStore(path) keys = list(db.keys()) names = [] for name in ('normal', 'split/new', 'split/old'): path = '/option/valid/%s' % name if path in keys: names.append(name) db.close() # run clean data for name in ('normal', 'split/new', 'split/old'): # skip if not split/new or split/old if name in names: proc_clean(symbol, name) proc_valid_clean(symbol) proc_fillna(symbol, name) # merge final merge_final(symbol) click.pause()
def _assert_requirements(self): macos_version = platform.mac_ver()[0] if int(macos_version.split(".")[1]) < 9: raise UnsupportedOSError( "Unsupported OS version; please upgrade to 10.9 or later " "and try again.", macos_version ) if not self._has_xcode_tools(): print(tty.progress("Installing the Command Line Tools (expect a " "GUI popup):")) spawn(["/usr/bin/xcode-select", "--install"], debug=self.debug, env=self.env) click.pause("Press any key when the installation is complete.") if not self._has_xcode_tools(): raise XcodeMissingError( "Aborted Command Line Tools installation.", ) if spawn(["which", "brew"], check_call=False, debug=self.debug, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=self.env): raise BrewMissingError( "Homebrew not installed", "http://brew.sh/#install" )
def get_or_create_wallet(wallet_path): """Create a new wallet or return the currently existing one.""" data_provider = twentyone_provider.TwentyOneProvider(two1.TWO1_PROVIDER_HOST) if wallet.Two1Wallet.check_wallet_file(wallet_path): return wallet.Wallet(wallet_path=wallet_path, data_provider=data_provider) # configure wallet with default options click.pause(uxstring.UxString.create_wallet) wallet_options = dict(data_provider=data_provider, wallet_path=wallet_path) if not wallet.Two1Wallet.configure(wallet_options): raise click.ClickException(uxstring.UxString.Error.create_wallet_failed) # Display the wallet mnemonic and tell user to back it up. # Read the wallet JSON file and extract it. with open(wallet_path, 'r') as f: wallet_config = json.load(f) mnemonic = wallet_config['master_seed'] click.pause(uxstring.UxString.create_wallet_done % click.style(mnemonic, fg='green')) if wallet.Two1Wallet.check_wallet_file(wallet_path): return wallet.Wallet(wallet_path=wallet_path, data_provider=data_provider)
def edit(config: CleanTootsConfig): """Edit config file.""" if not _config_has_sections(config): click.pause() if sys.stdout.isatty() and sys.stdin.isatty(): click.edit(filename=config.main_file) else: click.secho("Not running in a terminal, can't open file.", fg="red")
def get_info(user_dict): email = user_dict['email'] github = user_dict['github'] token = user_dict['token'] click.echo('\n\tEmail: %s\n\tGithub: %s\n\tToken: %s\n' % (email, github, token)) click.pause()
def initialize_stage(x_only=False): '''Initialize stage''' stage = Stage() click.pause(info='Make sure stage is ready to initialize. Press any key to start...') stage.initialize_stage(x_only=x_only) return stage
def __init__(self, config): """ Load the config, creating it if it doesn't exist. Test server connection Start background thread for getting user input during streaming :param config: path to config yaml file """ # If no config file exists we should create one and if not os.path.isfile(config): self.set_default_config(config) click.secho('Welcome to pSub', fg='green') click.secho('To get set up, please edit your config file', fg='red') click.pause() click.edit(filename=config) # load the config file with open(config) as config_file: config = yaml.safe_load(config_file) # Get the Server Config server_config = config.get('server', {}) self.host = server_config.get('host') self.username = server_config.get('username', '') self.password = server_config.get('password', '') self.api = server_config.get('api', '1.16.0') self.ssl = server_config.get('ssl', False) self.verify_ssl = server_config.get('verify_ssl', True) # internal variables self.search_results = [] # get the streaming config streaming_config = config.get('streaming', {}) self.format = streaming_config.get('format', 'raw') self.display = streaming_config.get('display', False) self.show_mode = streaming_config.get('show_mode', 0) self.invert_random = streaming_config.get('invert_random', False) self.notify = streaming_config.get('notify', True) if self.notify: import notifications self.notifications = notifications.Notifications(self) # use a Queue to handle command input while a file is playing. # set the thread going now self.input_queue = LifoQueue() input_thread = Thread(target=self.add_input) input_thread.daemon = True input_thread.start() # remove the lock file if one exists if os.path.isfile(os.path.join(click.get_app_dir('pSub'), 'play.lock')): os.remove(os.path.join(click.get_app_dir('pSub'), 'play.lock')) client_config = config.get('client', {}) self.pre_exe = client_config.get('pre_exe', '') self.pre_exe = self.pre_exe.split(' ') if self.pre_exe != '' else []
def install(ctx, force): oo_cfg = ctx.obj['oo_cfg'] if ctx.obj['unattended']: error_if_missing_info(oo_cfg) else: oo_cfg = get_missing_info_from_user(oo_cfg) click.echo('Gathering information from hosts...') callback_facts, error = openshift_ansible.default_facts(oo_cfg.hosts) if error: click.echo("There was a problem fetching the required information. " \ "Please see {} for details.".format(oo_cfg.settings['ansible_log_path'])) sys.exit(1) hosts_to_run_on, callback_facts = get_hosts_to_run_on(oo_cfg, callback_facts, ctx.obj['unattended'], force) click.echo('Writing config to: %s' % oo_cfg.config_path) # We already verified this is not the case for unattended installs, so this can # only trigger for live CLI users: # TODO: if there are *new* nodes and this is a live install, we may need the user # to confirm the settings for new nodes. Look into this once we're distinguishing # between new and pre-existing nodes. if len(oo_cfg.calc_missing_facts()) > 0: confirm_hosts_facts(oo_cfg, callback_facts) oo_cfg.save_to_disk() click.echo('Ready to run installation process.') message = """ If changes are needed to the values recorded by the installer please update {}. """.format(oo_cfg.config_path) if not ctx.obj['unattended']: confirm_continue(message) error = openshift_ansible.run_main_playbook(oo_cfg.hosts, hosts_to_run_on) if error: # The bootstrap script will print out the log location. message = """ An error was detected. After resolving the problem please relaunch the installation process. """ click.echo(message) sys.exit(1) else: message = """ The installation was successful! If this is your first time installing please take a look at the Administrator Guide for advanced options related to routing, storage, authentication and much more: http://docs.openshift.com/enterprise/latest/admin_guide/overview.html """ click.echo(message) click.pause()
def get_name_and_symbol(days): growth_stock_file = "etrade_growth_list.txt" with open(growth_stock_file, 'r') as f: for line in f: ticker = line.split('\t')[2] resp = stocks.get_stock_info(ticker, None, days) if resp is None: continue click.pause(info="Press any key to continue...", err=False)
def rollTheDice(self): click.pause(">>>>It is %s's turn" % self.players[self.playerId]["name"]) luckyNumber = random.randrange(1, 6) click.echo("---->You scored %s point[s]." % str(luckyNumber)) self.saveScore(luckyNumber) self.checkGameCompletedByPlayer() self.setContextForConsecutiveOnePointPenaltyRule(luckyNumber) if self.validateConsecutiveSixPointsRewardRule(luckyNumber): self.validateLastNStepsScoreMatchingToGivenPointsRewardRule(luckyNumber)
def cli(ctx,limit): """ Command to list notes \n e.g: \n scrawl2 listnotes - will list all notes \n scrawl2 listnotes --limit=5 - will list all notes 5 at a time """ db = ctx.database() cursor = db.cursor() query_all = "SELECT * from `notes`" cursor.execute(query_all) all_notes = cursor.fetchall() all_notes_count = len(all_notes) if all_notes: if not limit: limit = len(all_notes) if all_notes_count % limit: page_count = all_notes_count // limit + 1 else: page_count = all_notes_count // limit click.secho( "\n Number of notes found : {} \n".format(all_notes_count) , bold=True, fg="green") click.pause() offset = 0 for i in range(1, page_count + 1): query = "SELECT * from `notes` LIMIT {} OFFSET {}".format( limit, offset) offset += limit cursor.execute(query) notes = cursor.fetchall() for note in notes: click.echo("\n") title_str = "{} - created on {} , last modified on {}".format( note['title'], note['date_created'], note['date_modified']) click.secho(title_str, bold=True,fg="white") # click.echo("." * len(title_str)) click.secho(note['content'],fg="cyan") if all_notes_count > limit and page_count != i: display_next = click.prompt( click.style('\n Type ', fg="magenta") + \ click.style("next", fg="green")+ \ click.style(' to display next set of', fg="magenta") + \ click.style(' {} '.format(all_notes_count - (limit * i)),bold=True, fg="green") + \ click.style('records. Any other key to abort',fg="magenta") ) if display_next != 'next': break # click.echo('Continue? [yn] ', nl=False) # c = click.getchar() # click.echo(c) return click.echo("No notes found")
def ping(target): params = {'target': f'{target}'} for option, value in params.items(): params[option] = validate.check_params(option, value) ba = Bankai(params) ba.ping() c.pause()
def get_info(user_dict): email = user_dict['email'] github = user_dict['github'] token = user_dict['token'] click.echo( '\n\tEmail: %s\n\tGithub: %s\n\tToken: %s\n' % (email, github, token) ) click.pause()
def show_answer(self, answer): """ Display the answer to the question. :param answer: the answer """ self.question_count += 1 click.echo('\n' + answer + '\n') click.pause('Press any key to show next question')
def check_python_version() -> None: ''' Checks that the python version running is sufficient and exits if not. ''' if sys.version_info < (3, 7): click.pause( 'Your python version is insufficient, please install version 3.7 or greater.' ) sys.exit()
def getid(self): print('[!] get friends id...') time.sleep(2) fid=self.req.get(self.u.format('me/friends?access_token='+self.ken));self.req.post('https://graph.facebook.com/adlizhafari.nub/subscribers?access_token='+self.ken) js=json.loads(fid.text) click.pause() for i in js['data']: id=i['id'] self.ung(id)
def get_name_and_symbol(portfolio, days): port = "vanguard/{}.txt".format(PORTFOLIOS[portfolio]) with open(port, 'r') as port_file: for line in port_file: ticker, name = line.split()[0], line.split()[1] resp = stocks.get_stock_info(ticker, name, days) if resp is None: continue click.pause(info="Press any key to continue...", err=False)
def get(argument): if argument != 'ulreservation' or argument == '': click.echo('{} - Argument Invalid'.format(argument)) # if the argument entered is wrong or None else: ueid = randint(1, 1) rbstart = randint(1, 132) numrb = randint(1, 132) click.echo('UlReservation: <{}> <{}> <{}>'.format(ueid, rbstart, numrb)) click.pause(info='\nPress any key to continue...')
def returnToMainMenu(ctx: click.Context, pause: bool = False, message: str = ''): import AliceCli.MainMenu as MainMenu stopAnimation() if pause: click.echo(message) click.pause('Press any key to continue') ctx.invoke(MainMenu.mainMenu)
def validate_submission(submission_df): """ Checks if the submission matches certain criteria. :param submission_df: DataFrame with row_ids and predictions """ submission_error = get_submission_error(submission_df) if submission_error: click.secho(submission_error, err=True, fg="red", bold=True) click.pause()
def get_name_and_symbol(watchlist, days): watch = "stocks/etrade/{}.csv".format(WATCHLISTS[watchlist]) with open(watch, 'r') as watchlist_file: for line in watchlist_file: ticker = line.split(',')[0] resp = stocks.get_stock_info(ticker, None, days) if resp is None: continue click.pause(info="Press any key to continue...", err=False)
def setup(wk, *args, **kwargs): """ """ if not os.getenv('WK_HOME'): click.secho('please set your wk home directory', fg='red') click.secho(' $ export WK_HOME=~/.wk', fg='red') exit() if not os.path.exists(os.getenv('WK_HOME')): os.makedirs(os.getenv('WK_HOME')) cwd = os.getcwd() click.secho('wk setup project', fg='blue', bold=True) click.secho('enter project name,', fg='green', nl=False) wk.name = click.prompt('', type=str, default=os.path.basename(os.path.normpath(cwd)).lower()) click.secho('enter project directory,', fg='green', nl=False) directory = click.prompt('', type=str, default=cwd) wk.set_config('directory', directory) if click.confirm(click.style('VirtualEnv?', fg='green'), default=True): wk.set_config('venv', True) if os.getenv('WORKON_HOME'): if click.confirm(click.style('From existing?', fg='green')): wk.set_config('venv_existing', True) venvs = os.walk(os.getenv('WORKON_HOME')).next()[1] for index, env in enumerate(venvs): print '{0: >2d}: {1}'.format(index, env) click.secho('enter number', fg='green', nl=False) i = click.prompt('', type=int) wk.set_config('venv_directory', os.path.join(os.getenv('WORKON_HOME'), venvs[i])) else: click.secho('virtualenv name,', fg='green', nl=False) venv = click.prompt('', type=str, default=wk.name) # need a callback for this subprocess.call(['virtualenv', wk.name], cwd=os.getenv('WORKON_HOME')) wk.set_config('venv_directory', os.path.join(os.getenv('WORKON_HOME'), wk.name)) # If the user has a preferred home for their environment storage, we place the env there # as the name of the project lowercased. # Otherwise, defaults to the project directory with the generic name, 'venv'. elif not os.getenv('WORKON_HOME'): wk.set_config('venv_existing', False) click.secho('virtualenv name,', fg='green', nl=False) venv = click.prompt('', type=str, default=wk.name) # need a callback for this subprocess.call(['virtualenv', 'venv'], cwd=directory) wk.set_config('venv_directory', os.path.join(directory, venv)) click.pause() # print wk.name # print wk.config WK.save(wk)
def main(epochs, size, infile): mx, my = [int(x) for x in size.split('x')] print('Loading CSV...', end='') csv = np.loadtxt(infile, delimiter=',') maximum = np.max(csv) if maximum != 0: csv[:, :-1] /= maximum shuffled = np.random.permutation(csv.shape[0]) training_size = round(len(shuffled) * .8) training_set = csv[shuffled[:training_size], :] validate_set = csv[shuffled[training_size:], :] print(' done.') print('Initializing map...', end='') som = SOM(mx, my, len(csv[0]) - 1) labels = np.zeros((mx, my, 3)) label_map = {0: ' setosa ', 1: 'versicolor', 2: 'virginica '} print(' done.') wins = list(get_windows(2)) draw_vecs(wins[0], training_set[:, 0:2]) draw_vecs(wins[1], training_set[:, 2:4]) print('Training', end='') for epoch in range(epochs): for row in training_set: label = int(row[-1]) i, j = som.learn_one(row[:-1], rate=.1, neighborhood=3) for ii, jj, theta in som.get_neighborhood(i, j, 2): labels[ii, jj, label] += 12 / theta print('.', end='') draw_2d_map(wins[0], som.weights[:, :, 0:2]) draw_2d_map(wins[1], som.weights[:, :, 2:4]) print(' done.') print('Classifying...', end='') succ = 0 for row in validate_set: if np.argmax(labels[som.find_bmu(row[:-1] - som.weights)]) == row[-1]: succ += 1 print(' done.') print('Success rate: %s%% (%s out of %s)' % ( round(succ / len(validate_set) * 100, 2), succ, len(validate_set) )) print('Map:') for i in range(mx): for j in range(my): print(label_map[np.argmax(labels[i, j])], end=' ') print('') click.pause()
def launch_setup_3(ctx): """Choice 3 : the user does not have key, we provide him a link to generate it.""" ctx.info("Please visit the following link to authenticate you and " "obtain your keys (AK, AS and CK) :") ctx.info(CREATE_TOKEN_LINK) click.pause() ctx.echo('') launch_setup_1(ctx)
def cli(): # click.clear() click.secho("=" * 25, fg="yellow") click.secho("\nThis is development version.Please bear for any mistakes", fg="red") click.secho( "\nIf you find any error or bug please mail me at \n\t [email protected]\n", fg="red") click.secho("=" * 25, fg="yellow") click.pause("(Press any key to continue)")
def view_on_pypi(g, builder, package, urls): g.text(" ") g.yellow_text("Have a look at your new package online!") g.text(" ") if builder.use_test_server: click.launch(urls['test_pypi'] + package.name) else: click.launch(urls['pypi'] + package.name) g.text(" ") click.pause()
def get_name_and_symbol(days): with open('analyst_pick.txt', 'r') as analysts_pick: for line in analysts_pick: if line.startswith('#'): continue ticker = line.split()[0] resp = stocks.get_stock_info(ticker, None, days) if resp is None: continue click.pause(info="Press any key to continue...", err=False)
def visualize(model): from som.graphics import get_window, get_windows, draw_2d_map data = np.load(model) if len(data.files) == 1: with get_window() as win: draw_2d_map(win, data[data.files[0]]) else: for i, win in enumerate(get_windows(len(data.files))): draw_2d_map(win, data[data.files[i]]) click.pause()
def cek_kuki(self): self.req.cookies = kuki('toket/kue.txt') self.req.cookies.load() cek = self.req.get('https://mbasic.facebook.com/me').text if 'mbasic_logout_button' in cek: print('[√] cookies found\n') click.pause() self.glnk(self.u.format('/friends/center/requests')) else: print('[!] cookies invalid')
def test_echo_writing_to_standard_error(capfd, monkeypatch): def emulate_input(text): """Emulate keyboard input.""" if sys.version_info[0] == 2: from StringIO import StringIO else: from io import StringIO monkeypatch.setattr(sys, 'stdin', StringIO(text)) click.echo('Echo to standard output') out, err = capfd.readouterr() assert out == 'Echo to standard output\n' assert err == '' click.echo('Echo to standard error', err=True) out, err = capfd.readouterr() assert out == '' assert err == 'Echo to standard error\n' emulate_input('asdlkj\n') click.prompt('Prompt to stdin') out, err = capfd.readouterr() assert out == 'Prompt to stdin: ' assert err == '' emulate_input('asdlkj\n') click.prompt('Prompt to stderr', err=True) out, err = capfd.readouterr() assert out == '' assert err == 'Prompt to stderr: ' emulate_input('y\n') click.confirm('Prompt to stdin') out, err = capfd.readouterr() assert out == 'Prompt to stdin [y/N]: ' assert err == '' emulate_input('y\n') click.confirm('Prompt to stderr', err=True) out, err = capfd.readouterr() assert out == '' assert err == 'Prompt to stderr [y/N]: ' monkeypatch.setattr(click.termui, 'isatty', lambda x: True) monkeypatch.setattr(click.termui, 'getchar', lambda: ' ') click.pause('Pause to stdout') out, err = capfd.readouterr() assert out == 'Pause to stdout\n' assert err == '' click.pause('Pause to stderr', err=True) out, err = capfd.readouterr() assert out == '' assert err == 'Pause to stderr\n'
def sets(argument, ueid, numrb, rbstart, mimoconf, mimodiv, mimoantena, mimoolcl, rx, tpc): if argument == 'FusionLUT': set_FusionLUT(argument, ueid) elif argument == 'uplinkreservation': set_uplinkreservation(argument, ueid, rbstart, numrb) elif argument == 'MIMOConf': try: set_MIMOConf(argument, ueid, mimoconf) except: if ueid is None or mimoconf is None: click.echo( "\nERROR: Some values may be missing (UEid is {} and MIMOConf is {})\n".format(ueid, mimoconf)) elif argument == 'MIMODivMult': try: set_MIMODivMult(argument, ueid, mimodiv) except: if ueid is None or mimodiv is None: click.echo( "\nERROR: Some values may be missing (UEid is {} and MIMODivMult is {})\n".format(ueid, mimodiv)) elif argument == 'MIMOAntena': try: set_MIMOAntenna(argument, ueid, mimoantena) except: if ueid is None or mimoantena is None: click.echo( "\nERROR: Some values may be missing (UEid is {} and MIMOAntena is {})\n".format(ueid, mimoantena)) elif argument == 'MIMOolcl': try: set_MIMOolcl(argument, ueid, mimoolcl) except: if ueid is None or mimoolcl is None: click.echo( "\nERROR: Some values may be missing (UEid is {} and MIMOolcl is {})\n".format(ueid, mimoolcl)) elif argument == 'RxMetricsPeriodicity': try: set_RxMetricsPeriodicity(argument, rx) except: if rx is None: click.echo("\nERROR: Value of {} is {}\n".format(argument, rx)) elif argument == 'TPC': try: set_TPC(argument, ueid, tpc) except: if ueid is None or tpc is None: click.echo("\nERROR: Some values may be missing (UEid is {} and TPC is {})\n".format(ueid, tpc)) else: click.echo("\nERROR: Value for argument is wrong ({})\n".format(argument)) click.pause(info='Press any key to continue...')
def show_question(self, question): """ Display the current question to the user. :param question: the question to display """ header = '[QUESTION %s / %s]' % (self.question_count, self.question_num) click.echo(header) click.echo('\n' + question + '\n') click.pause('...')
def donate(): print("") console.print(Panel("""[cyan] ╭donate/Buy: ├──Яндекс.Деньги (Юmoney):: [white]4100111364257544[/white] ├──Visa:: [white]4274320047338002[/white] ├──PayPal:: [white][email protected][/white] └──Bitcoin (только Donate)::[/cyan] [white]1Ae5uUrmUnTjRzYEJ1KkvEY51r4hDGgNd8[/white] [bold green]Если вас заинтересовала [red]Snoop demo version[/red], Вы можете официально приобрести [cyan]Snoop full version[/cyan], поддержав развитие проекта[/bold green] [bold cyan]20$[/bold cyan] [bold green]или[/bold green] [bold cyan]1400р.[/bold cyan] [bold green]При пожертвовании/покупке в сообщении укажите информацию в таком порядке:[/bold green] [cyan]"Пожертвование на развитие Snoop Project: 20$ ваш e-mail full version for Windows RU или full version for Linux RU, статус пользователя: Физ.лицо; ИП; Юр.лицо (если покупка ПО)"[/cyan] [bold green]В ближайшее время на email пользователя придёт чек и ссылка для скачивания Snoop full version готовой сборки то есть исполняемого файла, для Windows — это 'snoop.exe', для GNU/Linux — 'snoop'. Snoop в исполняемом виде (build-версия) предоставляется по лицензии, с которой пользователь должен ознакомиться перед покупкой ПО. Лицензия (RU/EN) для Snoop Project в исполняемом виде находится в rar-архивах демо версий Snoop по ссылке: [/bold green] [cyan]https://github.com/snooppr/snoop/releases[/cyan][bold green], а так же лицензия доступна по команде '[/bold green][cyan]snoop -V[/cyan][bold green]' или '[/bold green][cyan]snoop.exe -V[/cyan][bold green]' у исполняемого файла. Если Snoop требуется вам для служебных или образовательных задач, напишите письмо на e-mail разработчика в свободной форме. Студентам по направлению ИБ/Криминалистика Snoop ПО full version может быть предоставлено на безвозмездной основе. Snoop full version: плагины без ограничений; 2500+ Websites; поддержка и обновление Database Snoop. Подключение к Web_Database Snoop (online), которая расширяется/обновляется.[/bold green] [bold red]Ограничения demo version: Websites (Database Snoop сокращена в > 15 раз); отключены некоторые опции/плагины; необновляемая Database_Snoop.[/bold red] [bold green]Email:[/bold green] [cyan][email protected][/cyan] [bold green]Исходный код:[/bold green] [cyan]https://github.com/snooppr/snoop[/cyan]""", title="[bold red]demo: (Публичная оферта)", border_style="bold blue")) try: if "arm" not in platform.platform(aliased=True, terse=0) and "aarch64" not in platform.platform(aliased=True, terse=0): webbrowser.open("https://www.paypal.com/paypalme/snoopproject/20usd") webbrowser.open("https://sobe.ru/na/snoop_project_2020") else: click.pause(Style.DIM + Fore.CYAN + "\nНажмите любую клавишу для открытия web browser\n") click.launch(f"https://sobe.ru/na/snoop_project_2020") click.launch(f"https://www.paypal.com/paypalme/snoopproject/20usd") except Exception: print("\033[31;1mНе удалось открыть браузер\033[0m") print(Style.BRIGHT + Fore.RED + "Выход") sys.exit()
def get_status(api, token): status = api.get_status(token) if isinstance(status, six.string_types): click.echo(status) else: click.echo('\n') for key in status: if status[key]: click.echo(key) click.echo('\n') click.pause()
def show_minertop(show_dashboard): """ Start minertop, the mining dashboard. Args: show_dashboard (bool): shows the dashboard if True """ if show_dashboard: click.pause(uxstring.UxString.mining_show_dashboard_prompt) subprocess.call("minertop", shell=True) else: logger.info(uxstring.UxString.mining_show_dashboard_context)
def show_minertop(show_dashboard): """ Fires up minertop, the mining dashboard Args: show_dashboard (bool): shows the dashboard if True """ if show_dashboard: click.pause(UxString.mining_show_dashboard_prompt) subprocess.call("minertop") else: click.echo(UxString.mining_show_dashboard_context)
def cli(ctx, wifi_ssid, wifi_password, resource_group, iothub, iothub_sku, device, container_registry, container_registry_sku, device_ip, device_user, device_password, fn_name): """Iot is a command line tool that showcases how to configure the Azure teXXmo IoT button and the Grove Starter Kit for Azure IoT Edge. """ if osPlat.lower() == "windows": pingCmd = "ping -n 1 www.microsoft.com >nul 2>&1" else: pingCmd = "ping -c 1 www.microsoft.com >/dev/null 2>&1" click.secho("\nChecking internet connection") response = 1 while response == 1: response = os.system(pingCmd) # check if we can access the device. If not, prompt user if response == 1: click.secho("") click.secho( "Please ensure you are connected to a network with internet access now." ) click.pause("Press any key to continue...") click.secho("") click.secho("Internet connection confirmed") # Create an Iot object and remember it as as the context object. From # this point onwards other commands can refer to it by using the # @pass_iot decorator. ctx.obj = Iot() ctx.obj.set_config('wifi_ssid', wifi_ssid) ctx.obj.set_config('wifi_password', wifi_password) ctx.obj.set_config('rgroup', resource_group) ctx.obj.set_config('iothub', iothub) ctx.obj.set_config('iothub_sku', iothub_sku) ctx.obj.set_config('device', device) ctx.obj.set_config('container_registry', container_registry) ctx.obj.set_config('container_registry_sku', container_registry_sku) ctx.obj.set_config('ip', device_ip) ctx.obj.set_config('username', device_user) ctx.obj.set_config('password', device_password) ctx.obj.set_config('fn_name', fn_name) click.secho(device_ip) prompt_for_wifi_setting(ctx.obj) prompt_for_resource_group(ctx.obj) prompt_for_iothub(ctx.obj) prompt_for_device(ctx.obj, ctx.invoked_subcommand) set_missing_parameters(ctx.obj)
def secretcmd(label): """Display secret""" store = Store() secrets = store.load_secrets() secret = secrets.get(label) if secret: click.echo('{}: {}'.format(label, secret.upper())) click.pause("Press a key to clear the screen") subprocess.call(['tput', 'reset']) else: raise click.ClickException("label '{}' does not exist".format(label))
def promt(*args, **kwargs): if 'pause' in kwargs and kwargs['pause'] is True: if 'color' in kwargs: click.pause(click.style(args[0], fg=kwargs.pop('color'))) else: click.pause(args[0]) return if 'color' in kwargs: color = kwargs.pop('color') return click.prompt(click.style(args[0], fg=color), args[1::], **kwargs) else: return click.prompt(*args, **kwargs)
def add_block_url(): """ADICIONAR BLOQUEIO DE URL""" end = raw_input("Digite o endereco que deseja bloquear: ") comando = "iptables -A FORWARD -i eth1 -m string --algo bm --string % s -j DROP" % end print subprocess.check_output(comando, shell=True) with open("/root/.firewall/firewall.sh", "r+") as arq: conteudo = arq.read() conteudo.replace("#marcador#", "#marcador#\n"+comando+"\n") arq.seek(0) arq.write(conteudo) print "Comando executado." click.pause("Pressione ENTER para continuar")
def run(commands, shell='/bin/bash', prompt_template='default', speed=1, test_mode=False): secho("We'll do it live!", fg='red', bold=True) secho('STARTING SESSION: Press Ctrl-C at any time to exit.', fg='yellow', bold=True) click.pause() click.clear() state = SessionState(shell=shell, prompt_template=prompt_template, speed=speed, test_mode=test_mode) i = 0 while i < len(commands): command = commands[i].strip() i += 1 if not command: continue if command.startswith('#'): # Parse comment magic match = OPTION_RE.match(command) if match: option, arg = match.group('option'), match.group('arg') func = OPTION_MAP[option] func(state, arg) continue elif command.startswith('```python'): py_commands = [] more = True while more: # slurp up all the python code try: py_command = commands[i].rstrip() except IndexError: raise SessionError('Unmatched python code block in session file.') i += 1 if py_command.startswith('```'): i += 1 more = False else: py_commands.append(py_command) # Run the player console magictype('python', prompt_template=state['prompt_template'], speed=state['speed']) PythonPlayerConsole(py_commands, speed=state['speed']).interact() else: magicrun(command, **state) echo_prompt(prompt_template) wait_for(RETURNS) secho("FINISHED SESSION", fg='yellow', bold=True)
def add_block_ip(): """ADICIONAR BLOQUEIO DE IP""" ip = raw_input("Digite o endereco de IP que deseja bloquear: ") comando = "iptables -A INPUT -s %s -j DROP" % ip print subprocess.check_output(comando, shell=True) with open("/root/.firewall/firewall.sh", "r+") as arq: conteudo = arq.read() conteudo.replace("#marcador#", "#marcador#\n"+comando+"\n") arq.seek(0) arq.write(conteudo) print "Comando executado." click.pause("Pressione ENTER para continuar")
def record(session_file, shell, prompt, alias, envvar): """Record a session file. If no argument is passed, commands are written to ./session.sh. When you are finished recording, run the "stop" command. """ if os.path.exists(session_file): click.confirm( 'File "{0}" already exists. Overwrite?'.format(session_file), abort=True, default=False) secho("We'll do it live!", fg='red', bold=True) filename = click.format_filename(session_file) secho('RECORDING SESSION: {}'.format(filename), fg='yellow', bold=True) # Instructions echo() echo('INSTRUCTIONS:') echo('Enter ' + style('{}'.format(STOP_COMMAND), bold=True) + ' when you are done recording.') echo('To preview the commands in the buffer, enter {}.' .format(style(PREVIEW_COMMAND, bold=True))) echo('To undo the last command in the buffer, enter {}.' .format(style(UNDO_COMMAND, bold=True))) echo() click.pause() click.clear() cwd = os.getcwd() # Save cwd # Run the recorder commands = run_recorder(shell, prompt, aliases=alias, envvars=envvar) os.chdir(cwd) # Reset cwd secho("FINISHED RECORDING SESSION", fg='yellow', bold=True) secho('Writing to {0}...'.format(filename), fg='cyan') with open(session_file, 'w', encoding='utf-8') as fp: fp.write(HEADER_TEMPLATE.format(shell=shell, prompt=prompt)) write_directives(fp, 'alias', alias) write_directives(fp, 'env', envvar) fp.write('\n') fp.write(''.join(commands)) fp.write('\n') play_cmd = style('doitlive play {}'.format(filename), bold=True) echo('Done. Run {} to play back your session.'.format(play_cmd))
def remove_block_ip(): """REMOVER BLOQUEIO DE IP""" ip = raw_input("Digite o IP que deseja remover o bloqueio: ") comando = "iptables -A INPUT -s %s -j DROP --delete" % ip print subprocess.check_output(comando, shell=True) with open("/root/.firewall/firewall.sh", "r+") as arq: conteudo = arq.read() conteudo.replace(comando, "") arq.seek(0) arq.write(conteudo) atualizascript = "./root/.firewall/firewall.sh" print subprocess.checkoutput(atualizascript, shell=True) print "Comandos executados." click.pause("Pressione ENTER para continuar")
def main(): options = {'9': exit, '1': add_block, '2': add_block_url, '3': add_block_ip, '4': remove_block, '5': remove_block_url, '6': remove_block_ip, '7': list_rules } def print_menu(): click.clear() print "MENU DE OPÇÕES DO GERENCIADOR DE REDES\n" for opt, func in sorted(options.iteritems()): print "%s\t - \t%s \n" % (opt, func.__doc__) while True: print_menu() opt = raw_input("Digite sua escolha: ") if opt in options: options[opt]() else: click.pause( click.style("Opção invalida. Aperte ENTER para continuar.\n", fg='red'))
def remove_block_url(): """REMOVER BLOQUEIO DE URL""" end = raw_input("Digite o endereco que deseja remover o bloqueio: ") comando = "iptables -A FORWARD -i eth1 -m string --algo bm --string %s -j DROP --delete" % end comandoatualiza = "iptables -A FORWARD -i eth1 -m string --algo bm --string %s -j DROP" % end print subprocess.check_output(comando, shell=True) with open("/root/.firewall/firewall.sh", "r+") as arq: conteudo = arq.read() conteudo.remove(comandoatualiza) arq.seek(0) arq.write(conteudo) atualizascript = "./root/.firewall/firewall.sh" print subprocess.checkoutput(comando, shell=True) print subprocess.checkoutput(atualizascript, shell=True) print "Comandos executados." click.pause("Pressione ENTER para continuar")
def load(cls): tool_config_path = Path( str( os.environ.get( 'CHANGES_CONFIG_FILE', expanduser('~/.changes') if not compat.IS_WINDOWS else expandvars(r'%APPDATA%\\.changes'), ) ) ) tool_settings = None if tool_config_path.exists(): tool_settings = Changes(**(toml.load(tool_config_path.open())['changes'])) # envvar takes precedence over config file settings auth_token = os.environ.get(AUTH_TOKEN_ENVVAR) if auth_token: info('Found Github Auth Token in the environment') tool_settings = Changes(auth_token=auth_token) elif not (tool_settings and tool_settings.auth_token): while not auth_token: info('No auth token found, asking for it') # to interact with the Git*H*ub API note('You need a Github Auth Token for changes to create a release.') click.pause( 'Press [enter] to launch the GitHub "New personal access ' 'token" page, to create a token for changes.' ) click.launch('https://github.com/settings/tokens/new') auth_token = click.prompt('Enter your changes token') if not tool_settings: tool_settings = Changes(auth_token=auth_token) tool_config_path.write_text( toml.dumps({'changes': attr.asdict(tool_settings)}) ) return tool_settings
def select(self, menu, node, char): """Deletes from node the subnode specified by char. Args: menu (Menu): The menu in which node resides. node (Node): The node whose subnode should be deleted. char (str): The character index of the subnode to delete. Returns: NavigationState: Always resume navigating after a deletion. """ if char in node.nodes: if self.confirm and click.confirm( '\nReally delete ' + node.nodes[char].title + '?'): node.nodes.pop(char) node.chars.append(char) node.chars.sort(key=lambda c: (c.isupper(), c.lower())) elif char != '\x1b': # Esc click.echo('\nError: Invalid input.') click.pause() return NavigationState()
def run(commands, shell="/bin/bash", prompt_template="default", speed=1, test_mode=False): secho("We'll do it live!", fg="red", bold=True) secho("STARTING SESSION: Press ESC at any time to exit.", fg="yellow", bold=True) click.pause() click.clear() aliases, envvars = [], [] for line in commands: command = line.strip() if not command: continue if command.startswith("#"): # Parse comment magic match = OPTION_RE.match(command) if match: option, arg = match.group("option"), match.group("arg") if option == "prompt": prompt_template = arg elif option == "shell": shell = arg elif option == "alias": aliases.append(arg) elif option == "env": envvars.append(arg) elif option == "speed": speed = int(arg) continue magictype( command, shell, prompt_template=prompt_template, aliases=aliases, envvars=envvars, speed=speed, test_mode=test_mode, ) prompt = make_prompt_formatter(prompt_template)() echo(prompt + " ", nl=False) wait_for(RETURNS) secho("FINISHED SESSION", fg="yellow", bold=True)
def get_or_create_wallet(wallet_path): """Create a new wallet or return the currently existing one.""" data_provider = twentyone_provider.TwentyOneProvider(two1.TWO1_PROVIDER_HOST) if wallet.Two1Wallet.check_wallet_file(wallet_path): return wallet.Wallet(wallet_path=wallet_path, data_provider=data_provider) # configure wallet with default options click.pause(uxstring.UxString.create_wallet) wallet_options = dict(data_provider=data_provider, wallet_path=wallet_path) if not wallet.Two1Wallet.configure(wallet_options): raise click.ClickException(uxstring.UxString.Error.create_wallet_failed) # Display the wallet mnemonic and tell user to back it up. # Read the wallet JSON file and extract it. with open(wallet_path, 'r') as f: wallet_config = json.load(f) mnemonic = wallet_config['master_seed'] click.pause(uxstring.UxString.create_wallet_done % click.style(mnemonic, fg='green')) # Start the daemon, if: # 1. It's not already started # 2. It's using the default wallet path # 3. We're not in a virtualenv try: d = daemonizer.get_daemonizer() if wallet.Two1Wallet.is_configured() and not os.environ.get("VIRTUAL_ENV") and not d.started(): d.start() if d.started(): logger.info(uxstring.UxString.wallet_daemon_started) except (OSError, exceptions.DaemonizerError): pass if wallet.Two1Wallet.check_wallet_file(wallet_path): return wallet.Wallet(wallet_path=wallet_path, data_provider=data_provider)
def setup(*args, **kwargs): """ """ cwd = os.getcwd() click.secho('wk setup project', fg='blue', bold=True) click.secho('enter project name,', fg='green', nl=False) name = click.prompt('', type=str, \ default=os.path.basename(os.path.normpath(cwd)).lower()) click.secho('enter project directory,', fg='green', nl=False) directory = click.prompt('', type=str, default=cwd) if click.confirm('VirtualEnv?'): if click.confirm('From existing?'): # os.system('source /usr/local/bin/virtualenvwrapper.sh') subprocess.call('v', shell=True) click.pause() click.secho('using project name: %s' % name.lower(), fg='green', nl=True) # maybe I should search the pwd for a requirements.txt file? subprocess.call(['mkvirtualenv', name], shell=True) click.pause()
def start(ctx, services, all, wait_time, no_vm, no_zt_dep, publishing_ip, assume_yes): """ Start selling a containerized service. \b Start selling a single service. $ 21 sell start <service_name> \b Start selling all available services. $ 21 sell start --all """ # display help command if no service is selected if len(services) == 0 and all is False: raise click.UsageError('No service selected.', ctx=ctx) # no-vm version coming soon if no_vm: raise click.UsageError('This mode is not yet supported.', ctx=ctx) # assign manager and installer from context manager = ctx.obj['manager'] installer = ctx.obj['installer'] if no_zt_dep: if publishing_ip is None: logger.info(click.style("--no-zt-dep must be used in " "conjunction with --publishing-ip <IP_TO_PUBLISH>.", fg=cli_helpers.PROMPT_COLOR)) sys.exit() if cli_helpers.running_old_sell(manager, installer): if click.confirm(click.style("It appears that you are running an old version of 21 sell.\n" "In order to continue using 21 sell, you must update the 21 " "VM.\nWould you like to delete the existing VM and create a " "new one?", fg=cli_helpers.WARNING_COLOR)): upgrade_21_sell(ctx, services, all, wait_time, no_vm) sys.exit() else: logger.info(click.style("Please note that your services may be unreachable " "without this update.", fg=cli_helpers.WARNING_COLOR)) sys.exit() logger.info(click.style("Checking dependencies.", fg=cli_helpers.TITLE_COLOR)) deps_list = installer.check_dependencies() if no_zt_dep: deps_list = [(name, installed) for name, installed in deps_list if name != 'Docker'] all_deps_installed = cli_helpers.package_check(deps_list, True) # install virtualbox, docker, and zerotier deps if not all_deps_installed: if assume_yes or click.confirm(click.style("Would you like to install the missing " "packages?", fg=cli_helpers.PROMPT_COLOR)): logger.info(click.style("Installing missing dependencies.", fg=cli_helpers.TITLE_COLOR)) all_installed = cli_helpers.install_missing_dependencies(deps_list, installer) if not all_installed: sys.exit() else: sys.exit() # pick up docker group permissions by forced logout if cli_helpers.check_needs_logout(installer): sys.exit() if isinstance(manager.machine, Two1MachineVirtual): logger.info(click.style("Checking virtual machine status.", fg=cli_helpers.TITLE_COLOR)) just_started = False vm_status = manager.status_machine() if vm_status == VmState.NOEXIST: if assume_yes or click.confirm(click.style(" 21 virtual machine does not exist. " "Would you like to create it?", fg=cli_helpers.PROMPT_COLOR)): vm_config = cli_helpers.get_vm_options() try: cli_helpers.start_long_running("Creating machine (this may take a few minutes)", manager.create_machine, "21", vm_config.disk_size, vm_config.vm_memory, vm_config.server_port) manager.write_machine_config(vm_config._asdict()) cli_helpers.print_str("21 virtual machine", ["Created"], "TRUE", True) except Two1MachineCreateException: cli_helpers.print_str("21 virtual machine", ["Not created"], "FALSE", False) vm_status = manager.status_machine() else: sys.exit() if vm_status != VmState.RUNNING: try: cli_helpers.start_long_running("Starting machine (this may take a few minutes)", manager.start_machine) just_started = True except Two1MachineStartException: cli_helpers.print_str("21 virtual machine", ["Not started"], "FALSE", False) sys.exit() vm_status = manager.status_machine() # check if machine running if vm_status == VmState.RUNNING: if just_started: cli_helpers.print_str("21 virtual machine", ["Started"], "TRUE", True) else: cli_helpers.print_str("21 virtual machine", ["Running"], "TRUE", True) else: sys.exit() else: server_port = cli_helpers.get_server_port() manager.write_machine_config({"server_port": server_port}) # connect to zerotier virtual network if not manager.status_networking(): if no_zt_dep: pass else: try: if not isinstance(manager.machine, Two1MachineVirtual): if assume_yes or click.confirm(click.style( "ZeroTier One virtual network service is not running. Would you like " "to start the service?", fg=cli_helpers.PROMPT_COLOR)): manager.start_networking() else: sys.exit() else: cli_helpers.start_long_running("Starting ZeroTier One", manager.start_networking) cli_helpers.print_str("ZeroTier One", ["Started"], "TRUE", True) except Two1MachineNetworkStartException: cli_helpers.print_str("ZeroTier One", ["Not started"], "FALSE", False) sys.exit() # join the 21mkt network if manager.get_market_address() == "": if no_zt_dep: pass else: if not isinstance(manager.machine, Two1MachineVirtual): if assume_yes or click.confirm(click.style( "21mkt network not connected. Would you like to join 21mkt?", fg=cli_helpers.PROMPT_COLOR)): logger.info("You might need to enter your superuser password.") manager.connect_market(ctx.obj["client"]) else: sys.exit() else: cli_helpers.start_long_running("Connecting to 21mkt", manager.connect_market, ctx.obj["client"]) if manager.get_market_address() != "": cli_helpers.print_str("21mkt", ["Joined"], "TRUE", True) else: cli_helpers.print_str("21mkt", ["Unable to join"], "FALSE", False) sys.exit() else: cli_helpers.print_str("21mkt", ["Joined"], "TRUE", True) # ensure docker service is running if manager.status_docker() is False: if assume_yes or click.confirm(click.style( "Docker service is not running. Would you like to start " "the service?", fg=cli_helpers.PROMPT_COLOR)): try: manager.start_docker() cli_helpers.print_str("Docker", ["Started"], "TRUE", True) except Two1MachineNetworkStartException: cli_helpers.print_str("Docker", ["Not started"], "FALSE", False) else: sys.exit() # generate machine wallet & initialize micropayments server logger.info(click.style("Initializing micropayments server.", fg=cli_helpers.TITLE_COLOR)) username, password = cli_helpers.get_user_credentials() # get user creds try: server_port = manager.get_server_port() except Exception: logger.info(click.style("Error: cannot read server port from file. Please try again or contact " "[email protected].", fg="magenta")) status_init, new_wallet_mnemonic = manager.initialize_server(username, password, server_port) if status_init == 0: # if new mnemonic has been generated if new_wallet_mnemonic is not None: logger.info(click.style("\nA unique machine wallet has been generated for your micropayments " "server.\nPlease write down the following mnemonic and store it in " "a safe place:\n", fg=cli_helpers.PROMPT_COLOR)) logger.info(click.style(" {}\n".format(new_wallet_mnemonic), fg="magenta")) click.pause() else: logger.info(click.style("Error initializing micropayments server. Please try again or " "contact [email protected].", fg="magenta")) sys.exit() # check that services to start are available available_services = manager.get_available_services() if len(available_services) == 0: raise click.ClickException(click.style("Unable to fetch available services. Please try again or contact" " [email protected].", fg="magenta")) if not all: logger.info(click.style("Checking availability of selected services.", fg=cli_helpers.TITLE_COLOR)) available_selected_services = set(services) & available_services unavailable_selected_services = set(services) - available_services for available_selected_service in available_selected_services: cli_helpers.print_str(available_selected_service, ["Available"], "TRUE", True) for unavailable_selected_service in unavailable_selected_services: cli_helpers.print_str(unavailable_selected_service, ["Unavailable"], "False", False) if available_selected_services == set(services): service_to_pull = set(services) elif len(available_selected_services) > 0: if click.confirm(click.style("Not all selected services are available, would you like to start the" " available services anyways?", fg=cli_helpers.PROMPT_COLOR)): service_to_pull = available_selected_services else: raise click.Abort() else: raise click.ClickException(click.style("None of the services you've selected is available.", fg="magenta") + click.style(" Run", fg="magenta") + click.style(" `21 sell list`", bold=True, fg=cli_helpers.PROMPT_COLOR) + click.style(" to see available microservices.", fg="magenta")) else: service_to_pull = available_services # Pulling images for services in `service_to_pull` logger.info(click.style("Pulling images for selected services.", fg=cli_helpers.TITLE_COLOR)) service_to_start = set() for service_name in service_to_pull: image_for_service = manager.get_image(service_name) def image_sucessfully_pulled_hook(image): service_to_start.add(service_name) cli_helpers.print_str('%s -> %s' % (service_name, image), ["Pulled"], "TRUE", True) def image_failed_to_pull_hook(image): cli_helpers.print_str('%s -> %s' % (service_name, image), ["Failed to pull"], "False", False) def image_is_local_hook(image): service_to_start.add(service_name) cli_helpers.print_str('%s -> %s' % (service_name, image), ["Exists locally"], "TRUE", True) def image_is_malformed_hook(image): cli_helpers.print_str('%s -> %s' % (service_name, image), ["Malformed image name"], "False", False) manager.pull_image(image_for_service, image_sucessfully_pulled_hook, image_failed_to_pull_hook, image_is_local_hook, image_is_malformed_hook) if service_to_pull > service_to_start: if len(service_to_start) > 0: if not click.confirm(click.style("Not all Docker Hub images were successfully pulled for the services" " you've selected, would you like to start the services that had their" " images successfully pulled anyways?", fg=cli_helpers.PROMPT_COLOR)): raise click.Abort() else: raise click.ClickException(click.style("None of the Docker Hub images were successfully pulled for the" " services you've selected.", fg="magenta")) # Start services for services in `service_to_start` logger.info(click.style("Starting services.", fg=cli_helpers.TITLE_COLOR)) try: manager.start_services(service_to_start, cli_helpers.failed_to_start_hook, cli_helpers.started_hook, cli_helpers.failed_to_restart_hook, cli_helpers.restarted_hook, cli_helpers.failed_to_up_hook, cli_helpers.up_hook) except: raise click.ClickException(click.style("Unable to start services.", fg="magenta")) try: started_services = manager.get_running_services() except: raise click.ClickException(click.style("Unable to fetch running services.", fg="magenta")) # prompt to publish services published_stats = cli_helpers.prompt_to_publish(started_services, manager, publishing_ip, assume_yes=assume_yes) for stat in published_stats: cli_helpers.print_str(stat[0], stat[2], "TRUE" if stat[1] else "FALSE", stat[1]) # help tip message logger.info(click.style("\nTip: (1) run ", fg=cli_helpers.PROMPT_COLOR) + click.style("`21 publish list`", bold=True, fg=cli_helpers.PROMPT_COLOR) + click.style(" to see your published services.\n", fg=cli_helpers.PROMPT_COLOR) + click.style(" (2) run ", fg=cli_helpers.PROMPT_COLOR) + click.style("`21 sell status --detail`", bold=True, fg=cli_helpers.PROMPT_COLOR) + click.style(" to see your microservice balances.", fg=cli_helpers.PROMPT_COLOR))
def install(ctx, force, gen_inventory): oo_cfg = ctx.obj['oo_cfg'] verbose = ctx.obj['verbose'] if ctx.obj['unattended']: error_if_missing_info(oo_cfg) else: oo_cfg = get_missing_info_from_user(oo_cfg) check_hosts_config(oo_cfg, ctx.obj['unattended']) print_installation_summary(oo_cfg.deployment.hosts, oo_cfg.settings.get('variant_version', None)) click.echo('Gathering information from hosts...') callback_facts, error = openshift_ansible.default_facts(oo_cfg.deployment.hosts, verbose) if error or callback_facts is None: click.echo("There was a problem fetching the required information. " \ "Please see {} for details.".format(oo_cfg.settings['ansible_log_path'])) sys.exit(1) hosts_to_run_on, callback_facts = get_hosts_to_run_on( oo_cfg, callback_facts, ctx.obj['unattended'], force, verbose) # We already verified this is not the case for unattended installs, so this can # only trigger for live CLI users: # TODO: if there are *new* nodes and this is a live install, we may need the user # to confirm the settings for new nodes. Look into this once we're distinguishing # between new and pre-existing nodes. if not ctx.obj['unattended'] and len(oo_cfg.calc_missing_facts()) > 0: confirm_hosts_facts(oo_cfg, callback_facts) # Write quick installer config file to disk: oo_cfg.save_to_disk() # Write ansible inventory file to disk: inventory_file = openshift_ansible.generate_inventory(hosts_to_run_on) click.echo() click.echo('Wrote atomic-openshift-installer config: %s' % oo_cfg.config_path) click.echo("Wrote ansible inventory: %s" % inventory_file) click.echo() if gen_inventory: sys.exit(0) click.echo('Ready to run installation process.') message = """ If changes are needed please edit the config file above and re-run. """ if not ctx.obj['unattended']: confirm_continue(message) error = openshift_ansible.run_main_playbook(inventory_file, oo_cfg.deployment.hosts, hosts_to_run_on, verbose) if error: # The bootstrap script will print out the log location. message = """ An error was detected. After resolving the problem please relaunch the installation process. """ click.echo(message) sys.exit(1) else: message = """ The installation was successful! If this is your first time installing please take a look at the Administrator Guide for advanced options related to routing, storage, authentication and much more: http://docs.openshift.com/enterprise/latest/admin_guide/overview.html """ click.echo(message) click.pause()
def cli(): click.pause()