Python getpass.getpass() Examples

The following are 30 code examples of getpass.getpass(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module getpass , or try the search function .
Example #1
Source File: ex2_paramiko.py    From python_course with Apache License 2.0 8 votes vote down vote up
def main():
    """Use Paramiko to change 'logging buffered <size>' configuration."""
    try:
        ip_addr = raw_input("Enter IP address: ")
    except NameError:
        ip_addr = input("Enter IP address: ")
    username = 'pyclass'
    password = getpass()
    port = 22

    remote_conn_pre = paramiko.SSHClient()
    remote_conn_pre.load_system_host_keys()

    remote_conn_pre.connect(ip_addr, port=port, username=username, password=password,
                            look_for_keys=False, allow_agent=False)
    remote_conn = remote_conn_pre.invoke_shell()

    time.sleep(1)
    clear_buffer(remote_conn)
    disable_paging(remote_conn)

    send_command(remote_conn, cmd='conf t')
    send_command(remote_conn, cmd='logging buffered 20010')
    send_command(remote_conn, cmd='end')

    output = send_command(remote_conn, cmd='show run | inc logging', delay=2)
    print('\n>>>>')
    print(output)
    print('>>>>\n') 
Example #2
Source File: ex8_netmiko.py    From python_course with Apache License 2.0 7 votes vote down vote up
def main():
    """
    Use Netmiko to change the logging buffer size and to disable console logging
    from a file for both pynet-rtr1 and pynet-rtr2
    """
    password = getpass()

    # Get connection parameters setup correctly
    for a_dict in (pynet1, pynet2, juniper_srx):
        a_dict['password'] = password
        a_dict['verbose'] = False

    for a_device in (pynet1, pynet2):
        net_connect = ConnectHandler(**a_device)
        net_connect.send_config_from_file(config_file='config_file.txt')

        # Verify configuration
        output = net_connect.send_command("show run | inc logging")
        print()
        print('#' * 80)
        print("Device: {}:{}".format(net_connect.ip, net_connect.port))
        print()
        print(output)
        print('#' * 80)
        print() 
Example #3
Source File: ex7_netmiko.py    From python_course with Apache License 2.0 7 votes vote down vote up
def main():
    """Use Netmiko to change the logging buffer size on pynet-rtr2."""
    password = getpass()

    # Get connection parameters setup correctly
    for a_dict in (pynet1, pynet2, juniper_srx):
        a_dict['password'] = password
        a_dict['verbose'] = False

    net_connect = ConnectHandler(**pynet2)
    config_commands = ['logging buffered 20000']
    net_connect.send_config_set(config_commands)

    output = net_connect.send_command("show run | inc logging buffer")
    print()
    print('#' * 80)
    print("Device: {}:{}".format(net_connect.ip, net_connect.port))
    print()
    print(output)
    print('#' * 80)
    print() 
Example #4
Source File: ex6_netmiko.py    From python_course with Apache License 2.0 7 votes vote down vote up
def main():
    """Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx."""
    password = getpass()

    # Get connection parameters setup correctly
    for a_dict in (pynet1, pynet2, juniper_srx):
        a_dict['password'] = password
        a_dict['verbose'] = False

    print("\nStart time: " + str(datetime.now()))
    for a_device in (pynet1, pynet2, juniper_srx):
        net_connect = ConnectHandler(**a_device)
        output = net_connect.send_command("show arp")
        print()
        print('#' * 80)
        print("Device: {}:{}".format(net_connect.ip, net_connect.port))
        print()
        print(output)
        print('#' * 80)
        print()

    print("\nEnd time: " + str(datetime.now())) 
Example #5
Source File: zoomeye.py    From vulscan with MIT License 6 votes vote down vote up
def zoomeye_api_test():
    zoomeye = ZoomEye()
    zoomeye.username = raw_input('ZoomEye Username: ')
    zoomeye.password = getpass.getpass(prompt='ZoomEye Password: ')
    zoomeye.login()
    print(zoomeye.resources_info())

    data = zoomeye.dork_search('solr')
    show_site_ip(data)

    data = zoomeye.dork_search('country:cn')
    show_site_ip(data)

    data = zoomeye.dork_search('solr country:cn')
    show_site_ip(data)

    data = zoomeye.dork_search('solr country:cn', resource='host')
    show_ip_port(data)


# zoomeye_api_test() 
Example #6
Source File: jira.py    From Matrix-NEB with Apache License 2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(JiraPlugin, self).__init__(*args, **kwargs)
        self.store = KeyValueStore("jira.json")
        self.rooms = RoomContextStore(
            [JiraPlugin.TYPE_TRACK, JiraPlugin.TYPE_EXPAND]
        )

        if not self.store.has("url"):
            url = raw_input("JIRA URL: ").strip()
            self.store.set("url", url)

        if not self.store.has("user") or not self.store.has("pass"):
            user = raw_input("(%s) JIRA Username: " % self.store.get("url")).strip()
            pw = getpass.getpass("(%s) JIRA Password: " % self.store.get("url")).strip()
            self.store.set("user", user)
            self.store.set("pass", pw)

        self.auth = (self.store.get("user"), self.store.get("pass"))
        self.regex = re.compile(r"\b(([A-Za-z]+)-\d+)\b") 
Example #7
Source File: getauth.py    From macops with Apache License 2.0 6 votes vote down vote up
def _GetPasswordInteractively(prompt='Password: ', hidden=True,
                              input_fn=raw_input):
  """Application specific getpass.

  Args:
    prompt: string with the password prompt
    hidden: bool whether to show user input
    input_fn: function to get user input, used in testing
  Returns:
    password as string
  Raises:
    KeyboardInterrupt: User cancelled request with keyboard interrupt (Ctrl+C)
    EOFError: If password is empty
  """
  if hidden:
    password = getpass.getpass(prompt)
  else:
    password = input_fn(prompt)
  return password 
Example #8
Source File: node.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def set_password(ctx):
    """
    Change the local admin password.

    Set the password required by `pdtools node login` and the local
    web-based administration page.
    """
    username = builtins.input("Username: ")
    while True:
        password = getpass.getpass("New password: ")
        confirm = getpass.getpass("Confirm password: ")

        if password == confirm:
            break
        else:
            print("Passwords do not match.")

    click.echo("Next, if prompted, you should enter the current username and password.")
    client = ctx.obj['client']
    result = client.set_password(username, password)
    click.echo(util.format_result(result))
    return result 
Example #9
Source File: utils.py    From S4 with GNU General Public License v3.0 6 votes vote down vote up
def get_input(*args, secret=False, required=False, blank=False, **kwargs):
    """
    secret: Don't show user input when they are typing.
    required: Keep prompting if the user enters an empty value.
    blank: turn all empty strings into None.
    """

    while True:
        if secret:
            value = getpass.getpass(*args, **kwargs)
        else:
            value = input(*args, **kwargs)

        if blank:
            value = value if value else None

        if not required or value:
            break

    return value 
Example #10
Source File: getauth.py    From macops with Apache License 2.0 6 votes vote down vote up
def _GetPasswordGUI(title='Password', text='Enter your password', hidden=True):
  """Application and platform specific GUI getpass.

  Args:
    title: string for title of window
    text: string for promp text
    hidden: bool whether to show user input
  Returns:
    password as string
  """
  pwprompt = cocoadialog.Standard_InputBox()
  if hidden:
    pwprompt.SetPasswordBox()
  pwprompt._title = title  # pylint: disable=protected-access
  pwprompt._informative_text = text  # pylint: disable=protected-access
  output = pwprompt.Show()
  password = output.split('\n')[1]
  return password 
Example #11
Source File: telegram_dumper.py    From telegram-messages-dump with MIT License 6 votes vote down vote up
def _init_connect(self):
        """ Connect to the Telegram server and Authenticate. """
        sprint('Connecting to Telegram servers...')
        if not self.connect():
            sprint('Initial connection failed.')

        # Then, ensure we're authorized and have access
        if not self.is_user_authorized():
            sprint('First run. Sending code request...')
            self.send_code_request(self.settings.phone_num)
            self_user = None
            while self_user is None:
                code = input('Enter the code you just received: ')
                try:
                    self_user = self.sign_in(self.settings.phone_num, code)
                # Two-step verification may be enabled
                except SessionPasswordNeededError:
                    pw = getpass("Two step verification is enabled. "
                                 "Please enter your password: ")
                    self_user = self.sign_in(password=pw) 
Example #12
Source File: device.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def password(ctx):
    """
    Change the router admin password.
    """
    url = ctx.obj['base_url'] + "/password/change"

    username = builtins.input("Username: ")
    while True:
        password = getpass.getpass("New password: ")
        confirm = getpass.getpass("Confirm password: ")

        if password == confirm:
            break
        else:
            print("Passwords do not match.")

    data = {
        "username": username,
        "password": password
    }
    router_request("POST", url, json=data) 
Example #13
Source File: firefox_decrypt.py    From firefox_decrypt with GNU General Public License v3.0 6 votes vote down vote up
def ask_password(profile, interactive):
    """
    Prompt for profile password
    """
    if not PY3:
        profile = profile.encode(SYS_ENCODING)

    passmsg = "\nMaster Password for profile {0}: ".format(profile)

    if sys.stdin.isatty() and interactive:
        passwd = getpass(passmsg)

    else:
        # Ability to read the password from stdin (echo "pass" | ./firefox_...)
        if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            passwd = sys.stdin.readline().rstrip("\n")
        else:
            LOG.warning("Master Password not provided, continuing with blank password")
            passwd = ""

    return py2_decode(passwd) 
Example #14
Source File: crypt.py    From pgrepup with GNU General Public License v3.0 6 votes vote down vote up
def _get_key():
    if this.key:
        return this.key

    secret = getpass.getpass()
    try:
        salt = config().get('Security', 'salt')
    except NoOptionError:
        salt = base64.urlsafe_b64encode(os.urandom(16))
        config().set('Security', 'salt', salt)

    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    this.key = base64.urlsafe_b64encode(kdf.derive(secret))
    return this.key 
Example #15
Source File: menu.py    From vault with MIT License 6 votes vote down vote up
def get_input(message='', secure=False, lowercase=False, check_timer=True, non_locking_values=[]):
    """
        Get and return user input
    """

    try:
        if secure:
            input_ = getpass.getpass(lock_prefix() + message)
        else:
            input_ = input(message)

        if check_timer and input_ not in non_locking_values:
            check_then_set_autolock_timer()
        else:
            set_autolock_timer()

        # Ensure the input is lowercased if required
        if lowercase:
            input_ = input_.lower()
    except KeyboardInterrupt:
        return False
    except Exception:  # Other Exception
        return False

    return input_ 
Example #16
Source File: automate_project.py    From project-automation with MIT License 6 votes vote down vote up
def GetCredentials():
    global repoName
    global private
    global username
    global password

    if repoName == "":
        repoName = input("Enter a name for the GitHub repository: ")
    if private == "":
        private = input("Private GitHub repository (y/n): ")
    while private != False and private != True:
        if private == "y":
            private = True
        elif private == "n":
            private = False
        else:
            print("{}Invalid value.{}".format(Fore.YELLOW, Fore.WHITE))
            private = input("Private GitHub repository (y/n): ")
    if username == "":
        username = input("Enter your GitHub username: ")
    if username == "" or password == "":
        password = getpass.getpass("Enter your GitHub password: ")


# creates GitHub repo if credentials are valid 
Example #17
Source File: create.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 6 votes vote down vote up
def get_value(prompt, default=None, hidden=False):
    '''Displays the provided prompt and returns the input from the user. If the
    user hits Enter and there is a default value provided, the default is
    returned.
    '''
    _prompt = '%s : ' % prompt
    if default:
        _prompt = '%s [%s]: ' % (prompt, default)

    if hidden:
        ans = getpass(_prompt)
    else:
        ans = raw_input(_prompt)

    # If user hit Enter and there is a default value
    if not ans and default:
        ans = default
    return ans 
Example #18
Source File: ui.py    From uptick with MIT License 6 votes vote down vote up
def get_terminal(text="Password", confirm=False, allowedempty=False):
    import getpass

    while True:
        pw = getpass.getpass(text)
        if not pw and not allowedempty:
            print_message("Cannot be empty!", "error")
            continue
        else:
            if not confirm:
                break
            pwck = getpass.getpass("Confirm " + text)
            if pw == pwck:
                break
            else:
                print_message("Not matching!", "warning")
    return pw 
Example #19
Source File: instaloader.py    From instaloader with MIT License 6 votes vote down vote up
def interactive_login(self, username: str) -> None:
        """Logs in and internally stores session, asking user for password interactively.

        :raises LoginRequiredException: when in quiet mode.
        :raises InvalidArgumentException: If the provided username does not exist.
        :raises ConnectionException: If connection to Instagram failed."""
        if self.context.quiet:
            raise LoginRequiredException("Quiet mode requires given password or valid session file.")
        try:
            password = None
            while password is None:
                password = getpass.getpass(prompt="Enter Instagram password for %s: " % username)
                try:
                    self.login(username, password)
                except BadCredentialsException as err:
                    print(err, file=sys.stderr)
                    password = None
        except TwoFactorAuthRequiredException:
            while True:
                try:
                    code = input("Enter 2FA verification code: ")
                    self.two_factor_login(code)
                    break
                except BadCredentialsException:
                    pass 
Example #20
Source File: exercise2_with_threads.py    From python_course with Apache License 2.0 6 votes vote down vote up
def main():
    password = getpass()
    start_time = datetime.now()

    hostnames = [
        'arista1.twb-tech.com',
        'arista2.twb-tech.com',
        'arista3.twb-tech.com',
        'arista4.twb-tech.com',
    ]

    print()
    print(">>>>>")
    for host in hostnames:
        net_device = create_device_dict(host, password)
        my_thread = threading.Thread(target=scp_file, args=(net_device,))
        my_thread.start()

    main_thread = threading.currentThread()
    for some_thread in threading.enumerate():
        if some_thread != main_thread:
            some_thread.join()
    print(">>>>>")

    print("\nElapsed time: " + str(datetime.now() - start_time)) 
Example #21
Source File: exercise3.py    From python_course with Apache License 2.0 6 votes vote down vote up
def main():
    password = getpass()

    filename = 'my_devices.yml'
    my_devices = read_yaml(filename)

    for hostname, net_device in my_devices.items():
        file_system = net_device.pop('file_system')
        net_device['password'] = password

        # Create the Netmiko SSH connection
        ssh_conn = ConnectHandler(**net_device)
        print()
        print(">>>>>")
        print(ssh_conn.find_prompt())

        # Transfer the IOS image to device
        source_file = "my_file.txt"
        dest_file = "my_file.txt"

        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            file_system=file_system,
            direction='put',
            overwrite_file=False,
        )

        md5_check = transfer_dict['file_verified']
        file_exists = transfer_dict['file_exists']

        if md5_check and file_exists:
            print("File successfully transferred to: {host}".format(**net_device))
        else:
            print("Failure on SCP: {host} !!!".format(**net_device))
        print(">>>>>") 
