Ejemplo n.º 1
0
def get_initial_config_params():
    ''' Get initial config params from user. '''

    questions = [
        Text(
            'project_name',
            message='Enter your project_name',
        ),
        Text('user',
             message='Enter your SSH username',
             default=DEFAULT_CONFIG['user']),
        Text('ssh_port',
             message='Enter SSH port',
             default=DEFAULT_CONFIG['port']),
        List('deployment_preset',
             message='Select your deployment preset',
             choices=[presets.WEB, presets.NODE, presets.REMOTE_SOURCE]),
        Text('deployment_base_dir',
             message='Enter your base directory for deployment',
             default=DEFAULT_CONFIG['deployment']['base_dir'])
    ]

    answers = prompt(questions)

    return answers
Ejemplo n.º 2
0
    def ask_questions(self):
        questions = [
            Text(
                'name',
                message="What's your package name",
                validate=lambda _, x: check_pkgname(x)),
            Text(
                'author',
                message="What's the name of package's author",
                default=get_full_name()),
            Text(
                'author_email',
                message="What's the e-mail of package's author",
                default=get_email(),
                validate=lambda _, x: validate_email(x)),
            Text('description', message="Brief description the package"),
            Text(
                'version',
                message="What's the initial version",
                default="0.1.0",
                validate=lambda _, x: check_version(x)),
            List(
                'license',
                message="What's the package license",
                choices=LICENSES,
                default="MIT"),
        ]
        answers = prompt(questions)
        if answers is None:
            return False

        self._metadata.update(answers)

        return True
Ejemplo n.º 3
0
    def create(self) -> dict:
        """ 
        >>> QuizRouter().create()
        Displays a text field which accepts input for the quiz name and returns a dictionary witk keys: question, options and answer
        """

        questions = [
            Text(name="question", message="Enter question"),
            Text(name="options", message="Enter options"),
            Text(name="answer", message="Enter answer")
        ]

        return prompt(questions)
def add_new_contact():
    """Add a new contact to the contact book."""

    # When creating a multiple choice question from the next two
    # functions, there is a logical phallacy that a contact could
    # be part of the favourites list, but not the entries list,
    # which I am going to ignore for the sake of simplicity.
    def save_new_contact(new_contact):
        """Save new contact."""
        entries.append(new_contact)
        print("New contact saved.")

    def add_new_contact_to_favourites(new_contact):
        """Add new contact to favourites."""
        favourites.append(new_contact)
        print("New contact successfully added to favourites.")

    # `QuestionsCatalogue` takes a list of any questions made from
    # either an inquirer or an inquirer-executor class.
    answers_and_functions = QuestionsCatalogue(
        [
            Text("first_name", message="First name"),
            Text("last_name", message="Last name"),
            Text("phone", message="phone number"),
            Text("email", message="email address"),
            Text("known_for", message="known for"),
            InqExCheckbox(
                "What do you want to do with this contact?",
                [save_new_contact, add_new_contact_to_favourites],
            ),
        ]
    ).prompt_all()

    # Unpacking the returned tuple into variables
    answers, list_of_functions = answers_and_functions

    # Creating a new instance for our new contact
    new_contact = Entry.create(
        answers["first_name"],
        answers["last_name"],
        answers["known_for"],
        email=answers["email"],
        phone=answers["phone"],
    )

    # Executing all the functions the user has checked.
    for function in list_of_functions:
        function(new_contact)
 def change_number(self):
     """Change the phone number for this contact."""
     # If you are thinking: "Wouldn't a simple `input` call do it here?"
     # Yes it would, but that's not what we are doing here, is it? ;)
     self.phone = prompt(
         [Text("new_number", message="Please enter the new phone number")]
     )["new_number"]
 def change_email(self):
     """Change the email for this contact."""
     # If you are thinking: "Wouldn't a simple `input` call do it here?"
     # Yes it would, but that's not what we are doing here, is it? ;)
     self.email = prompt(
         [Text("new_email", message="Please enter the new email adress")]
     )["new_email"]
