def suma(a, b): a = int(_raw_input("Ingrese primer numero: ")) b = int(_raw_input("Ingrese segundo numero: ")) print(a + b) return a + b
def prompt_credentials(device, user=None): """ Prompt for username, password and return them as Credentials namedtuple. :param device: Device or realm name to store :param user: (Optional) If set, use as default username """ if not device: raise MissingRealmName('You must specify a device/realm name.') creds = () print('\nUpdating credentials for device/realm %r' % device) user_default = '' if user: user_default = ' [%s]' % user username = getpass._raw_input('Username%s: ' % user_default) or user if username == '': print('\nYou must specify a username, try again!') return prompt_credentials(device, user=user) passwd = getpass.getpass('Password: '******'\nPassword cannot be blank, try again!') return prompt_credentials(device, user=username) creds = Credentials(username, passwd, device) return creds
def EncodePassword(loggingArcGisFlag=False, password=None): """ Encodage d'un mot de passe :param loggingArcGisFlag: Flag pour l'ajout des messages dans ArcGIS :param paramPassword : Mot de passe à encoder (si utilisation depuis une TBX ArcGIS Pro) :return passwordEncoded: Mot depasse encodé """ # Initialisation de la configuration scriptDirPath = os.path.dirname(os.path.realpath(__file__)) configFilePath = os.path.join(scriptDirPath, "Configuration.ini") config = ConfigTools(configFilePath) # Initialisation des logs logPath = __CheckParamFolder(config.getValue("MAIN", "LOG_DIR"), "Log") LogTool(printFlag=True, loggingFlag=True, loggingArcGisFlag=loggingArcGisFlag, loggingDirPath=logPath) LogTool.Instance().addInfo("==========================================================================") LogTool.Instance().addInfo("Encodage d'un mot de passe...") # Si pas utilisation depuis une TBX ArcGIS Pro alors on demande la valeur if(password == None): password = getpass._raw_input("Mot de passe à encoder ?") ##end if passwordEncoded = None if(password != None and len(password)>0): print("Mot de passe à encoder : {}".format(password)) passwordEncoded = CryptoTool.Encode(password) print("Mot de passe encodé : {}".format(passwordEncoded.decode("utf-8"))) ##end if LogTool.Instance().addInfo("==========================================================================") return passwordEncoded
def generate_password(self): from src.random_password import random_password as rp # TODO(climent): move the options to the config file def print_policy(policy): for i in policy: print "%s: %s" % (policy[i][0], policy[i][1]) policy = { "L": ["[L]efthand", True], "R": ["[R]ighthand", True], "U": ["[U]ppercase", True], "l": ["[l]owercase", True], "N": ["[N]umbers", True], "S": ["[S]ymbols", True], "s": ["[s]imple symbols", True], } response = None while True: if not response: passwd = rp().generate_password(password_policy=policy, pwlength=config.pwlength) print "Generated password: %s" % passwd response = getpass._raw_input("Accept [y/./ENTER] > ") if response in policy: policy[response][1] = not policy[response][1] print_policy(policy) continue if response == ".": print_policy(policy) if response.lower() == "y": return passwd
def custom_fallback(prompt="Password: "******"Unable to hide password. Make sure no-one else can see your screen!",1,False) res = getpass._raw_input(prompt) os.system("cls" if os.name == "nt" else "clear") print ( "Gaza101's Scratch Statistics Server v"+ver +"\nWith thanks to Dylan5797 and DadOfMrLog\n" ) return res
def encode_password(): """ Encodage d'un mot de passe """ # Initialisation de la configuration script_dir_path = os.path.dirname(os.path.realpath(__file__)) config_file_path = os.path.join(script_dir_path, "Configuration.ini") config = ConfigTools(config_file_path) # Initialisation des logs log_path = _check_param_folder(config.get_value("MAIN", "LOG_DIR"), "Log") LogTool(printFlag=True, loggingFlag=True, loggingDirPath=log_path) LogTool.instance().init("Encodage d'un mot de passe") # Demande du mot de passe password = getpass._raw_input("Mot de passe à encoder ?") if password != None and len(password) > 0: LogTool.instance().add_info( "Mot de passe à encoder : {}".format(password)) password_encoded = CryptoTool.encode(password) LogTool.instance().add_info("Mot de passe encodé : {}".format( password_encoded.decode("utf-8"))) # end if LogTool.instance().finalize()
def create_vault(self): if os.path.isfile(self.vault_file_name): print("Overwriting %s ..." % self.vault_file_name) try: answer = getpass._raw_input("Continue? [y/N] > ") if answer.lower() != "y": print(" exit requested... exiting.") sys.exit(0) except (KeyboardInterrupt, EOFError): print(" exit requested... exiting.") sys.exit(0) else: print("Creating %s ..." % self.vault_file_name) self.vault_password = self.get_vault_password( require_confirmation=True) #self.vault_modified = True # If the file exists, this will create a new empty vault, which we then # open with the constructor if os.path.isfile(self.vault_file_name): Vault.create(self.vault_password, filename=self.vault_file_name) self.vault = Vault(self.vault_password, filename=self.vault_file_name) print("... Done.\n")
def generate_password(self): from src.random_password import random_password as rp # TODO(climent): move the options to the config file def print_policy(policy): for i in policy: print('%s: %s' % (policy[i][0], policy[i][1])) policy = { 'L': ['[L]efthand', True], 'R': ['[R]ighthand', True], 'U': ['[U]ppercase', True], 'l': ['[l]owercase', True], 'N': ['[N]umbers', True], 'S': ['[S]ymbols', True], 's': ['[s]imple symbols', True] } response = None while True: if not response: passwd = rp().generate_password(password_policy=policy, pwlength=config.pwlength) print("Generated password: %s" % passwd) response = getpass._raw_input('Accept [y/./ENTER] > ') if response in policy: policy[response][1] = not policy[response][1] print_policy(policy) continue if response == ".": print_policy(policy) if response.lower() == "y": return passwd
def unix_getpass(prompt='Password: '******'Password: '******'/dev/tty', os.O_RDWR|os.O_NOCTTY) tty = os.fdopen(fd, 'w+', 1) input = tty if not stream: stream = tty except EnvironmentError as e: # If that fails, see if stdin can be controlled. try: fd = sys.stdin.fileno() except (AttributeError, ValueError): passwd = fallback_getpass(prompt, stream) input = sys.stdin if not stream: stream = sys.stderr if fd is not None: passwd = None try: old = termios.tcgetattr(fd) # a copy to save new = old[:] #new[3] &= ~(termios.ECHO|termios.ISIG) # 3 == 'lflags' new[3] &= ~termios.ECHO # 3 == 'lflags'; is like (~termios.ECHO)|termios.ISIG tcsetattr_flags = termios.TCSAFLUSH if hasattr(termios, 'TCSASOFT'): tcsetattr_flags |= termios.TCSASOFT try: termios.tcsetattr(fd, tcsetattr_flags, new) passwd = getpass._raw_input(prompt, stream, input=input) # finally: termios.tcsetattr(fd, tcsetattr_flags, old) stream.flush() # issue7208 except termios.error: if passwd is not None: # _raw_input succeeded. The final tcsetattr failed. Reraise # instead of leaving the terminal in an unknown state. raise # We can't control the tty or stdin. Give up and use normal IO. # fallback_getpass() raises an appropriate warning. del input, tty # clean up unused file objects before blocking passwd = fallback_getpass(prompt, stream) stream.write('\n') return passwd
def custom_fallback(prompt="Password: "******"Unable to hide password. Make sure no-one else can see your screen!", 1, False) res = getpass._raw_input(prompt) os.system("cls" if os.name == "nt" else "clear") print("Gaza101's Scratch Comments Server v" + ver + "\nWith thanks to Dylan5797 and DadOfMrLog\n") return res
def challenge(): try: u = getpass._raw_input("\n\nEnter username: ") p = getpass.getpass() except Exception as err: print('ERROR:', err) else: print('You entered:', u, p)
def main(): parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('-f', '--filename', help='file generated with nmap -oX', required=True) parser.add_argument('-H', '--hosturl', help='hosturl for logging in to nessus server', default="https://127.0.0.1:8834") parser.add_argument( '-n', '--scanname', help='name for the scan in nessus, default is nmap_xml_<date>', required=False) parser.add_argument( '-P', '--policy', help= 'Nessus policy that is prepared with script_id(33818) Nmap (XML file importer)', default="nmap_xml") parser.add_argument('-p', '--password', help='password for logging in to nessus server', required=False) parser.add_argument('-u', '--user', help='username for logging in to nessus server', required=False) args = vars(parser.parse_args()) print args if not args['hosturl']: args['hosturl'] = getpass._raw_input('Hosturl: ') if not args['user']: args['user'] = getpass._raw_input('User: '******'password']: args['password'] = getpass.getpass() if not args['scanname']: args['scanname'] = "nmap_xml_%s" % datetime.now().strftime( "%Y%m%d-%H%M%S") print args startscan(args)
def tty_entry(tty_name, prompt): # Copied from https://github.com/python/cpython/blob/3.6/Lib/getpass.py # Make tty configurable, derive defaults from None tty_name = tty_name or '/dev/tty' stream = None passwd = None with contextlib.ExitStack() as stack: try: # Always try reading and writing directly on the tty first. fd = os.open(tty_name, os.O_RDWR | os.O_NOCTTY) tty = io.FileIO(fd, 'w+') stack.enter_context(tty) input = io.TextIOWrapper(tty) stack.enter_context(input) if not stream: stream = input except OSError as e: # If that fails, see if stdin can be controlled. stack.close() try: fd = sys.stdin.fileno() except (AttributeError, ValueError): fd = None passwd = fallback_getpass(prompt, stream) input = sys.stdin if not stream: stream = sys.stderr if fd is not None: try: old = termios.tcgetattr(fd) # a copy to save new = old[:] new[3] &= ~termios.ECHO # 3 == 'lflags' tcsetattr_flags = termios.TCSAFLUSH if hasattr(termios, 'TCSASOFT'): tcsetattr_flags |= termios.TCSASOFT try: termios.tcsetattr(fd, tcsetattr_flags, new) passwd = _raw_input(prompt, stream, input=input) finally: termios.tcsetattr(fd, tcsetattr_flags, old) stream.flush() # issue7208 except termios.error: if passwd is not None: # _raw_input succeeded. The final tcsetattr failed. Reraise # noqa # instead of leaving the terminal in an unknown state. raise # We can't control the tty or stdin. Give up and use normal IO. # noqa # fallback_getpass() raises an appropriate warning. if stream is not input: # clean up unused file objects before blocking stack.close() passwd = fallback_getpass(prompt, stream) stream.write('\n') return passwd
def upload(self): """ Upload the site to the server. """ self.clean() self.build() self.pluginMethod('preDeploy', self) # Get access information from the config or the user awsAccessKey = self.config.get('aws-access-key') or \ raw_input('Amazon access key (http://bit.ly/Agl7A9): ').strip() awsSecretKey = getpassword('aws', awsAccessKey) or \ getpass._raw_input('Amazon secret access key (will be saved in keychain): ').strip() # Try to fetch the buckets with the given credentials connection = boto.connect_s3(awsAccessKey.strip(), awsSecretKey.strip()) # Exit if the information was not correct try: buckets = connection.get_all_buckets() except: logging.info('Invalid login credentials, please try again...') return # If it was correct, save it for the future self.config.set('aws-access-key', awsAccessKey) self.config.write() setpassword('aws', awsAccessKey, awsSecretKey) awsBucketName = self.config.get('aws-bucket-name') or \ raw_input('S3 bucket name (www.yoursite.com): ').strip().lower() if awsBucketName not in [b.name for b in buckets]: if raw_input('Bucket does not exist, create it? (y/n): ') == 'y': try: awsBucket = connection.create_bucket(awsBucketName, policy='public-read') except boto.exception.S3CreateError, e: logging.info('Bucket with name %s already is used by someone else, please try again with another name' % awsBucketName) return # Configure S3 to use the index.html and error.html files for indexes and 404/500s. awsBucket.configure_website('index.html', 'error.html') self.config.set('aws-bucket-website', awsBucket.get_website_endpoint()) self.config.set('aws-bucket-name', awsBucketName) self.config.write() logging.info('Bucket %s was selected with website endpoint %s' % (self.config.get('aws-bucket-name'), self.config.get('aws-bucket-website'))) logging.info('You can learn more about s3 (like pointing to your own domain) here: https://github.com/koenbok/Cactus') else: return
def login_if_needed(vcloud): if vcloud.logged_in: log.info("Already logged in") return print("Please log into vCloud", file=sys.stderr) username = _raw_input("Username: "******"Password: ") vcloud.login(username, password)
def login_if_needed(gh, scopes, comment): if gh.logged_in: log.info("Already logged in") return print("Please log into GitHub ({0})".format(gh.nickname or "public"), file=sys.stderr) username = _raw_input("Username: "******"Password: ") gh.login(username, password, scopes=scopes, comment=comment)
def main(): global mounted_devices, disk_images if not detect_ethernet(): print """ ************************************************************ * Ethernet Interface is not detected. * * Before shipping, please make sure to add a network NIC. * ************************************************************ """ pass print "At any point, if you want to interrupt the installation, hit Control-C" disk_images = get_net_disk_images() + get_live_disk_images() if len(disk_images) <= 0: print "There is no disk image on this media or network." pass disks = get_disks(False) targets = [] index = 1 n_free_disk = 0 first_target = None print "Detected disks" for d in disks: if mounted_devices.has_key(d.device_name): print "%3d : %s - mounted %s" % (index, d.device_name, mounted_devices[d.device_name]) else: print "%3d : %s" % (index, d.device_name) n_free_disk = n_free_disk + 1 if n_free_disk == 1: first_target = index - 1 pass pass index += 1 pass if n_free_disk > 1: print " NOTE: Mounted disks cannot be the installation target." selection = getpass._raw_input(" space separated: ") for which in selection.split(" "): try: index = string.atoi(which) - 1 if not disks[index].mounted: targets.append(disks[index]) else: print "%s is mounted and cannot be the target." % disks[index].device_name pass except Exception, e: print "Bad input for picking disk" raise e pass pass pass
def do_add(self, line=None): """ Adds an entry to the vault. """ self.check_vault() entry = self.vault.Record.create() try: while True: entry.title = getpass._raw_input("Entry's title: ") if entry.title == "": accept_empty = getpass._raw_input("Entry is empty. Enter Y to accept ") if accept_empty.lower() == "y": break else: break entry.group = getpass._raw_input("Entry's group: ") entry.user = getpass._raw_input("Username: "******"Entry's notes: ") entry.url = getpass._raw_input("Entry's url: ") entry.passwd = self.prompt_password() except EOFError: print "" return self.vault.records.append(entry) self.vault_modified = True print "Entry Added, but vault not yet saved" self.set_prompt()
def main(): parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('-f','--filename', help='file generated with nmap -oX', required=True) parser.add_argument('-H','--hosturl', help='hosturl for logging in to nessus server', default="https://127.0.0.1:8834") parser.add_argument('-n','--scanname', help='name for the scan in nessus, default is nmap_xml_<date>', required=False) parser.add_argument('-P','--policy', help='Nessus policy that is prepared with script_id(33818) Nmap (XML file importer)', default="nmap_xml") parser.add_argument('-p','--password', help='password for logging in to nessus server', required=False) parser.add_argument('-u','--user', help='username for logging in to nessus server', required=False) args = vars(parser.parse_args()) print args if not args['hosturl']: args['hosturl'] = getpass._raw_input('Hosturl: ') if not args['user']: args['user'] = getpass._raw_input('User: '******'password']: args['password'] = getpass.getpass() if not args['scanname']: args['scanname'] = "nmap_xml_%s"%datetime.now().strftime("%Y%m%d-%H%M%S") print args startscan(args)
def ask_user_yesno(msg, default=True): """Ask user Y/N question :param str msg: question text :param bool default: default value :return bool: User choice """ while True: answer = getpass._raw_input('{} [{}]: '.format( msg, 'y/N' if not default else 'Y/n')) if answer in ('y', 'Y', 'yes'): return True elif answer in ('n', 'N', 'no'): return False
def main(): cont = 0 while cont != 3: print("Sistema de Inventario") print("Login!") user = input("Usuario: ") password = getpass._raw_input("Password: "******"Acceso autorizado!") while True: print("1.Mostrar Herramientas Disponibles") print("2.Ingresar nuevas Herramientas") print("3.Borrar Alguna Herramienta") print("4.Vender Herramientas") print("5.Salir del sistema: ") opc = int(input("Escoja una opcion: ")) if opc == 5: print("Adios...") tabla_tools.cerrar_tools() break elif opc == 1: tabla_tools.mostrar_tools() elif opc == 2: cod = input("Introduzca el codigo: ") name = input("Nombre: ") price = float(input("Precio: ")) cant= int(input("Cantidad: ")) brand = input("Marca: ") tabla_tools.ingresar_tools(cod,name,price,cant,brand) elif opc == 3: tabla_tools.borrar_tools() else: print("En contruccion...!") else: print("Usuario Incorrecto") cont = cont + 1 print("Tiene ",cont," intentos") if cont == 3: print("Tiene 3 intentos...Acceso Denegado!") print("Adios!") validar_userDB.cerrar_acceso() else: print("Adios....")
def prompt_password(self, old_password=None): created_random_password = False while True: message = "New password. [.] for none, [ENTER] for random.\n" if old_password is not None: message = "New password. [.] for none, [..] to keep the same. [ENTER] for random\n" passwd = getpass.getpass("%sPassword: "******"": from src.random_password import random_password #TODO(climent): move the options to the config file password_policy = {'L': True, 'R': True, 'U': True, 'l': True, '2': True, 's': True, 'S': True} while True: passwd = random_password().generate_password(password_policy) created_random_password = True print "Generated password: %s" % passwd while True: accept_password = getpass._raw_input('Enter [y] to accept, [ENTER] for random ') if accept_password in password_policy: if password_policy[accept_password] is True: password_policy[accept_password] = False else: password_policy[accept_password] = True print password_policy else: break if accept_password.lower() == "y": break break elif old_password is not None and passwd == "..": return old_password elif passwd == '.': passwd = '' if created_random_password is False: passwd2 = getpass.getpass("Re-Type Password: "******"Passwords don't match" elif passwd == "": empty_passwd = getpass.getpass("Password is empty. Enter Y to accept ") if empty_passwd.lower() == "y": break else: break return passwd
def do_del(self, line=None): """ Delete an entry from the vault. """ if not self.vault: raise RuntimeError("No vault opened") vault_records = None match_records = None nomatch_records = None uuid = None title = None user = None group = None uuid_regexp = '^[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}$' pattern = re.compile(uuid_regexp, re.IGNORECASE) if pattern.search(line) is not None: uuid = line match_records, nonmatch_records = self.mod_titles(title=title, uuid=uuid, user=user, group=group) if match_records is None: print "No matches found." return if len(match_records) > 1: print "Too many records matched your search criteria" for record in match_records: print "%s [%s] " % (record.title.encode('utf-8', 'replace'), record.user.encode('utf-8', 'replace')) return if len(match_records) == 1: print "Deleting the following record:" self.do_show(str(match_records[0].uuid)) confirm_delete = getpass._raw_input("Confirm you want to delete the record [YES]: ") if confirm_delete.lower() == 'yes': self.vault.records = nonmatch_records print "Entry Deleted, but vault not yet saved" self.vault_modified = True print ""
def deploy(self): self.build(clean=True) self.execHook('preDeploy') awsAccessKey = self.config.get('aws-access-key') or raw_input('Amazon access key (http://goo.gl/5OgV8): ').strip() awsSecretKey = getpassword('aws', awsAccessKey) or getpass._raw_input('Amazon secret access key: ').strip() connection = boto.connect_s3(awsAccessKey.strip(), awsSecretKey.strip()) try: buckets = connection.get_all_buckets() except: self.log('Invalid login credentials, please try again...') return self.config.set('aws-access-key', awsAccessKey) self.config.write() setpassword('aws', awsAccessKey, awsSecretKey) awsBucketName = self.config.get('aws-bucket-name') or raw_input('S3 bucket name: ').strip().lower() if awsBucketName not in [b.name for b in buckets]: if raw_input('Bucket does not exist, create it? (y/n): ') == 'y': try: awsBucket = connection.create_bucket(awsBucketName, policy='public-read') except boto.exception.S3CreateError, e: self.log('Bucket with name %s already is used by someone else, please try again with another name' % awsBucketName) return awsBucket.configure_website('index.html', 'error.html') self.config.set('aws-bucket-website', awsBucket.get_website_endpoint()) self.config.set('aws-bucket-name', awsBucketName) self.config.write() self.log('Bucket %s was created with website endpoint %s' % (self.config.get('aws-bucket-name'), self.config.get('aws-bucket-website'))) self.log('You can learn more about s3 (like pointing to your own domain) here: https://github.com/koenbok/Cactus') else: return
def do_del(self, line=None): """ Delete an entry from the vault. Entries can only be deleted using the UUID. """ self.check_vault() try: match_records, nonmatch_records = self.find_matches(line) except: return if not match_records: print("No matches found.") return if len(match_records) > 1: print("Too many records matched your search criteria") for record in match_records: print("[%s.%s] <%s>" % (record.group, record.title, record.user)) return if len(match_records) == 1: print("Deleting the following record:") self.do_show(str(match_records[0].uuid), hide_password=True) try: confirm_delete = getpass._raw_input( "Confirm you want to delete the record by writing \"yes\": " ) except (EOFError, KeyboardInterrupt): print("\nDelete cancelled...") return if confirm_delete.lower() == 'yes': self.vault.records = nonmatch_records print("Entry Deleted, but vault not yet saved") self.vault_modified = True print("")
def do_del(self, line=None): """ Delete an entry from the vault. Entries can only be deleted using the UUID. """ self.check_vault() try: match_records, nonmatch_records = self.find_matches(line) except: return if not match_records: print "No matches found." return if len(match_records) > 1: print "Too many records matched your search criteria" for record in match_records: print "[%s.%s] <%s>" % ( record.group.encode("utf-8", "replace"), record.title.encode("utf-8", "replace"), record.user.encode("utf-8", "replace"), ) return if len(match_records) == 1: print "Deleting the following record:" self.do_show(str(match_records[0].uuid), hide_password=True) try: confirm_delete = getpass._raw_input('Confirm you want to delete the record by writing "yes": ') except EOFError, KeyboardInterrupt: print "\nDelete cancelled..." return if confirm_delete.lower() == "yes": self.vault.records = nonmatch_records print "Entry Deleted, but vault not yet saved" self.vault_modified = True
def prompt_credentials(device, user=None): """ Prompt for username, password and return them as Credentials namedtuple. :param device: Device or realm name to store :param user: (Optional) If set, use as default username """ if not device: raise MissingRealmName('You must specify a device/realm name.') creds = () # Make sure we can even get tty i/o! if sys.stdin.isatty() and sys.stdout.isatty(): print '\nUpdating credentials for device/realm %r' % device user_default = '' if user: user_default = ' [%s]' % user username = getpass._raw_input('Username%s: ' % user_default) or user if username == '': print '\nYou must specify a username, try again!' return prompt_credentials(device, user=user) passwd = getpass.getpass('Password: '******'Password (again): ') if not passwd: print '\nPassword cannot be blank, try again!' return prompt_credentials(device, user=username) if passwd != passwd2: print '\nPasswords did not match, try again!' return prompt_credentials(device, user=username) creds = Credentials(username, passwd, device) return creds
def do_add(self, line=None): """ Adds an entry to the vault. """ line = self._encode_line(line) self.check_vault() entry = self.vault.Record.create() # if len(line) > 0: # entry.user = line[0] # if len(line) > 1: # entry.title = line[1] # if len(line) > 2: # entry.group = line[2] try: if not entry.title: while True: entry.title = getpass._raw_input('Entry\'s title: ') if entry.title == "": accept_empty = getpass._raw_input( "Entry is empty. Enter Y to accept ") if accept_empty.lower() == 'y': break else: break if not entry.group: entry.group = getpass._raw_input('Entry\'s group: ') if not entry.user: entry.user = getpass._raw_input('Username: '******'Entry\'s notes: ') entry.url = getpass._raw_input('Entry\'s url: ') entry.passwd = self.prompt_password() except EOFError: print("") return self.vault.records.append(entry) self.vault_modified = True print("Entry Added, but vault not yet saved") self.set_prompt()
def do_add(self, line=None): """ Adds an entry to the vault """ entry = self.vault.Record.create() while True: entry.title = getpass._raw_input('Entry\'s title: ') if entry.title == "": accept_empty = getpass._raw_input("Entry is empty. Enter Y to accept ") if accept_empty.lower() == 'y': break else: break entry.group = getpass._raw_input('Entry\'s group: ') entry.user = getpass._raw_input('Username: '******'Entry\'s notes: ') entry.url = getpass._raw_input('Entry\'s url: ') entry.passwd = self.prompt_password() self.vault.records.append(entry) self.vault_modified = True print "Entry Added, but vault not yet saved"
os.makedirs(name) except OSError as e: if e.errno != errno.EEXIST: raise src_dir = os.path.abspath(os.path.dirname(__file__)) frame_dir = os.path.join(src_dir, '..', 'temp', 'sampattavanich_2014', 'frames') HOST = 'lincs-omero.hms.harvard.edu' PORT = 4064 GROUP = 'Public' # Read username and password. print "Connecting to OMERO server: %s:%d" % (HOST, PORT) username = getpass._raw_input('Username: '******'s needed. # -JLM 2013/12/04)
def test_trims_trailing_newline(self): input = StringIO('test\n') self.assertEqual('test', getpass._raw_input(input=input))
def test_uses_stdin_as_different_locale(self, mock_input): stream = TextIOWrapper(BytesIO(), encoding="ascii") mock_input.readline.return_value = "Hasło: " getpass._raw_input(prompt="Hasło: ",stream=stream) mock_input.readline.assert_called_once_with()
def test_uses_stdin_as_default_input(self, mock_input): mock_input.readline.return_value = 'input_string' getpass._raw_input(stream=StringIO()) mock_input.readline.assert_called_once_with()
def test_uses_stderr_as_default(self): input = StringIO('input_string') prompt = 'some_prompt' with mock.patch('sys.stderr') as stderr: getpass._raw_input(prompt, input=input) stderr.write.assert_called_once_with(prompt)
if __name__ == "__main__": global mounted_devices, mounted_partitions, usb_disks, wce_disk_image_path wce_disk_image_path = ["/live/image/wce-disk-images"] print "Here we go" time.sleep(3) triage_result = True while True: triage_result = triage() # If there is no router to talk to, I don't have # network. So, just wait for the machine to reboot. if (not get_router_ip_address()) or (not triage_result): print "" yes_no = getpass._raw_input("Reboot (i=Install)? ([Y]/n/i) ") if ((len(yes_no) == 0) or (yes_no[0].lower() == 'y')): reboot() sys.exit(0) pass if (len(yes_no) > 0): what = yes_no[0].lower() if what == 'i': break pass pass else: break pass mount_usb_disks()
except OSError as e: if e.errno != errno.EEXIST: raise src_dir = os.path.abspath(os.path.dirname(__file__)) frame_dir = os.path.join(src_dir, '..', 'temp', 'sampattavanich_2014', 'frames') HOST = 'lincs-omero.hms.harvard.edu' PORT = 4064 GROUP = 'Public' # Read username and password. print "Connecting to OMERO server: %s:%d" % (HOST, PORT) username = getpass._raw_input('Username: '******'s needed. # -JLM 2013/12/04)
def update_event(self, inp=-1): self.set_output_val( 0, getpass._raw_input(self.input(0), self.input(1), self.input(2)))
from getpass import _raw_input def occurrences(string, sub): count = start = 0 while True: start = string.find(sub, start) + 1 if start > 0: count+=1 else: return count count = occurrences("azcbobobegghakl", "bob") print (count) s = _raw_input("Enter a string:") count = 0 start = 0 for letter in s: start = s.find("bob", start) + 1 if start > 0: count += 1 print ("Number of times bob occurs is:", count)
from getpass import _raw_input from builtins import print score = float(_raw_input("Enter a score:")) if score < 0.0 or score > 1.0: print("The entered value is out of range") print("Exiting of the program...") quit() elif score >= 0.9: print("A") elif score >= 0.8: print ("B") elif score >= 0.7: print ("C") elif score >= 0.6: print ("D") elif score < 0.6: print ("F")
from getpass import _raw_input from builtins import print fname = _raw_input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short.txt" fh = open(fname) count = 0 lst = list() for line in fh: line.rstrip() if line.startswith("From:"): lst = line.split() print (lst[1]) count += 1 print("There were", count, "lines in the file with From as the first word")
if i and i != 'IP': # iterate through all rows and add to a temp array temp_hosts.append(i) print(temp_hosts) # scan # Scan Settings # nessus_url = "https://nessus.example.com:8834" nessus_url = "https://192.168.111.10:8834" scan_policy = "Basic Network Scan" scan_name = "My Scan" # Scanner Credentials user = getpass._raw_input('User: '******','.join(temp_hosts) # Set target and scan name scan.scan_add(targets=hosts, name=scan_name) # scan.scan_exists(targets=hosts, name=scan_name)
pilih = input("\n\tsilakan pilih : ") if pilih == 1: print(nilai_mahasiswa()) elif pilih == 2: print(pembayaran()) elif pilih == 3: print(kalkulator()) else: exit tanya() def tanya(): tanya = raw_input("\nKembali ke menu (y/t)? ") if tanya == "y": menu() elif tanya == "t": exit else: print("\n\tSalah input...........!!!") user = raw_input("\nUsername : "******"\nPassword :"******"nurul" and password == "nurul171099": menu() else: print("maaf password dan username anda salah.....!!!")
def test_flushes_stream_after_prompt(self): stream = mock.Mock(spec=StringIO) input = StringIO('input_string') getpass._raw_input('some_prompt', stream, input=input) stream.flush.assert_called_once_with()
time.sleep(2) print("send ping to "+rem_adr) def postPing(): requests.post(url=rem_adr) t = Thread(target = postPing, args=()) t.start() return "SEND" @app.post('/service/sendPong') def receivePong(): print("RECEIVE PONG") # time.sleep(0.5) return sendPing() if(__name__ == "__main__"): host = _raw_input(">> Local Machine adress? ") port = _raw_input(">> Local Machine port? ") remHost = _raw_input(">> Remote Machine adress? ") remPort = _raw_input(">> Remote Machine port? ") rem_adr = "http://"+remHost+":"+remPort+"/service/sendPing" app.run(host=host,port=port)
def makedirs_exist_ok(name): try: os.makedirs(name) except OSError as e: if e.errno != errno.EEXIST: raise HOST = "lincs-omero.hms.harvard.edu" PORT = 4064 GROUP = "Public" # Read username and password. print "Connecting to OMERO server: %s:%d" % (HOST, PORT) username = getpass._raw_input("Username: "******"Error: Connection not available, please check your " "username and password.") sys.exit(1) else: print "Login successful.\n" # Set our default group so we can see the data. # (I thought I had to do this, but now I am not sure it's needed. # -JLM 2013/12/04) try:
import getpass import csv from argparse import ArgumentParser from netmiko import ConnectHandler if __name__ == "__main__": parser = ArgumentParser(description='Arguments') parser.add_argument('-c', '--csv', required=True, action='store', help='Location of CSV file') args = parser.parse_args() device_type = getpass._raw_input('Device Type: ') ssh_username = getpass.getpass(prompt='Username: '******'Command:# ') with open(args.csv, "r") as file: reader = csv.DictReader(file) for device_row in reader: ssh_session = ConnectHandler(device_type=device_type, ip=device_row['device_ip'], username=ssh_username, password=ssh_password) print("-------- {0} ---------".format(device_row['device_ip'])) print(ssh_session.send_command(ssh_command))
def get_destination(self): IP_dest = getpass._raw_input("Server: ").encode('utf-8') user_dest = getpass.getpass("Username: "******"Password: ").encode('utf-8')
def test_uses_stdin_as_different_locale(self, mock_input): stream = TextIOWrapper(BytesIO(), encoding='ascii') mock_input.readline.return_value = 'Hasło: ' getpass._raw_input(prompt='Hasło: ', stream=stream) mock_input.readline.assert_called_once_with()
def custom_fallback(prompt="Password: "******"Unable to hide password. Make sure no-one else can see your screen!",1,False) return getpass._raw_input(prompt)
def upload(self): """ Upload the site to the server. """ # Make sure we have internet if not internetWorking(): logging.info( 'There does not seem to be internet here, check your connection' ) return logging.debug('Start upload') self.clean() self.build() logging.debug('Start preDeploy') self.pluginMethod('preDeploy', self) logging.debug('End preDeploy') # Get access information from the config or the user awsAccessKey = self.config.get('aws-access-key') or \ raw_input('Amazon access key (http://bit.ly/Agl7A9): ').strip() awsSecretKey = getpassword('aws', awsAccessKey) or \ self.config.get('aws-secret-key') or \ getpass._raw_input('Amazon secret access key (will be saved in keychain): ').strip() # Try to fetch the buckets with the given credentials connection = boto.connect_s3(awsAccessKey.strip(), awsSecretKey.strip()) logging.debug('Start get_all_buckets') # Exit if the information was not correct try: buckets = connection.get_all_buckets() except: logging.info('Invalid login credentials, please try again...') return logging.debug('end get_all_buckets') # If it was correct, save it for the future self.config.set('aws-access-key', awsAccessKey) self.config.write() setpassword('aws', awsAccessKey, awsSecretKey) awsBucketName = self.config.get('aws-bucket-name') or \ raw_input('S3 bucket name (www.yoursite.com): ').strip().lower() if awsBucketName not in [b.name for b in buckets]: if raw_input('Bucket does not exist, create it? (y/n): ') == 'y': logging.debug('Start create_bucket') try: awsBucket = connection.create_bucket(awsBucketName, policy='public-read') except boto.exception.S3CreateError, e: logging.info( 'Bucket with name %s already is used by someone else, please try again with another name' % awsBucketName) return logging.debug('end create_bucket') # Configure S3 to use the index.html and error.html files for indexes and 404/500s. awsBucket.configure_website('index.html', 'error.html') self.config.set('aws-bucket-website', awsBucket.get_website_endpoint()) self.config.set('aws-bucket-name', awsBucketName) self.config.write() logging.info( 'Bucket %s was selected with website endpoint %s' % (self.config.get('aws-bucket-name'), self.config.get('aws-bucket-website'))) logging.info( 'You can learn more about s3 (like pointing to your own domain) here: https://github.com/koenbok/Cactus' ) else: return
def test_flushes_stream_after_prompt(self): # see issue 1703 stream = mock.Mock(spec=StringIO) input = StringIO('input_string') getpass._raw_input('some_prompt', stream, input=input) stream.flush.assert_called_once_with()
import getpass from config.Master import Master from model.BaseDevice import BaseDevice master = Master() ip = getpass._raw_input("ip del cisco") EquipoPrueba = BaseDevice(ip, "pba", master) device = EquipoPrueba.connect() # print(EquipoPrueba.sendCommand(device,"show conf")) print(EquipoPrueba.get_recursive_routes())
def do_mod(self, line=None): """ Modify an entry from the vault. """ self.check_vault() try: match_records, nonmatch_records = self.find_matches(line) except: return if not match_records: print "No matches found." return if len(match_records) > 1: print "Too many records matched your search criteria." if line: for record in match_records: print "[%s.%s] [%s]" % ( record.group.encode("utf-8", "replace"), record.title.encode("utf-8", "replace"), record.user.encode("utf-8", "replace"), ) return vault_modified = False record = match_records[0] new_record = {} print "" if self.uuid is True: print "Uuid: [%s]" % str(record.uuid) print "Modifying: [%s.%s]" % (record.group.encode("utf-8", "replace"), record.title.encode("utf-8", "replace")) print "Enter a single dot (.) to clear the field, ^D to maintain the current entry." print "" try: new_record["group"] = getpass._raw_input("Group [%s]: " % record.group) except EOFError: new_record["group"] = "" print "" except KeyboardInterrupt: print " pressed. Aborting modifications." return if new_record["group"] == ".": new_record["group"] = "" elif new_record["group"] == "": new_record["group"] = record.group if new_record["group"] != record.group: vault_modified = True try: new_record["title"] = getpass._raw_input("Title [%s]: " % record.title) except EOFError: new_record["title"] = "" print "" except KeyboardInterrupt: print " pressed. Aborting modifications." return if new_record["title"] == ".": new_record["title"] = "" elif new_record["title"] == "": new_record["title"] = record.title if new_record["title"] != record.title: vault_modified = True try: new_record["user"] = getpass._raw_input("User [%s]: " % record.user) except EOFError: new_record["user"] = "" print "" except KeyboardInterrupt: print " pressed. Aborting modifications." return if new_record["user"] == ".": new_record["user"] = "" elif new_record["user"] == "": new_record["user"] = record.user if new_record["user"] != record.user: vault_modified = True try: new_record["password"] = self.prompt_password(old_password=record.passwd) except EOFError: new_record["password"] = record.passwd print "" except KeyboardInterrupt: print " pressed. Aborting modifications." return if new_record["password"] != record.passwd: vault_modified = True if record.notes.encode("utf-8", "replace") != "": print "[NOTES]" print "%s" % record.notes try: new_record["notes"] = getpass._raw_input("Entry's notes: ") except EOFError: new_record["notes"] = "" print "" except KeyboardInterrupt: print " pressed. Aborting modifications." return if new_record["notes"] == ".": new_record["notes"] = "" elif new_record["notes"] == "": new_record["notes"] = record.notes if new_record["notes"] != record.notes: vault_modified = True try: new_record["url"] = getpass._raw_input("Entry's url [%s]: " % record.url) except EOFError: new_record["url"] = "" print "" except KeyboardInterrupt: print " pressed. Aborting modifications." return if new_record["url"] == ".": new_record["url"] = "" elif new_record["url"] == "": new_record["url"] = record.url if new_record["url"] != record.url: vault_modified = True if vault_modified == True: record.title = new_record["title"] record.user = new_record["user"] record.group = new_record["group"] record.notes = new_record["notes"] record.url = new_record["url"] record.passwd = new_record["password"] self.vault.records = nonmatch_records self.vault.records.append(record) print "Entry Modified, but vault not yet saved" self.vault_modified = True print ""