Example #22
Source File: exercise2.py    From python_course with Apache License 2.0 6 votes vote down vote up
def main():
    password = getpass()

    hostnames = [
        'arista1.twb-tech.com',
        'arista2.twb-tech.com',
        'arista3.twb-tech.com',
        'arista4.twb-tech.com',
    ]

    for host in hostnames:
        net_device = create_device_dict(host, password)
        file_system = net_device.pop('file_system')

        # Create the Netmiko SSH connection
        ssh_conn = ConnectHandler(**net_device)
        print()
        print(">>>>>")
        print(ssh_conn.find_prompt())

        # Transfer the IOS image to device
        source_file = "my_file.txt"
        dest_file = "my_file.txt"

        transfer_dict = file_transfer(
            ssh_conn,
            source_file=source_file,
            dest_file=dest_file,
            file_system=file_system,
            direction='put',
            overwrite_file=False,
        )

        md5_check = transfer_dict['file_verified']
        file_exists = transfer_dict['file_exists']

        if md5_check and file_exists:
            print("File successfully transferred to: {host}".format(**net_device))
        else:
            print("Failure on SCP: {host} !!!".format(**net_device))
        print(">>>>>") 
Example #23
Source File: ex4_snmp.py    From python_course with Apache License 2.0 6 votes vote down vote up
def main():
    """
    Create a script that connects to both routers (pynet-rtr1 and pynet-rtr2) and
    prints out both the MIB2 sysName and sysDescr.
    """
    try:
        ip_addr1 = raw_input("pynet-rtr1 IP address: ")
        ip_addr2 = raw_input("pynet-rtr2 IP address: ")
    except NameError:
        ip_addr1 = input("pynet-rtr1 IP address: ")
        ip_addr2 = input("pynet-rtr2 IP address: ")
    community_string = getpass.getpass(prompt="Community string: ")

    pynet_rtr1 = (ip_addr1, community_string, 161)
    pynet_rtr2 = (ip_addr2, community_string, 161)

    for a_device in (pynet_rtr1, pynet_rtr2):
        print("\n*********************")
        for the_oid in (SYS_NAME, SYS_DESCR):
            snmp_data = snmp_helper.snmp_get_oid(a_device, oid=the_oid)
            output = snmp_helper.snmp_extract(snmp_data)

            print(output)
        print("*********************")
    print() 