Ejemplo n.º 7
0
def main(host, user, password):
    questions = [Checkbox('tags', message='Tags', choices=get_tags())]
    tags = prompt(questions)['tags']
    questions = []
    extra_vars, passwords = get_vars(tags)
    for var in extra_vars:
        questions.append(Text(var, var))
    extra_vars = prompt(questions)
    for item in passwords:
        extra_vars[item] = gen_pass()

    command = ['ansible-playbook', '-i %s,' % host, '-t %s' % ','.join(tags)]
    if extra_vars:
        command.append('-e "%s"' % ' '.join(
            ('%s=%s' % (k, v) for k, v in extra_vars.items())))
    if user is not None:
        command.append('-u %s' % user)

    if password:
        command.append('-k')

    command.append('ansible.yml')
    res = ' '.join(command)
    pbcopy(res)
    echo('The follow command has been copied to clipboard:')
    echo(res)
Ejemplo n.º 8
0
    def update(self, id) -> dict:
        """ 
        >>> QuizRouter().update(id: int)
        Accpets int argument, id which is used in the message
        Displays a text field which accepts input for the quiz name and returns a dictionary witk keys: question, options and answer
        """

        questions = [
            Text(name="question",
                 message=f"Enter new question for quiz with ID={id}"),
            Text(name="options",
                 message=f"Enter new options for quiz with ID={id}"),
            Text(name="answer",
                 message=f"Enter new answer for quiz with ID={id}")
        ]

        return prompt(questions)
Ejemplo n.º 9
0
def select_vm_clone(vms):
    answers = select_vm(vms, 'Select a VM to clone')

    questions = [
        Text(name='count', message='Number of clones', validate=clone_count)
    ]

    answers.update(prompt(questions, theme=GreenPassion()))
    return answers
Ejemplo n.º 10
0
def get_credentials():
    questions = []
    answers = []

    if not Config.PC_HOST:
        questions.append(
            Text(name='pc_host',
                 message='IP address or host name of Prism Element',
                 validate=input_required))
    else:
        answers.append({'pc_host': Config.PC_HOST})

    if not Config.PC_PORT:
        questions.append(
            Text(name='pc_port',
                 message='HTTPS port for Prism Element',
                 default='9440',
                 validate=input_required))
    else:
        answers.append({'pc_port': Config.PC_PORT})

    if not Config.USERNAME:
        questions.append(
            Text(name='username',
                 message='Prism Element username',
                 validate=input_required))
    else:
        answers.append({'username': Config.USERNAME})

    if not Config.PASSWORD:
        questions.append(
            Password(name='password',
                     message='Password for Prism Element',
                     validate=input_required))
    else:
        answers.append({'password': Config.PASSWORD})

    answers.append(prompt(questions, theme=GreenPassion()))
    cred = {}
    for answer in answers:
        for key, value in answer.items():
            cred[key] = value

    return cred
Ejemplo n.º 11
0
    def create(self) -> dict:
        """ 
        >>> Category().create()
        Displays a text field which accepts input for the category name and returns a dictionary witk key, name
        """

        questions = [
            Text(name="name", message="Enter category name"),
        ]

        return prompt(questions)
Ejemplo n.º 12
0
def generate_options(rhost: str) -> dict:
    """
        dnsrecon -d {HOSTNAME} -n {Nameserver IP} -j {json file}
    """

    questions = list()

    pre_questions = [
        Confirm("use_ip",
                default=True,
                message="Use IP {0} for Name Server".format(rhost)),
    ]

    pre_answers = prompt(pre_questions)

    # If we decided against using an IP
    if not pre_answers["use_ip"]:
        questions.append(Text("name_server", message="Input Name Server"))

    # Are there items that match etc host defs
    domains = Util().ip_to_domains(rhost)
    if domains:
        questions.append(
            Checkbox("domains",
                     message="Input domain to search",
                     choices=domains))
    else:
        questions.append(Text("domains", message="Input domain to search"))

    answers = prompt(questions)

    # annotate answers
    if pre_answers["use_ip"]:
        answers["name_server"] = rhost

    # if we put in only one domain name then turn it into a list
    if not hasattr(answers["domains"], "sort"):
        answers["domains"] = [answers["domains"]]

    return answers