Example #24
Source File: ex3_telnet_class.py    From python_course with Apache License 2.0 6 votes vote down vote up
def main():
    """Convert the code from exercise2 to a class-based solution."""
    try:
        ip_addr = raw_input("IP address: ")
    except NameError:
        ip_addr = input("IP address: ")
    ip_addr = ip_addr.strip()
    username = 'pyclass'
    password = getpass.getpass()

    my_conn = TelnetConn(ip_addr, username, password)
    my_conn.login()
    my_conn.send_command()
    my_conn.disable_paging()
    output = my_conn.send_command('show ip int brief')

    print("\n\n")
    print(output)
    print("\n\n")

    my_conn.close_conn() 
Example #25
Source File: ex7_pynxos_config.py    From python_course with Apache License 2.0 6 votes vote down vote up
def main():
    password = getpass()
    nxos1 = {
        'host': 'nxos1.twb-tech.com',
        'username': 'pyclass',
        'password': password,
        'transport': 'https',
        'port': 8443,
    }
    nxos2 = {   # noqa
        'host': 'nxos2.twb-tech.com',
        'username': 'pyclass',
        'password': password,
        'transport': 'https',
        'port': 8443,
    }

    config_commands = ['interface Loopback99', 'ip address 172.31.254.99/32']
    for device in (nxos1,):
        nxapi_conn = Device(**device)
        nxapi_conn.config_list(config_commands)
        output = nxapi_conn.show('show run interface loopback99', raw_text=True)
        print(output) 
Example #26
Source File: ex3_pyez_facts.py    From python_course with Apache License 2.0 6 votes vote down vote up
def main():
    """Connect to Juniper device using PyEZ. Display device facts."""
    pwd = getpass()
    try:
        ip_addr = raw_input("Enter Juniper SRX IP: ")
    except NameError:
        ip_addr = input("Enter Juniper SRX IP: ")
    ip_addr = ip_addr.strip()

    juniper_srx = {
        "host": ip_addr,
        "user": "pyclass",
        "password": pwd
    }

    print("\n\nConnecting to Juniper SRX...\n")
    a_device = Device(**juniper_srx)
    a_device.open()
    pprint(a_device.facts)
    print() 
Example #27
Source File: tututils.py    From python-zhmcclient with Apache License 2.0 6 votes vote down vote up
def make_client(zhmc, userid=None, password=None):
    """
    Create a `Session` object for the specified HMC and log that on. Create a
    `Client` object using that `Session` object, and return it.

    If no userid and password are specified, and if no previous call to this
    method was made, userid and password are interactively inquired.
    Userid and password are saved in module-global variables for future calls
    to this method.
    """

    global USERID, PASSWORD  # pylint: disable=global-statement

    USERID = userid or USERID or \
        six.input('Enter userid for HMC {}: '.format(zhmc))
    PASSWORD = password or PASSWORD or \
        getpass.getpass('Enter password for {}: '.format(USERID))

    session = zhmcclient.Session(zhmc, USERID, PASSWORD)
    session.logon()
    client = zhmcclient.Client(session)
    print('Established logged-on session with HMC {} using userid {}'.
          format(zhmc, USERID))
    return client 