Ejemplo n.º 13
0
 def __init__(self, hp=100, atk=11):
     self.name = prompt([Text("name", message="How may I address you?")])["name"]
     # The prompt_and_execute() method directly returns
     # the return value of the chosen option.
     self.role = InqExList(
         "In what martial art style have you been educated?",
         [choose_assassin, choose_berserker, choose_mage],
     ).prompt_and_execute()
     self.weapon = InqExList(
         "What is your weapon of choice?", [choose_ax, choose_sword, choose_mace]
     ).prompt_and_execute()
     self.hp = hp
     self.atk = atk
Ejemplo n.º 14
0
    def update(self, id) -> dict:
        """ 
        >>> Category().update(id: int)
        Accpets int argument, id which is used in the message
        Displays a text field which accepts input for the category name and returns a dictionary witk key, name
        """

        questions = [
            Text(name="name",
                 message=f"Enter new name for category with ID={id}")
        ]

        return prompt(questions)
Ejemplo n.º 15
0
    def get_user_inputs(self):
        for i in range(self.number_of_func):
            print("")
            print(CVIOLET + "Enter Params for Function " + str(i + 1) + CEND)
            print("")
            _input = {}

            question = [
                List('type',
                     message="Which function type to run?",
                     choices=['magnitude', 'categorical']),
                Text('start',
                     message="Bioperiod Start Date. Example: 10/20",
                     validate=lambda _, d: d is not ''),
                Text('end',
                     message="Bioperiod End Date. Example: 06/20",
                     validate=lambda _, d: d is not '')
            ]

            answers = prompt(question)
            _input["type"] = answers['type']
            _input["bioperiod_start_date"] = answers['start']
            _input["bioperiod_end_date"] = answers['end']

            cate_question = [
                Text('binnings',
                     message="Define the binnings. Example: 0.3, 0.5 ",
                     validate=lambda _, d: d is not ''),
            ]
            if answers['type'] == 'categorical':
                cate_answer = prompt(cate_question)
                _input["binnings"] = [
                    float(x.strip())
                    for x in cate_answer['binnings'].split(',')
                ]
                _input["binnings"].insert(0, 0)

            self.user_inputs["func_" + str(i)] = _input
    def setUp(self):
        def return_one():
            """Return 1"""
            return 1

        def return_two():
            """Return 2"""
            return 2

        def return_three():
            """Return 3"""
            return 3

        def return_four():
            """Return 4"""
            return 4

        def return_five():
            """Return 5"""
            return 5

        self.inqex_checkbox = InqExCheckbox.from_iterable(
            "What do you want to return?", [return_one, return_two])
        self.inqex_list = InqExList.from_iterable(
            "What do you want to return?",
            [return_three, return_four, return_five])
        self.text_question_first_name = Text("first_name",
                                             message="What's your first name")
        self.text_question_last_name = Text("last_name",
                                            message="What's your last name")

        self.questions_catalogue = QuestionsCatalogue([
            self.inqex_checkbox,
            self.inqex_list,
            self.text_question_first_name,
            self.text_question_last_name,
        ])
Ejemplo n.º 17
0
    def get_user_inputs(self):
        # inquirer questions for hydrologic_variable, binning, and functional_bin_number
        print('')
        questions = [
            List(
                'hydrologic_variable',
                message="Which hydrologic variable?",
                choices=['d: depth', 'v: velocity', 't: shear stress'],
            ),
            Text('binning',
                 message="Define the binning. Example: 1.2, 2.1 ",
                 validate=lambda _, d: d is not ''),
            Text('functional_bin_number',
                 message="Input functional bin number. Example: 0 or 1",
                 validate=lambda _, d: will_it_float(d)),
        ]

        answers = prompt(questions)
        # parse answers to desired values
        self.hydrologic_variable = answers['hydrologic_variable'][0]
        self.binning = [
            float(x.strip()) for x in answers['binning'].split(',')
        ]
        self.functional_bin_number = int(answers['functional_bin_number'])
Ejemplo n.º 18
0
from textfsm import TextFSM
from netmiko import ConnectHandler
from inquirer import prompt, Text, Password
from networkx import draw, Graph
from matplotlib.pyplot import show

while True:
    questions = [
        Text(name='ip_file', message="Input your ip file list"),
    ]

    answers = prompt(questions)

    try:
        ip_file = open(answers['ip_file'], 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

account = [
    Text(name='username', message="Input your username"),
    Password(name='password', message="Input your password")
]

credential = prompt(account)

list_ip = [line.strip() for line in ip_file]

graph = Graph()