Example #28
Source File: bulkloader.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def AuthFunction(self,
                   raw_input_fn=raw_input,
                   password_input_fn=getpass.getpass):
    """Prompts the user for a username and password.

    Caches the results the first time it is called and returns the
    same result every subsequent time.

    Args:
      raw_input_fn: Used for dependency injection.
      password_input_fn: Used for dependency injection.

    Returns:
      A pair of the username and password.
    """
    self.auth_called = True
    return _AuthFunction(self.host, self.email, self.passin,
                         raw_input_fn, password_input_fn) 
Example #29
Source File: iam.py    From aegea with Apache License 2.0 5 votes vote down vote up
def create_user(args):
    if args.prompt_for_password:
        from getpass import getpass
        args.password = getpass(prompt="Password for IAM user {}:".format(args.username))
    else:
        args.password = generate_password()
    try:
        user = resources.iam.create_user(UserName=args.username)
        clients.iam.get_waiter('user_exists').wait(UserName=args.username)
        logger.info("Created new IAM user %s", user)
        print(BOLD("Generated new password for IAM user {}: {}".format(args.username, args.password)))
    except resources.iam.meta.client.exceptions.EntityAlreadyExistsException:
        user = resources.iam.User(args.username)
        logger.info("Updating existing IAM user %s", user)
    try:
        user.create_login_profile(UserName=user.name, Password=args.password, PasswordResetRequired=True)
    except resources.iam.meta.client.exceptions.EntityAlreadyExistsException:
        if args.reset_password:
            clients.iam.update_login_profile(UserName=user.name, Password=args.password, PasswordResetRequired=True)
            print(BOLD("Generated reset password for IAM user {}: {}".format(args.username, args.password)))
    for group in args.groups:
        try:
            group = resources.iam.create_group(GroupName=group)
            logger.info("Created new IAM group %s", group)
        except resources.iam.meta.client.exceptions.EntityAlreadyExistsException:
            group = resources.iam.Group(group)
        user.add_group(GroupName=group.name)
        logger.info("Added %s to %s", user, group) 
Example #30
Source File: authentication.py    From WebGPIO with GNU General Public License v3.0 5 votes vote down vote up
def inputPassword():
	password = getpass.getpass()
	print("Re-enter")
	repassword = getpass.getpass()

	if password != repassword:
		print("Passwords don't match. Try again")
		return inputPassword()
	return password