def ask_admin_password(): admin_password = getpass.getpass("Set Administrator password: "******"Re-enter Administrator password: "******"\nPasswords do not match" return ask_admin_password() return admin_password
def create_account_commandline(db, verbose=False): account = entity.Account() account.username = input('username (lower case only) > ') if not account.username: raise ValueError('no username given') if not constants.NAME_RX.match(account.username): raise ValueError('invalid username given') if db.get_account(username=account.username): raise ValueError("username %s already in use" % account.username) account.email = input('email > ') if not account.email: raise ValueError('no email given') if not constants.EMAIL_RX.match(account.email): raise ValueError('invalid email given') if db.get_account(email=account.email): raise ValueError("email %s already in use" % account.email) account.role = input('role > ') if not account.role: raise ValueError('no role given') if not account.role in constants.ACCOUNT_ROLES: raise ValueError('invalid role given') account.state = constants.ENABLED password = getpass.getpass('password > ') if password: confirm = getpass.getpass('confirm password > ') if password != confirm: raise ValueError('passwords did not match') else: password = '' account.password = password db.create_account(account, dict(user_agent='commandline')) if verbose: print('created account', username)
def getkey(l, pwd='', empty=False, text=''): # queries the user twice for a passphrase if neccessary, and # returns a scrypted key of length l # allows empty passphrases if empty == True # 'text' will be prepended to the password query # will not query for a password if pwd != '' global _prev_passphrase #clearpwd = (pwd.strip()=='') pwd2 = not pwd if not pwd: if _prev_passphrase: print >>sys.stderr, "press enter to reuse the previous passphrase" while pwd != pwd2 or (not empty and not pwd.strip()): pwd = getpass.getpass('1/2 %s Passphrase: ' % text) if pwd.strip(): pwd2 = getpass.getpass('2/2 %s Repeat passphrase: ' % text) elif _prev_passphrase is not None: pwd = _prev_passphrase break #if isinstance(pwd2, str): # clearmem(pwd2) if pwd.strip(): _prev_passphrase = pwd key = scrypt.hash(pwd, scrypt_salt)[:l] #if clearpwd: clearmem(pwd) return key
def login(args): args = parse_login_command_line(args, help=lixian_help.login) if args.cookies == '-': args._args['cookies'] = None if len(args) < 1: args.username = args.username or XunleiClient(cookie_path=args.cookies, login=False).get_username() or get_config('username') or raw_input('ID: ') args.password = args.password or get_config('password') or getpass('Password: '******'username') args.password = args[0] if args.password == '-': args.password = getpass('Password: '******'-': args.password = getpass('Password: '******'-': args.password = getpass('Password: '******'Too many arguments') if not args.username: raise RuntimeError("What's your name?") if args.cookies: print 'Saving login session to', args.cookies else: print 'Testing login without saving session' client = XunleiClient(args.username, args.password, args.cookies)
def main(): prog = os.path.basename(sys.argv[0]) or "gktool.py" # glib.set_application_name(prog) (GET, SET) = (0, 1) # defaults: verbose = False attrs = {} cmd = GET mngr = SecretManager() loglevel = logging.WARN parser = option_parser() (options, args) = parser.parse_args() if options.verbose: loglevel = logging.INFO logging.basicConfig(level=loglevel) if not args or args[0] not in ("get", "set"): parser.print_usage() sys.exit(-1) else: if args[0] == "set": cmd = SET if options.attrs: attrs = parse_kvpairs(options.attrs) logging.info(" attrs = %s" % attrs) else: logging.error(" Attributes must be specified with --attrs option.") sys.exit(-1) if options.type and options.type == "network": mngr = NetworkSecretManager() if cmd == GET: results = mngr.find(attrs, options.single) for res in results: print >>sys.stdout, options.format % res else: if not options.name: print >>sys.stderr, " You must specify the display name for this secret!" sys.exit(-1) secret = options.secret if not secret: secret = getpass.getpass("Enter password > ") secret2 = getpass.getpass("Re-enter password to confirm > ") if secret != secret2: print >>sys.stderr, "The passwords' pair does not match!" sys.exit(-1) mngr.create(options.name, attrs, secret, options.keyring, force=False) exit(0)
def getAPISecret(args): log.info('Function Enter: getAPISecret') if args.verbose: args.key_secret = getpass.getpass("%-6s: %s" % ('INFO','Passwd: ')) else: args.key_secret = getpass.getpass("%-6s:" % 'Passwd') log.info('Function Exit : getAPISecret')
def prompt_for_password(prompt=None, no_colon=False, stream=None): """ Prompts for and returns a new password if required; otherwise, returns None. A trailing colon is appended unless ``no_colon`` is True. If the user supplies an empty password, the user will be re-prompted until they enter a non-empty password. ``prompt_for_password`` autogenerates the user prompt based on the current host being connected to. To override this, specify a string value for ``prompt``. ``stream`` is the stream the prompt will be printed to; if not given, defaults to ``sys.stderr``. """ from fabric.state import env handle_prompt_abort("a connection or sudo password") stream = stream or sys.stderr # Construct prompt default = "[%s] Login password for '%s'" % (env.host_string, env.user) password_prompt = prompt if (prompt is not None) else default if not no_colon: password_prompt += ": " # Get new password value new_password = getpass.getpass(password_prompt, stream) # Otherwise, loop until user gives us a non-empty password (to prevent # returning the empty string, and to avoid unnecessary network overhead.) while not new_password: print("Sorry, you can't enter an empty password. Please try again.") new_password = getpass.getpass(password_prompt, stream) return new_password
def ask_passwords(self): ''' prompt for connection and become passwords if needed ''' op = self.options sshpass = None becomepass = None become_prompt = '' become_prompt_method = "BECOME" if C.AGNOSTIC_BECOME_PROMPT else op.become_method.upper() try: if op.ask_pass: sshpass = getpass.getpass(prompt="SSH password: "******"%s password[defaults to SSH password]: " % become_prompt_method if sshpass: sshpass = to_bytes(sshpass, errors='strict', nonstring='simplerepr') else: become_prompt = "%s password: " % become_prompt_method if op.become_ask_pass: becomepass = getpass.getpass(prompt=become_prompt) if op.ask_pass and becomepass == '': becomepass = sshpass if becomepass: becomepass = to_bytes(becomepass) except EOFError: pass return (sshpass, becomepass)
def manual_auth(username, hostname): default_auth = 'p' auth = raw_input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth) if len(auth) == 0: auth = default_auth if auth == 'r': default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa') path = raw_input('RSA key [%s]: ' % default_path) if len(path) == 0: path = default_path try: key = ssh.RSAKey.from_private_key_file(path) except ssh.PasswordRequiredException: password = getpass.getpass('RSA key password: '******'d': default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa') path = raw_input('DSS key [%s]: ' % default_path) if len(path) == 0: path = default_path try: key = ssh.DSSKey.from_private_key_file(path) except ssh.PasswordRequiredException: password = getpass.getpass('DSS key password: '******'Password for %s@%s: ' % (username, hostname)) t.auth_password(username, pw)
def _auth_func(): if debug == False: if email != None: return email,getpass.getpass('Password for %s:' % email) else: return raw_input('Username:'******'Password:') return "*****@*****.**",""
def initialize_database(): sys.stderr.write("Initializing the first user\n\n") field_names = { 'email' : 'Email address', 'first_name' : 'First name', 'last_name' : 'Last name', 'cb_username' : 'Mapped Carbon Black username' } field_order = ('email', 'first_name', 'last_name', 'cb_username') u = User() for field in field_order: sys.stderr.write(field_names[field] + ': ') sys.stderr.flush() response = sys.stdin.readline().strip() setattr(u, field, response) # capture password password_mismatch = True while password_mismatch: try: pass1 = getpass.getpass("Password: "******"Confirm : ") if pass1 == pass2: password_mismatch = False else: sys.stderr.write("Passwords don't match\n") except getpass.GetPassWarning: sys.exit(1) u.password = pass1 app.create_base_data(u)
def do_passwd(self, arg): """Change master password for opened database Syntax: password [new password] If new password is not provided with command, you will be promted to enter new one. """ if not arg: # Password is not provided with command. Ask user for it pass1 = getpass(_("New password: "******"Repeat password: "******"Empty passwords are really insecure. You should " \ "create one.") return if pass1!=pass2: print _("Passwords don't match! Please repeat.") return new_pass = pass1 else: new_pass = arg self.pdb.changePassword(new_pass) self.printMessage(_("Password changed."))
def main(): welcome_banner() try: while True: print("Enter the following: \n") seed = getpass.getpass('password: '******'Re-enter password: '******'t match, please try again" while True: print("\nMain Menu: ") mode = raw_input('\n1. Input host and usernames by hand.\n2. Use accounts.json\nMake a selection: ') if mode == "1": use_user_input(seed) break elif mode == "2": use_json_file(seed) use_user_input(seed) break else: print "unknown mode, please try again" except KeyboardInterrupt: print "program exiting"
def __init__(self, manual=True): # self.logOnDetails = { # 'username': input("Steam user: "******"Password: "******"Password: "******"Email Adress: ") self.emailer = EmailConnector(mail, getpass("Password: "******"Created Client") self.client.on('error', self._handle_client_error) self.client.on('auth_code_required', self._handle_auth_req) self.client.on('logged_on', self._client_handle_logon) self.client.on('connected', self._handle_client_connected) self.client.on('disconnected', self._handle_client_disconnected) self.client.on('reconnected', self._handle_client_reconnected) print("Doing login") self.client.login(**self.logOnDetails) print("Login was sent.") msg, = self.client.wait_event(EMsg.ClientAccountInfo, 20) # print "Logged on as: %s" % msg.body.persona_name self.client.run_forever()
def createUser(self, args): self._start(args) while True: username = raw_input('Enter email address: ') if User.users().get(username=username): print('Username already exists. Please pick another username.') else: break print('username: %s' % username) while True: is_admin = raw_input('Admininstrative user? (y/N): ') if (len(is_admin) == 0) or (is_admin.upper() == 'N'): admin = False break elif is_admin.upper() == 'Y': admin = True break while True: password_1 = getpass.getpass('Enter password: '******'Re-enter password: '******'Passwords do not match.') else: break user = User(username, password_1, admin) user.save() # Db.instance().insert_user(username, password_1, admin) print('Successfully created user %s' % username)
def all_syllabus(): print("Starting Crawling https://zkyomu.c.u-tokyo.ac.jp...") username = input("ID:") password = getpass.getpass("パスワード:") code_number = getpass.getpass("暗証番号:") utask = utaskweb() res = utask.login_utaskweb(username=username, password=password, code_number=code_number) utask.syllabus_link() utask.search_syllabus(nendo=2013, semester="winter") results = utask.search_results() data = [] print("Scraping the syllabus...") for result in results: data.append(utask.scrape_syllabus(url=result)) filename = "out.csv" with open(filename, 'w', encoding="utf-16") as f: for d in data: w = csv.DictWriter(f, d.keys()) if data.index(d) == 0: w.writeheader() w.writerow(d) f.close()
def main(): rtr1_pass = getpass("Enter router password: "******"Enter switch password: "******"show version") show_run = sw_con.send_command("show run") save_file(sw_con.base_prompt + '-ver', show_ver) save_file(sw_con.base_prompt + '-run', show_run)
def do_register(self, line): """Registers for a new account: "register <userid> <noupdate>" <userid> : The desired user ID <noupdate> : Do not automatically clobber config values. """ args = self._parse(line, ["userid", "noupdate"]) password = None pwd = None pwd2 = "_" while pwd != pwd2: pwd = getpass.getpass("Type a password for this user: "******"Retype the password: "******"Password mismatch." pwd = None else: password = pwd body = { "type": "m.login.password" } if "userid" in args: body["user"] = args["userid"] if password: body["password"] = password reactor.callFromThread(self._do_register, body, "noupdate" not in args)
def clin_register(args): clin_default_dir = get_default_dir(args) conf_path = u'%s/conf.yml' % clin_default_dir apiserver = None if os.path.exists(conf_path): with open(conf_path, u'r') as f: t = yaml.safe_load(f) if u'apiserver' in t: apiserver = t[u'apiserver'] if not apiserver: apiserver = default_api_server username = args.username password = args.password if not password: while True: pw1 = getpass.getpass(u'Enter password:'******'passworld should more than 3 characters') continue pw2 = getpass.getpass(u'Confirm password:'******'confirm incorrect') continue password = pw1 break client = ApiV1Client(apiserver) ret = client.create_user(username, password) print(ret) print(base64.encodestring(password))
def get_credentials(username=None, password=None): try: my_netrc = netrc.netrc() except: pass else: auth = my_netrc.authenticators(GITHUB_API_HOST) if auth: response = '' while response.lower() not in ('y', 'n'): print('Using the following GitHub credentials from ' '~/.netrc: {0}/{1}'.format(auth[0], '*' * 8)) response = input( 'Use these credentials (if not you will be prompted ' 'for new credentials)? [Y/n] ') if response.lower() == 'y': username = auth[0] password = auth[2] if not (username or password): print("Enter your GitHub username and password so that API " "requests aren't as severely rate-limited...") username = raw_input('Username: '******'Password: '******'t as severely rate-limited...") password = getpass.getpass('Password: ') return username, password
def init_db(): engine = g.db_session.get_bind() from orvsd_central import models Model.metadata.create_all(bind=engine) # Create an admin account. ans = raw_input("There are currently no admin accounts, would you like to " "create one? (Y/N) ") if not ans.lower().startswith("y"): return username = raw_input("Username: "******"Email: ") matching = False while not matching: password = getpass.getpass("Password: "******"Confirm Password: "******"Passwords do not match. Please try again." # Get admin role. admin_role = USER_PERMS.get('admin') admin = models.User(name=username, email=email, password=password, role=admin_role) g.db_session.add(admin) g.db_session.commit() print "Administrator account created!"
def crab_get_and_save_grid_passphrase(path=None): if not crab_global_options.allow_insecure_stupidity: raise ValueError('allow_insecure_stupidity is not set') if path is None: path = os.path.expanduser('~/.jmtctgpp') print ''' ******************************************************************************* WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING DO NOT, under any circumstances, enter your GRID passphrase at the prompts. It will not be treated securely, and may end up in the hands of anyone. WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ******************************************************************************* ''' while 1: pp = getpass.getpass('GRID passphrase:') pp2 = getpass.getpass('again:') if pp != pp2 or len(pp) < 4: print 'did not match' else: break open(path, 'wt').write(zlib.compress(pp)) os.chmod(path, 0400) return pp
def run(self, credopts=None, sambaopts=None, versionopts=None, newpassword=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) # get old password now, to get the password prompts in the right order old_password = creds.get_password() net = Net(creds, lp, server=credopts.ipaddress) password = newpassword while True: if password is not None and password is not '': break password = getpass("New Password: "******"Retype Password: "******"Sorry, passwords do not match.\n") try: net.change_password(password) except Exception, msg: # FIXME: catch more specific exception raise CommandError("Failed to change password : {0!s}".format(msg))
def login(): print("\n##############################################################") print("# Login #") print("##############################################################\n") global AccountDetails UserName=input("Enter Your Name : ") UserName=validationAccount(AccountDetails,UserName,'') #Getting the Key and Password Values Accounts=READ_CSV(AccountDetails) CurrentUser=Accounts[(Accounts['AccountName'] == UserName)] CurrentPassword=CurrentUser[['Password']].to_string(header=False,index=False).lstrip() PassWord=getpass.getpass("Enter Your Password : "******"Error: Incorrect Password , Attempt:",(MinAttempt)," Attempt Left :",(MaxAttempt-MinAttempt)) PassWord=getpass.getpass("Enter Your Correct Password : "******"cls") print("Too Many Unsucessfull Attempts") print("Terminate Program.") print("##############################################################\n") exit() print("Login Sucessfully") print("##############################################################\n") os.system("cls") ViewAccounts(UserName,'')
def _saveKey(key, options): if not options['filename']: kind = keys.objectType(key) kind = {'ssh-rsa':'rsa','ssh-dss':'dsa'}[kind] filename = os.path.expanduser('~/.ssh/id_%s'%kind) options['filename'] = raw_input('Enter file in which to save the key (%s): '%filename).strip() or filename if os.path.exists(options['filename']): print '%s already exists.' % options['filename'] yn = raw_input('Overwrite (y/n)? ') if yn[0].lower() != 'y': sys.exit() if not options['pass']: while 1: p1 = getpass.getpass('Enter passphrase (empty for no passphrase): ') p2 = getpass.getpass('Enter same passphrase again: ') if p1 == p2: break print 'Passphrases do not match. Try again.' options['pass'] = p1 keyObj = keys.Key(key) comment = '%s@%s' % (getpass.getuser(), socket.gethostname()) filepath.FilePath(options['filename']).setContent( keyObj.toString('openssh', options['pass'])) os.chmod(options['filename'], 33152) filepath.FilePath(options['filename'] + '.pub').setContent( keyObj.public().toString('openssh', comment)) print 'Your identification has been saved in %s' % options['filename'] print 'Your public key has been saved in %s.pub' % options['filename'] print 'The key fingerprint is:' print keyObj.fingerprint()
def __init__(self, **keys): bot.Bot.__init__(self, **keys) if self.xmpp_src_password is None: self.xmpp_src_password = getpass.getpass("XMPP src password: "******"XMPP dst password: ")
def prompt_user_info(): username = input('Input username: '******'Input password: '******'Input again: ') if password == password_again: break else: print('Password do not match!') dev = input('Decice(eth0 by default): ') if not dev: dev = 'eth0' choice = input('Forked to background after authentication(Yes by default)\n<Y/N>: ') if choice == 'n' or choice == 'N': daemon = "False" else: daemon = "True" dhcp_cmd = input('Dhcp command(Press Enter to pass): ') if not dhcp_cmd: dhcp_cmd = '' return { 'username': username, 'password': password, 'ethernet_interface': dev, 'daemon': daemon, 'dhcp_command': dhcp_cmd }
def _request_password(self): password = getpass.getpass() confirm = getpass.getpass("Confirm Password:"******"passwords do not match - try again!" return None return password
def main(): ''' Comprueba si el usuario ha introducido como opcion el leer los hosts de un fichero. Si no lo ha hecho, solicita la informacion del host remoto por linea de comandos. Una vez se tiene la informacion para establecer una conexion SSH con el host, se solicita al usuario que introduzca las pruebas que quiere realizar. ''' hosts, doc_name = parse_program_options() doc = doc_func.create(doc_name) if hosts: for host in hosts: ip, user, pwd = host ssh_conn = sshConnection(ip, user, pwd) code = ssh_conn.connect() if code == 1: i = 1 while code == 1 and i<=2: pwd = getpass.getpass("Introduzca password para %s@%s\n" % (user,ip)) code = ssh_conn.connect() i+=1 if code == 0: doc.add_heading('Pruebas sobre %s' % ip, level=1) try: while(1): select_test(ssh_conn, doc) except KeyboardInterrupt: ssh_conn.disconnect() ssh_conn.disconnect() else: while(1): print 'Press CTRL+C to stop.' ip = raw_input("Introduzca IP remota \n") user = raw_input("Introduzca el usuario \n") pwd = getpass.getpass("Introduzca password \n") ssh_conn = sshConnection(ip, user, pwd) code = ssh_conn.connect() if code == 1: i = 1 while code == 1 and i<=2: pwd = getpass.getpass("Introduzca password para %s@%s\n" % (user,ip)) code = ssh_conn.connect() i+=1 if code == 0: doc.add_heading('Pruebas sobre %s' % ip, level=1) try: while(1): select_test(ssh_conn, doc) except KeyboardInterrupt: ssh_conn.disconnect() ssh_conn.disconnect() doc_func.end_doc(doc)
def make_wallet_password( password=None ): """ Make a wallet password: prompt for a wallet, and ensure it's the right length. If @password is not None, verify that it's the right length. Return {'status': True, 'password': ...} on success Return {'error': ...} on error """ if password is not None and len(password) > 0: if len(password) < WALLET_PASSWORD_LENGTH: return {'error': 'Password not long enough (%s-character minimum)' % WALLET_PASSWORD_LENGTH} return {'status': True, 'password': password} else: p1 = getpass("Enter new password: "******"Confirm new password: ") if p1 != p2: return {'error': 'Passwords do not match'} if len(p1) < WALLET_PASSWORD_LENGTH: return {'error': 'Password not long enough (%s-character minimum)' % WALLET_PASSWORD_LENGTH} else: return {'status': True, 'password': p1}
def __call__(self, parser, args, values, option_string=None): password = getpass.getpass() setattr(args, self.dest, password)
validate_code = ''.join(e for e in raw_code if e.isalnum()) if(len(validate_code) != 4): print("[X] 验证码识别出错:" + validate_code + ",请查看当前目录下_tmp.png,手动打码") validate_code_img.save('_tmp.png') validate_code = raw_input('---> 验证码:') validate_code_img.save('_tmp_'+validate_code+'.png') else: print("[-] 验证码识别完成,结果:"+raw_code+' -> '+validate_code) validate_code_img.save(validate_code+'.png') validate_code_img.close() #构造Post数据,2019.03上线含验证码版本 login_data = {'model' : 'uplogin.jsp', 'service': 'http://yqzx.ustc.edu.cn/login_cas', 'username' : raw_input('UserID : '), 'password' : getpass.getpass('Passwd : '), 'LT': validate_code, 'button' : '' } #通过urllib2提供的request方法来向指定Url发送我们构造的数据,并完成登录过程 response = urllib2.urlopen( urllib2.Request(login_url, urllib.urlencode(login_data), post_header)) CheckUrl(response) print('[-] 登录成功,当前用户'+login_data['username']) # 载入测试表单 file = open('yqzx.json') data = json.load(file) file.close()
def get_pass(): password = getpass.getpass('Set password: ') hash_pass = hashlib.sha3_256() hash_pass.update(password.encode()) return hash_pass
def start_loop(): global _loc global tasks global t_time global node_id global stop print( '\n============* WELCOME TO THE DEADLOCK EMULATION PROGRAM *=============\n' ) node_id = mec_id(ip_address()) # print('node id: ', node_id) _threads_ = [ receive_offloaded_task_mec, call_execute_re_offload, connect_to_broker ] for i in _threads_: Thread(target=i).daemon = True Thread(target=i).start() x = gp.getpass('Press any key to Start...').lower() if x != 'exit': print('========= Waiting for tasks ==========') _time_ = dt.datetime.now() while True: try: if len(received_task_queue) > 0: info = received_task_queue.pop(0) tasks, t_time = info print('EDF List of Processes: ', tasks, '\n') print('\n========= Running Deadlock Algorithm ===========') a = load_tasks() list_seq = get_exec_seq(scheduler(a)) if len( list_seq ) > 0: # do only when there is a task in safe sequence wait_list = calc_wait_time(list_seq) print('\nWaiting Time List: ', wait_list) compare_result = compare_local_mec(wait_list) print('\nExecute Locally: ', compare_result[1]) _loc += len( compare_result[1] ) # total number of tasks to be executed locally print('\nExecute in MEC: ', compare_result[0]) print('\nSending to cooperative platform') if len(compare_result[0]) > 0: cooperative_mec(compare_result[0]) execute(compare_result[1]) generate_results() _time_ = dt.datetime.now() else: send_message(str('wt {} 0.0'.format(ip_address()))) time.sleep(1) now = dt.datetime.now() delta = now - _time_ if delta > dt.timedelta(minutes=3): print('terminating programme 5 mins elapsed') _id_ = get_hostname()[-1] result = f"wt{_id_}_2_{mec_no} = {mec_waiting_time} " \ f"\nrtt{_id_}_2_{mec_no} = {mec_rtt} \ncpu{_id_}_2_{mec_no} = {_cpu} " \ f"\noff_mec{_id_}_2_{mec_no} = {_off_mec} " \ f"\noff_cloud{_id_}_2_{mec_no} = {_off_cloud} " \ f"\ninward_mec{_id_}_2_{mec_no} = {_inward_mec}" \ f"\nloc{_id_}_2_{mec_no} = {_loc} " \ f"\ndeadlock{_id_}_2_{mec_no} = {deadlock} \nmemory{_id_}_2_{mec_no} = {memory}" list_result = [ f"wt{_id_}_2_{mec_no} = {mec_waiting_time} ", f"\nrtt{_id_}_2_{mec_no} = {mec_rtt} \ncpu{_id_}_2_{mec_no} = {_cpu} ", f"\noff_mec{_id_}_2_{mec_no} = {_off_mec} \noff_cloud{_id_}_2_{mec_no} = {_off_cloud} ", f"\ninward_mec{_id_}_2_{mec_no} = {_inward_mec}", f"\nloc{_id_}_2_{mec_no} = {_loc} ", f"\ndeadlock{_id_}_2_{mec_no} = {deadlock} \nmemory{_id_}_2_{mec_no} = {memory}" ] for i in list_result: cmd = 'echo "{}" >> data.py'.format(i) os.system(cmd) send_result(hosts['osboxes-0'], list_result) send_email(result) stop += 1 ''' for i in thread_record: i.join() ''' _client.loop_stop() time.sleep(1) print('done') os.system('kill -9 {}'.format(os.getpid())) break except KeyboardInterrupt: print('\nProgramme Terminated') _id_ = get_hostname()[-1] result = f"wt{_id_}_2_{mec_no} = {mec_waiting_time} " \ f"\nrtt{_id_}_2_{mec_no} = {mec_rtt} \ncpu{_id_}_2_{mec_no} = {_cpu} " \ f"\noff_mec{_id_}_2_{mec_no} = {_off_mec} \noff_cloud{_id_}_2_{mec_no} = {_off_cloud} " \ f"\ninward_mec{_id_}_2_{mec_no} = {_inward_mec}" \ f"\nloc{_id_}_2_{mec_no} = {_loc} " \ f"\ndeadlock{_id_}_2_{mec_no} = {deadlock} \nmemory{_id_}_2_{mec_no} = {memory}" list_result = [ f"wt{_id_}_2_{mec_no} = {mec_waiting_time} ", f"\nrtt{_id_}_2_{mec_no} = {mec_rtt} \ncpu{_id_}_2_{mec_no} = {_cpu} ", f"\noff_mec{_id_}_2_{mec_no} = {_off_mec} \noff_cloud{_id_}_2_{mec_no} = {_off_cloud} ", f"\ninward_mec{_id_}_2_{mec_no} = {_inward_mec}", f"\nloc{_id_}_2_{mec_no} = {_loc} ", f"\ndeadlock{_id_}_2_{mec_no} = {deadlock} \nmemory{_id_}_2_{mec_no} = {memory}" ] for i in list_result: cmd = 'echo "{}" >> data.py'.format(i) os.system(cmd) send_result(hosts['osboxes-0'], list_result) send_email(result) stop += 1 ''' for i in thread_record: i.join() ''' _client.loop_stop() time.sleep(1) print('done') os.system('kill -9 {}'.format(os.getpid())) break
from netmiko import ConnectHandler from getpass import getpass device1 = { "host": 'cisco3.lasthop.io', "username": "******", "password": getpass(), "device_type": "cisco_ios", #"global_delay_factor": 2 } net_connect = ConnectHandler(**device1) print(net_connect.find_prompt()) output = net_connect.send_command("show ip interface brief", delay_factor=5) print(output) net_connect.disconnect()
def get_connect_kwargs(options): ops = ('host', 'port', 'user', 'schema') kwargs = dict((o, getattr(options, o)) for o in ops if getattr(options, o)) if options.password: kwargs['password'] = getpass() return kwargs
def prompt(prompt, private): if private: return getpass.getpass(prompt) return raw_input(prompt)
while not icmp: print( "[\033[91mBantus\033[00m] No ICMP Processes Running.") udp = True main() else: print("[\033[91mBantus\033[00m] {} Is Not A Command.\n".format( Dicput)) main() try: users = ["JOKE", "Guest"] clear = "clear" os.system(clear) username = getpass.getpass("[+] Username: "******"[+] Incorrect, Exiting.\n") exit() except KeyboardInterrupt: exit() try: passwords = ["JOKE", "Guest"] password = getpass.getpass("[+] Password: "******"JOKE": if password == passwords[0]: print("[+] Login Correct.") print("[+] Type Help To See Commands.") cookie.write("DIE")
argparser.add_argument('input_test_json', help='Input Test JSON file') argparser.add_argument('-u', '--username', help='username', required=False) argparser.add_argument('-p', '--password', help='password', required=False) args = argparser.parse_args() session_id = None username = args.username password = args.password if (username is not None and password is None): # User specified a username but not a password, so ask import getpass password = getpass.getpass("Password: "******"Accessing the Login page") r = requests.get(login_url, verify=False) csrftoken = r.cookies['csrftoken'] data = dict() data['username'] = username data['password'] = password data['csrfmiddlewaretoken'] = csrftoken headers = dict()
def menu(self): while 1: self.clear() result = Figlet(font='doom') print(result.renderText('LadroBank')) print('# Acesso ao LadroBank #') print('') menuPrincipal = ['Entrar', 'Sair'] items = 1 for mp in menuPrincipal: print(str(items) + ' - ' + mp) items = items + 1 print('') opcoesPrincipal = int(input('Selecione a operação: ')) print('') if opcoesPrincipal == 1: self.clear() ms = Figlet(font='doom') print(ms.renderText('Entrar')) print('# Entrar no Sistema #') print('') print('Digite o usuário e senha ou Digite 2 para voltar ao menu principal..') print('') loginOP = str(input('Usuario: ')) if loginOP == '2': print('...') time.sleep(1) print('Finalizando Login.') time.sleep(0.8) else: senhaOP = getpass('Senha: (Ela não aparecerá na tela enquanto digita)') print('') # Instância o nosso serviço de usuário, onde tem todas as funções relacionadas # a usuários usuarioService = UsuarioService.UsuarioService # Atribui o retorno da função que verifica o usuário e senha, retorna o Usuário # caso o login esteja correto, e falso caso o contrário response = usuarioService.efetuarLogin(usuarioService, loginOP, senhaOP) # Se o login foi válido, chama a view de operações do usuário # Se não é renderizado o menu novamente na tela if response: # Operador ternário que verifica o tipo de usuário. Se ele for admin, é carregado a visão de # administrador, caso contrário o menu padrão é aberto. cadastros.Cadastros().menu(response['id']) if response['admin'] == 'true' else operacoes.Operacoes().menu(response['id']) else: self.menu() elif opcoesPrincipal == 2: i = ' ' print('') print('Finalizando Sistema', '') time.sleep(1) for p in range(5): print(i) time.sleep(0.5) print('Obrigado por utilizar nossos serviços.') print('') msg = Figlet(font='doom') print(msg.renderText('LadroBank Agradece !')) time.sleep(0.8) break else: print('Operação não existe, tente novamente!') time.sleep(1.5) self.clear()
import string import getpass if __name__ == '__main__': if len(sys.argv) < 2: print("Usage: generate_config.py <NUMBER>") sys.exit(1) number = sys.argv[1] instance = os.environ.get('MID_INSTANCE') username = os.environ.get('MID_USERNAME') password = os.environ.get('MID_PASSWORD') if not instance: print("Instance: ", end='', flush=True, file=sys.stderr) instance = sys.stdin.readline().strip().replace('.service-now.com', '') if not username: print("Username: ", end='', flush=True, file=sys.stderr) username = sys.stdin.readline().strip() if not password: password = getpass.getpass() with open('config.xml') as infile: tmpl = string.Template(infile.read()) print(tmpl.substitute(instance=instance, username=username, password=password, number=number))
def main(): # Main parser parser = argparse.ArgumentParser(description='Rewriting of some PowerView\'s functionalities in Python') subparsers = parser.add_subparsers(title='Subcommands', description='Available subcommands') # TODO: support keberos authentication # Credentials parser credentials_parser = argparse.ArgumentParser(add_help=False) credentials_parser.add_argument('-w', '--workgroup', dest='domain', default=str(), help='Name of the domain we authenticate with') credentials_parser.add_argument('-u', '--user', required=True, help='Username used to connect to the Domain Controller') credentials_parser.add_argument('-p', '--password', help='Password associated to the username') credentials_parser.add_argument('--hashes', action='store', metavar = 'LMHASH:NTHASH', help='NTLM hashes, format is [LMHASH:]NTHASH') # AD parser, used for net* functions running against a domain controller ad_parser = argparse.ArgumentParser(add_help=False, parents=[credentials_parser]) ad_parser.add_argument('-t', '--dc-ip', dest='domain_controller', required=True, help='IP address of the Domain Controller to target') # Target parser, used for net* functions running against a normal computer target_parser = argparse.ArgumentParser(add_help=False, parents=[credentials_parser]) target_parser.add_argument('--computername', dest='target_computername', required=True, help='IP address of the computer target') # Parser for the get-adobject command get_adobject_parser= subparsers.add_parser('get-adobject', help='Takes a domain SID, '\ 'samAccountName or name, and return the associated object', parents=[ad_parser]) get_adobject_parser.add_argument('--sid', dest='queried_sid', help='SID to query (wildcards accepted)') get_adobject_parser.add_argument('--sam-account-name', dest='queried_sam_account_name', help='samAccountName to query (wildcards accepted)') get_adobject_parser.add_argument('--name', dest='queried_name', help='Name to query (wildcards accepted)') get_adobject_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_adobject_parser.add_argument('-a', '--ads-path', help='Additional ADS path') get_adobject_parser.set_defaults(func=get_adobject) # Parser for the get-netuser command get_netuser_parser= subparsers.add_parser('get-netuser', help='Queries information about '\ 'a domain user', parents=[ad_parser]) get_netuser_parser.add_argument('--username', dest='queried_username', help='Username to query (wildcards accepted)') get_netuser_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_netuser_parser.add_argument('-a', '--ads-path', help='Additional ADS path') get_netuser_parser.add_argument('--unconstrained', action='store_true', help='Query only users with unconstrained delegation') get_netuser_parser.add_argument('--admin-count', action='store_true', help='Query only users with adminCount=1') get_netuser_parser.add_argument('--allow-delegation', action='store_true', help='Return user accounts that are not marked as \'sensitive and not allowed for delegation\'') get_netuser_parser.add_argument('--spn', action='store_true', help='Query only users with not-null Service Principal Names') get_netuser_parser.set_defaults(func=get_netuser) # Parser for the get-netgroup command get_netgroup_parser= subparsers.add_parser('get-netgroup', help='Get a list of all current '\ 'domain groups, or a list of groups a domain user is member of', parents=[ad_parser]) get_netgroup_parser.add_argument('--groupname', dest='queried_groupname', default='*', help='Group to query (wildcards accepted)') get_netgroup_parser.add_argument('--sid', dest='queried_sid', help='Group SID to query') get_netgroup_parser.add_argument('--username', dest='queried_username', help='Username to query: will list the groups this user is a member of (wildcards accepted)') get_netgroup_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_netgroup_parser.add_argument('-a', '--ads-path', dest='ads_path', help='Additional ADS path') get_netgroup_parser.add_argument('--full-data', action='store_true', help='If set, returns full information on the groups, otherwise, just the samAccountName') get_netgroup_parser.add_argument('--admin-count', action='store_true', help='Query only users with adminCount=1') get_netgroup_parser.set_defaults(func=get_netgroup) # Parser for the get-netcomputer command get_netcomputer_parser= subparsers.add_parser('get-netcomputer', help='Queries informations about '\ 'domain computers', parents=[ad_parser]) get_netcomputer_parser.add_argument('--computername', dest='queried_computername', default='*', help='Computer name to query') get_netcomputer_parser.add_argument('-os', '--operating-system', dest='queried_os', help='Return computers with a specific operating system (wildcards accepted)') get_netcomputer_parser.add_argument('-sp', '--service-pack', dest='queried_sp', help='Return computers with a specific service pack (wildcards accepted)') get_netcomputer_parser.add_argument('-spn', '--service-principal-name', dest='queried_spn', help='Return computers with a specific service principal name (wildcards accepted)') get_netcomputer_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_netcomputer_parser.add_argument('-a', '--ads-path', dest='ads_path', help='Additional ADS path') get_netcomputer_parser.add_argument('--printers', action='store_true', help='Query only printers') get_netcomputer_parser.add_argument('--unconstrained', action='store_true', help='Query only computers with unconstrained delegation') get_netcomputer_parser.add_argument('--ping', action='store_true', help='Ping computers (will only return up computers)') get_netcomputer_parser.add_argument('--full-data', action='store_true', help='If set, returns full information on the groups, otherwise, just the dnsHostName') get_netcomputer_parser.set_defaults(func=get_netcomputer) # Parser for the get-netdomaincontroller command get_netdomaincontroller_parser= subparsers.add_parser('get-netdomaincontroller', help='Get a list of '\ 'domain controllers for the given domain', parents=[ad_parser]) get_netdomaincontroller_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_netdomaincontroller_parser.set_defaults(func=get_netdomaincontroller) # Parser for the get-netfileserver command get_netfileserver_parser= subparsers.add_parser('get-netfileserver', help='Return a list of '\ 'file servers, extracted from the domain users\' homeDirectory, scriptPath, and profilePath fields', parents=[ad_parser]) get_netfileserver_parser.add_argument('--target-users', nargs='+', metavar='TARGET_USER', help='A list of users to target to find file servers (wildcards accepted)') get_netfileserver_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_netfileserver_parser.set_defaults(func=get_netfileserver) # Parser for the get-dfsshare command get_dfsshare_parser= subparsers.add_parser('get-dfsshare', help='Return a list of '\ 'all fault tolerant distributed file systems for a given domain', parents=[ad_parser]) get_dfsshare_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_dfsshare_parser.add_argument('-v', '--version', nargs='+', choices=['v1', 'v2'], default=['v1', 'v2'], help='The version of DFS to query for servers: v1, v2 or all (default: all)') get_dfsshare_parser.add_argument('-a', '--ads-path', dest='ads_path', help='Additional ADS path') get_dfsshare_parser.set_defaults(func=get_dfsshare) # Parser for the get-netou command get_netou_parser= subparsers.add_parser('get-netou', help='Get a list of all current '\ 'OUs in the domain', parents=[ad_parser]) get_netou_parser.add_argument('--ouname', dest='queried_ouname', default='*', help='OU name to query (wildcards accepted)') get_netou_parser.add_argument('--guid', dest='queried_guid', help='Only return OUs with the specified GUID in their gplink property.') get_netou_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_netou_parser.add_argument('-a', '--ads-path', help='Additional ADS path') get_netou_parser.add_argument('--full-data', action='store_true', help='If set, returns full information on the OUs, otherwise, just the adspath') get_netou_parser.set_defaults(func=get_netou) # Parser for the get-netsite command get_netsite_parser= subparsers.add_parser('get-netsite', help='Get a list of all current '\ 'sites in the domain', parents=[ad_parser]) get_netsite_parser.add_argument('--sitename', dest='queried_sitename', help='Site name to query (wildcards accepted)') get_netsite_parser.add_argument('--guid', dest='queried_guid', help='Only return sites with the specified GUID in their gplink property.') get_netsite_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_netsite_parser.add_argument('-a', '--ads-path', help='Additional ADS path') get_netsite_parser.add_argument('--full-data', action='store_true', help='If set, returns full information on the sites, otherwise, just the name') get_netsite_parser.set_defaults(func=get_netsite) # Parser for the get-netsubnet command get_netsubnet_parser= subparsers.add_parser('get-netsubnet', help='Get a list of all current '\ 'subnets in the domain', parents=[ad_parser]) get_netsubnet_parser.add_argument('--sitename', dest='queried_sitename', help='Only return subnets for the specified site name (wildcards accepted)') get_netsubnet_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_netsubnet_parser.add_argument('-a', '--ads-path', help='Additional ADS path') get_netsubnet_parser.add_argument('--full-data', action='store_true', help='If set, returns full information on the subnets, otherwise, just the name') get_netsubnet_parser.set_defaults(func=get_netsubnet) # Parser for the get-netgpo command get_netgpo_parser= subparsers.add_parser('get-netgpo', help='Get a list of all current '\ 'GPOs in the domain', parents=[ad_parser]) get_netgpo_parser.add_argument('--gponame', dest='queried_gponame', default='*', help='GPO name to query for (wildcards accepted)') get_netgpo_parser.add_argument('--displayname', dest='queried_displayname', help='Display name to query for (wildcards accepted)') get_netgpo_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_netgpo_parser.add_argument('-a', '--ads-path', help='Additional ADS path') get_netgpo_parser.set_defaults(func=get_netgpo) # Parser for the get-netgroup command get_netgroupmember_parser= subparsers.add_parser('get-netgroupmember', help='Return a list of members of a domain groups', parents=[ad_parser]) get_netgroupmember_parser.add_argument('--groupname', dest='queried_groupname', help='Group to query, defaults to the \'Domain Admins\' group (wildcards accepted)') get_netgroupmember_parser.add_argument('--sid', dest='queried_sid', help='SID to query') get_netgroupmember_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query') get_netgroupmember_parser.add_argument('-a', '--ads-path', dest='ads_path', help='Additional ADS path') get_netgroupmember_parser.add_argument('-r', '--recurse', action='store_true', help='If the group member is a group, try to resolve its members as well') get_netgroupmember_parser.add_argument('--use-matching-rule', action='store_true', help='Use LDAP_MATCHING_RULE_IN_CHAIN in the LDAP search query when -Recurse is specified.\n' \ 'Much faster than manual recursion, but doesn\'t reveal cross-domain groups') get_netgroupmember_parser.add_argument('--full-data', action='store_true', help='If set, returns full information on the members') get_netgroupmember_parser.set_defaults(func=get_netgroupmember) # Parser for the get-netsession command get_netsession_parser= subparsers.add_parser('get-netsession', help='Queries a host to return a '\ 'list of active sessions on the host (you can use local credentials instead of domain credentials)', parents=[target_parser]) get_netsession_parser.set_defaults(func=get_netsession) #Parser for the get-localdisks command get_localdisks_parser = subparsers.add_parser('get-localdisks', help='Queries a host to return a '\ 'list of active disks on the host (you can use local credentials instead of domain credentials)', parents=[target_parser]) get_localdisks_parser.set_defaults(func=get_localdisks) #Parser for the get-netdomain command get_netdomain_parser = subparsers.add_parser('get-netdomain', help='Queries a host for available domains', parents=[ad_parser]) get_netdomain_parser.set_defaults(func=get_netdomain) # Parser for the get-netshare command get_netshare_parser= subparsers.add_parser('get-netshare', help='Queries a host to return a '\ 'list of available shares on the host (you can use local credentials instead of domain credentials)', parents=[target_parser]) get_netshare_parser.set_defaults(func=get_netshare) # Parser for the get-netloggedon command get_netloggedon_parser= subparsers.add_parser('get-netloggedon', help='This function will '\ 'execute the NetWkstaUserEnum RPC call ti query a given host for actively logged on '\ 'users', parents=[target_parser]) get_netloggedon_parser.set_defaults(func=get_netloggedon) # Parser for the get-netlocalgroup command get_netlocalgroup_parser= subparsers.add_parser('get-netlocalgroup', help='Gets a list of '\ 'members of a local group on a machine, or returns every local group. You can use local '\ 'credentials instead of domain credentials, however, domain credentials are needed to '\ 'resolve domain SIDs.', parents=[target_parser]) get_netlocalgroup_parser.add_argument('--groupname', dest='queried_groupname', help='Group to list the members of (defaults to the local \'Administrators\' group') get_netlocalgroup_parser.add_argument('--list-groups', action='store_true', help='If set, returns a list of the local groups on the targets') get_netlocalgroup_parser.add_argument('-t', '--dc-ip', dest='domain_controller', default=str(), help='IP address of the Domain Controller (used to resolve domain SIDs)') get_netlocalgroup_parser.add_argument('-r', '--recurse', action='store_true', help='If the group member is a domain group, try to resolve its members as well') get_netlocalgroup_parser.set_defaults(func=get_netlocalgroup) # Parser for the invoke-checklocaladminaccess command invoke_checklocaladminaccess_parser = subparsers.add_parser('invoke-checklocaladminaccess', help='Checks '\ 'if the given user has local admin access on the given host', parents=[target_parser]) invoke_checklocaladminaccess_parser.set_defaults(func=invoke_checklocaladminaccess) # Parser for the invoke-userhunter command invoke_userhunter_parser = subparsers.add_parser('invoke-userhunter', help='Finds '\ 'which machines domain users are logged into', parents=[ad_parser]) invoke_userhunter_parser.add_argument('--computername', dest='queried_computername', nargs='+', default=list(), help='Host to enumerate against') invoke_userhunter_parser.add_argument('--computerfile', dest='queried_computerfile', type=argparse.FileType('r'), help='File of hostnames/IPs to search') invoke_userhunter_parser.add_argument('--computer-adspath', dest='queried_computeradspath', type=str, help='ADS path used to search computers against the DC') invoke_userhunter_parser.add_argument('--unconstrained', action='store_true', help='Query only computers with unconstrained delegation') invoke_userhunter_parser.add_argument('--groupname', dest='queried_groupname', help='Group name to query for target users') invoke_userhunter_parser.add_argument('--targetserver', dest='target_server', help='Hunt for users who are effective local admins on this target server') invoke_userhunter_parser.add_argument('--username', dest='queried_username', help='Hunt for a specific user name') invoke_userhunter_parser.add_argument('--user-adspath', dest='queried_useradspath', type=str, help='ADS path used to search users against the DC') invoke_userhunter_parser.add_argument('--userfile', dest='queried_userfile', type=argparse.FileType('r'), help='File of user names to target') invoke_userhunter_parser.add_argument('--threads', type=int, default=1, help='Number of threads to use (default: %(default)s)') invoke_userhunter_parser.add_argument('-v', '--verbose', action='store_true', help='Displays results as they are found') invoke_userhunter_parser.add_argument('--admin-count', action='store_true', help='Query only users with adminCount=1') invoke_userhunter_parser.add_argument('--allow-delegation', action='store_true', help='Return user accounts that are not marked as \'sensitive and '\ 'not allowed for delegation\'') invoke_userhunter_parser.add_argument('--stop-on-success', action='store_true', help='Stop hunting after finding target user') invoke_userhunter_parser.add_argument('--check-access', action='store_true', help='Check if the current user has local admin access to the target servers') invoke_userhunter_parser.add_argument('-d', '--domain', dest='queried_domain', help='Domain to query for machines') invoke_userhunter_parser.add_argument('--stealth', action='store_true', help='Only enumerate sessions from commonly used target servers') invoke_userhunter_parser.add_argument('--stealth-source', nargs='+', choices=['dfs', 'dc', 'file'], default=['dfs', 'dc', 'file'], help='The source of target servers to use, '\ '\'dfs\' (distributed file server), \'dc\' (domain controller), '\ 'or \'file\' (file server) (default: all)') invoke_userhunter_parser.add_argument('--show-all', action='store_true', help='Return all user location results') invoke_userhunter_parser.add_argument('--foreign-users', action='store_true', help='Only return users that are not part of the searched domain') invoke_userhunter_parser.set_defaults(func=invoke_userhunter) args = parser.parse_args() if args.hashes: try: args.lmhash, args.nthash = args.hashes.split(':') except ValueError: args.lmhash, args.nthash = 'aad3b435b51404eeaad3b435b51404ee', args.hashes finally: args.password = str() else: args.lmhash = args.nthash = str() if args.password is None and not args.hashes: from getpass import getpass args.password = getpass('Password:'******'func', 'hashes'): parsed_args[k] = v #try: results = args.func(**parsed_args) #except Exception, e: #print >>sys.stderr, repr(e) #sys.exit(-1) try: for x in results: x = str(x) print x if '\n' in x: print '' except TypeError: print results
#! /bin/python import getpass word = getpass.getpass('Word: ') def hangman(word): answer = '%d %d %d %d %d %d %d '% (1, 2, 3, 4, 5, 6, 7) print answer tries = 1 while tries <= 5: guess = raw_input('guess the word one letter at a time: ') #if len(guess)>1: # guess = raw_input('try again: guess the word one letter at a time: ') if isinstance(guess, (int)): guess = raw_input('try again: guess the word one letter at a time: ') if guess in word: for i in range(len(word)): if word[i] == guess: answer = answer.replace("%d " % (i+1), guess, i+1) print answer if answer == word: print "you win" if answer == word: return True else: print "u have tried this many times %d you only get 5 tries" % (tries) tries += 1 print "Better luck next time BITCH"
def cli(): clear() s = Snapchat() username = raw_input('Please enter username: '******'win'): password = getpass.getpass('Please enter password: '******'Please enter password (empty for token entry): ') if password == '': auth_token = raw_input('Please enter auth token: ') if not s.login_token(username, auth_token): raw_input('Invalid username/auth token combo') clear() exit() else: if not s.login(username, password): raw_input('Invalid username/password combo') clear() exit() pynotify.init("pySnap") queue = Queue.Queue() bg_scheduler = sched.scheduler(time.time, time.sleep) bg_scheduler.enter(300, 1, check_snaps, (s, bg_scheduler, queue)) bg_check = threading.Thread(target=bg_scheduler.run) bg_check.setDaemon(True) bg_check.start() snaps = s.get_snaps() user_input = None functions = { 'R': lambda: s.get_snaps(), 'S': send } clear() while user_input != 'X': print 'Welcome to Snapchat!' print 'Logged in as {0} (token {1})'.format(username, s.auth_token) print print '{0} pending snaps:'.format(len(snaps)) num = 1 for snap in snaps: #print snap #print snap['media_type'] dt = datetime.fromtimestamp(snap['sent'] / 1000) ext = s.media_type(snap['media_type'], binary=False) timestamp = str(snap['sent']).replace(':', '-') filename = '{}+{}+{}.{}'.format(timestamp, snap['sender'], snap['id'], ext) path = PATH + filename # check if file already exists so we don't need to redownload ''' if not os.path.isfile(path): data = s.get_snap(snap['id']) with open(path, 'wb') as outfile: outfile.write(data) ''' snap['path'] = path print '[{0}] Snap from {1} ({2}s, Sent {3})'.format(num, snap['sender'], snap['time'], dt) num += 1 print print '[R] - refresh snaps' print '[S] - send a snap' print '[X] - exit' user_input = raw_input('Enter an option: ').upper() num_input = int(user_input) if user_input.isdigit() else None if len(snaps) >= num_input > 0: dt = datetime.fromtimestamp(snap['sent'] / 1000) ext = s.media_type(snap['media_type'], binary=False) timestamp = str(snap['sent']).replace(':', '-') filename = '{}+{}+{}.{}'.format(timestamp, snap['sender'], snap['id'], ext) path = PATH + filename snap = snaps[num_input - 1] if not os.path.isfile(path): data = s.get_snap(snap['id']) with open(path, 'wb') as outfile: outfile.write(data) snap['path'] = path file_path = snap['path'] # open /dev/null or equivalent so we can redirect stdout/stderr to it nullfile = open(os.devnull, 'w') # cross-platform method to open a media file p = None scheduler = sched.scheduler(time.time, time.sleep) # try: if True: if sys.platform.startswith('linux'): p = subprocess.Popen(['xdg-open', file_path], stdout=nullfile, stderr=nullfile, preexec_fn=os.setsid) elif sys.platform.startswith('darwin'): p = subprocess.Popen(['open', file_path], stdout=nullfile, stderr=nullfile) elif sys.platform.startswith('win'): p = subprocess.Popen(['start /WAIT', file_path], stdout=nullfile, stderr=nullfile) else: print 'I don\'t recognize your operating system: {0}'.format(sys.platform) scheduler.enter(snap['time'], 1, mark_read, (s, snap, p, queue)) t = threading.Thread(target=scheduler.run) t.start() # except: # print 'Uh oh, I was unable to open the file.' elif user_input in functions: if user_input == 'R': queue.put(functions[user_input]()) print 'Refreshed!' else: functions[user_input](s) elif user_input != 'X': print 'I don\'t recognize that command.' if user_input != 'X': raw_input('Press enter to continue...') clear() if not queue.empty(): while not queue.empty(): buf = queue.get() new_snaps = [] for st in buf: found = False for snap in snaps: if st['id'] == snap['id']: found = True break if found == True: new_snaps.append(st) for snap in new_snaps: title = 'New snap from {0}!'.format(snap['sender']) dt = datetime.fromtimestamp(snap['sent'] / 1000) message = '{0} seconds, sent {1}'.format(snap['time'], dt) notice = pynotify.Notification(title, message) notice.show() # snaps = buf sys.exit(0)
if c.name == name: obj = c break else: obj = c break return obj parser = argparse.ArgumentParser() parser.add_argument('--folder') args_list = parser.parse_args() username = '******' password = getpass("Enter in vcenter password: ") vcenter_ip = 'visa-vcsa.rangers.lab' vcenter_port = '443' cluster_name = 'Visa-POC-Cluster' folder_name = args_list.folder template_name = 'Centos7-Throughput' customization_spec_name = 'Centos7-spec' new_vm_prefix = 'linTP' # This will connect us to vCenter s = SmartConnectNoSSL(host=vcenter_ip, user=username, pwd=password, port=vcenter_port) content = s.RetrieveContent() #Get Folder folder = get_obj(content, [vim.Folder], folder_name)
print( 'Bad username (be sure NOT to use your email, this method is depreciated)\nEnding process' ) quit() # Need better way to parse public key pub_key = requests.get('https://keybase.io/' + user + '/key.asc').text.split('\n') if pub_key[0].split(' ', 1)[0] == '404': print('There is no public key associated with this username.') quit() salt = js['salt'] session = js['login_session'] pass_phrase = scrypt.hash(getpass.getpass( 'Keybase password (this cannot be accessed or stored outside of this script): ' ), salt, N=32768, r=8, p=1, buflen=256) v4 = pass_phrase[194:224] v5 = pass_phrase[224:256] nonce = nonce_gen(32) print(v4) print(v5) print(nonce)
#coding=utf-8 import paramiko import time import re #datatime内建模块是显示时间用的. from datetime import datetime import socket import getpass #raw_input()和getpass.getpass()提示用户输入用户名密码. datetime.now()方法记录当前时间,年、月、日赋值给date, # 时、分、秒复制给time_now username = raw_input('Enter your SSH username: '******'Enter your SSH password: '******'reachable_ip.txt') number_of_switch = len(iplist.readlines()) total_number_of_ports = number_of_switch * 16
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Hero lws import getpass usename = "lin" passworld = "abcdefg" _usename = str(input("usename:")) _passworld = str(getpass.getpass("passworld:")) if _usename == usename and _passworld == passworld: print("Welcome to user {name} login...".format(name = usename)) else: print("invalid username or passworld...")
import argparse import getpass parser = argparse.ArgumentParser() parser.add_argument('-ip', '--ipaddress', help='IP address of switch', required=True) parser.add_argument('-user', '--user', help='Username', required=True) parser.add_argument('-pass', '--password', help='Password', required=False) args = parser.parse_args() if args.password == None: args.password = getpass.getpass() import requests import json """ Modify these please """ url = 'http://%s/ins' % args.ipaddress switchuser = args.user switchpassword = args.password myheaders = {'content-type': 'application/json'} payload = { "ins_api": { "version": "1.0", "type": "cli_show",
spinner.stop_and_persist(symbol='🦄 '.encode('utf-8'), text=res['m']) except: spinner.fail('数据提交失败') return if __name__=="__main__": if os.path.exists('./config.json'): configs = json.loads(open('./config.json', 'r').read()) username = configs["username"] password = configs["password"] hour = configs["schedule"]["hour"] minute = configs["schedule"]["minute"] else: username = input("👤 浙大统一认证用户名: ") password = getpass.getpass('🔑 浙大统一认证密码: ') print("⏲ 请输入定时时间(默认每天6:05)") hour = input("\thour: ") or 6 minute = input("\tminute: ") or 5 main(username, password) # Schedule task scheduler = BlockingScheduler() scheduler.add_job(main, 'cron', args=[username, password], hour=hour, minute=minute) print('⏰ 已启动定时程序,每天 %02d:%02d 为您打卡' %(int(hour), int(minute))) print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass
def user_delete(): while True: choice = int(input("What type of account do you have?\n1.Super-user\n2.Normal User\n3.<-Back\n\n^_^: ")) if choice == 3: break elif choice > 3: print("Invalid entry") elif choice == 2: print("Please login with your credentials. ") user_name = '/N' + usrnm() password = getpass("Password") if authenticate(user_name, password): conf = input("Are you sure you want to delete the account with username '{0}'?(Y/N)\n\n^_^ :".format( user_name[2:])).lower() if conf == 'y': user_dict.pop(user_name) print("The user '{0}' has been deleted".format(user_name[2:])) sleep(2) return False elif conf == 'n': print('\nAccount deletion cancelled\n') sleep(2) continue else: print("Please enter the correct option") else: print("You can have the superuser delete the user account") sleep(2) elif choice == 1: print("Please login with your credentials. ") user_name = '/S' + usrnm() password = getpass("Password:"******"Select the user type of the account you would like to delete\n1.Normal\n2.Priviliged\n3.<-Back\n\n^_^: ")) if del_usr_type == 3: break del_usr_name = usr_typ[del_usr_type] + input( "Enter the username of the account to be deleted \n\n^_^: ") if del_usr_name in user_dict: while True: conf = input("The user '{0}' will be deleted. Are you sure? (Y/N): \n\n^_^: ".format( del_usr_name[2:])).lower() if conf == 'y': user_dict.pop(del_usr_name) print("The user '{0}' has been deleted".format(del_usr_name[2:])) sleep(2) break elif conf == 'n': print('\nAccount deletion cancelled\n') sleep(2) break else: print("Please enter the correct option") else: print("User '{0}' is not found in database".format(del_usr_name[2:])) else: print("You don't seem to have enough privileges to make changes.\n")
if rpcpass == "": access = ServiceProxy("http://127.0.0.1:5010") else: access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:5010") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "encryptwallet": try: pwd = getpass.getpass(prompt="Enter passphrase: ") pwd2 = getpass.getpass(prompt="Repeat passphrase: ") if pwd == pwd2: access.encryptwallet(pwd) print "\n---Wallet encrypted. Server stopping, restart to run with encrypted wallet---\n" else: print "\n---Passphrases do not match---\n" except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a Bitcoin address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n"
from time import sleep from pprint import pprint from getpass import getpass logging.basicConfig(level=logging.DEBUG,format="%(levelname)s: %(message)s") if len(sys.argv) < 2: sys.argv.append( "localhost:27015" ) addrs = [arg.split(":",1) for arg in sys.argv[1:]] for host, port in addrs: name = "{0}:{1}".format(host,port) try: rcon = os.environ["P"+name.replace(".","").replace(":","")] except KeyError: rcon = getpass( "rcon password for {0}: ".format(name) ) s = RCON( host, int(port), rcon ) s.connect() print s r = s.rcon( "stats", 4 ) print r print def cb( rid, ret, str1 ): print str1 s.execute( "help", cb=cb ) time.sleep(10)
if option < 0 or option > 2: print("\nOh... okay!") sleep(1) continue elif option != 2: user_creator('/N') elif option == 2: prot_1 = input( "You need to be a super-user to create an account priviliged accounts. Would you like to login as superuser(Y/N)\n\n^_^: ") if prot_1.lower() == 'y': user_name = '/S' + usrnm() password = getpass("Password") if authenticate(user_name, password): user_creator("/S") elif choice == 2: while True: user_type = int(input("Enter the account type:\n\t1.Super-user\n\t2.Normal User\n\t3.<-Back\n\n^_^: ")) if user_type == 3: break elif user_type == 1: usr_typ = '/S' elif user_type == 2: usr_typ = '/N' else: print("Invalid entry") system('cls')
def handle(self, *args, **options): username = options[self.UserModel.USERNAME_FIELD] database = options['database'] # If not provided, create the user with an unusable password password = None user_data = {} # Same as user_data but with foreign keys as fake model instances # instead of raw IDs. fake_user_data = {} # Do quick and dirty validation if --noinput if not options['interactive']: try: if not username: raise CommandError("You must use --%s with --noinput." % self.UserModel.USERNAME_FIELD) username = self.username_field.clean(username, None) for field_name in self.UserModel.REQUIRED_FIELDS: if options[field_name]: field = self.UserModel._meta.get_field(field_name) user_data[field_name] = field.clean( options[field_name], None) else: raise CommandError( "You must use --%s with --noinput." % field_name) except exceptions.ValidationError as e: raise CommandError('; '.join(e.messages)) else: # Prompt for username/password, and any other required fields. # Enclose this whole thing in a try/except to catch # KeyboardInterrupt and exit gracefully. default_username = get_default_username() try: if hasattr(self.stdin, 'isatty') and not self.stdin.isatty(): raise NotRunningInTTYException("Not running in a TTY") # Get a username verbose_field_name = self.username_field.verbose_name while username is None: input_msg = capfirst(verbose_field_name) if default_username: input_msg += " (leave blank to use '%s')" % default_username username_rel = self.username_field.remote_field input_msg = '%s%s: ' % ( input_msg, ' (%s.%s)' % (username_rel.model._meta.object_name, username_rel.field_name) if username_rel else '') username = self.get_input_data(self.username_field, input_msg, default_username) if not username: continue if self.username_field.unique: try: self.UserModel._default_manager.db_manager( database).get_by_natural_key(username) except self.UserModel.DoesNotExist: pass else: self.stderr.write( "Error: That %s is already taken." % verbose_field_name) username = None for field_name in self.UserModel.REQUIRED_FIELDS: field = self.UserModel._meta.get_field(field_name) user_data[field_name] = options[field_name] while user_data[field_name] is None: message = '%s%s: ' % ( capfirst(field.verbose_name), ' (%s.%s)' % ( field.remote_field.model._meta.object_name, field.remote_field.field_name, ) if field.remote_field else '', ) input_value = self.get_input_data(field, message) user_data[field_name] = input_value fake_user_data[field_name] = input_value # Wrap any foreign keys in fake model instances if field.remote_field: fake_user_data[ field_name] = field.remote_field.model( input_value) # Get a password while password is None: password = getpass.getpass() password2 = getpass.getpass('Password (again): ') if password != password2: self.stderr.write( "Error: Your passwords didn't match.") password = None # Don't validate passwords that don't match. continue if password.strip() == '': self.stderr.write( "Error: Blank passwords aren't allowed.") password = None # Don't validate blank passwords. continue try: validate_password(password2, self.UserModel(**fake_user_data)) except exceptions.ValidationError as err: self.stderr.write('\n'.join(err.messages)) password = None except KeyboardInterrupt: self.stderr.write("\nOperation cancelled.") sys.exit(1) except NotRunningInTTYException: self.stdout.write( "Superuser creation skipped due to not running in a TTY. " "You can run `manage.py createsuperuser` in your project " "to create one manually.") if username: user_data[self.UserModel.USERNAME_FIELD] = username user_data['password'] = password user_data["supervisor"] = True self.UserModel._default_manager.db_manager( database).create_superuser(**user_data) if options['verbosity'] >= 1: self.stdout.write("Superuser created successfully.")
try: prot = sys.argv[1] # Protocol src = addr(sys.argv[2]) # Source ip address dst = addr(sys.argv[3]) # Destination ip address dst_port = sys.argv[4] # Destination port device = sys.argv[5] # Router/Switch address except: print( 'Usage: protocol, source ip, destination ip, destination port, device ip' ) exit() username = input('Username: '******'Password: '******'device_type': 'cisco_ios', 'ip': device, 'username': username, 'password': password, 'secret': '' } try: ssh_connect = ConnectHandler(**cisco_switch) except: print('Unable to connect to ' + device) exit()
import urllib.request import http.cookiejar import sys import getpass import re url = "http://e.ustb.edu.cn/userPasswordValidate.portal" #登陆url data = {} #表单 data['Login.Token1'] = input("账号") data['Login.Token2'] = getpass.getpass("密码") data['goto'] = r'http://e.ustb.edu.cn/loginSuccess.portal' data['gotoOnFail'] = r'http://e.ustb.edu.cn/loginFailure.portal' headers = { 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3' } url = "http://e.ustb.edu.cn/userPasswordValidate.portal" data = {} data['Login.Token1'] = input("账号") data['Login.Token2'] = getpass.getpass("密码") data['goto'] = r'http://e.ustb.edu.cn/loginSuccess.portal' data['gotoOnFail'] = r'http://e.ustb.edu.cn/loginFailure.portal' data = urllib.parse.urlencode(data) data = data.encode('utf-8') def saveCookie(url, data): cj = http.cookiejar.CookieJar()
local_path = os.path.join(target_folder, basename) if os.path.exists(local_path): logging.debug("- Skipping %s, already downloaded", local_path) continue logging.debug("- Downloading %s", key.key) local_tmp_path = local_path + "_tmp" key.get_contents_to_filename(local_tmp_path) os.rename(local_tmp_path, local_path) if __name__ == "__main__": logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) logging.getLogger("boto").setLevel(logging.INFO) args = parse_args() logging.info("Download latest meta-review dump to %s", args.dest_folder) assert os.path.exists(args.dest_folder) and os.path.isdir( args.dest_folder), "Output folder does not exist!" aws_access_key = getpass( "Please enter your AWS access key and press Enter (characters not visible): " ) aws_secret_key = getpass("AWS secret key: ") download_latest(aws_access_key, aws_secret_key, args.dest_folder) logging.info("Done!")
def main(): #check argument validation try: userInput = checkArg() except InvalidArgumen as ea: print(ea.msg) print("try cpaneltop --help ") sys.exit() except NoUserHost as eu: print(eu.msg) print("try cpaneltop --help ") sys.exit() except UnknownParameter as ep: print(ep.msg) print("try cpaneltop --help ") sys.exit() #store user password and add this key/value to userInput Dictionary userInput['password'] = getpass("enter your password: "******"Connecting...") """ userInput is like this: { 'user@host': '*****@*****.**', 'port': 0, #alwayze str 'time': 1, #alwayze integer 'help': 0, 'user': '******', 'host': 'domain', 'password' : 'getpass' //initial in main and add to perv dictionary } """ #if user didnt use to time argument we set default period to 10 second if userInput['time'] == 0: userInput['time'] += 10 if userInput['ssl'] == 0: userInput['ssl'] = 'no' #find out wheter user entered port or not if userInput['port'] == '0': host1 = CpanelHost(username=userInput['user'],domain=userInput['host'],\ password=userInput['password'],period=userInput['time'],ssl=userInput['ssl']) else: host1 = CpanelHost(username=userInput['user'],domain=userInput['host'],\ password=userInput['password'],period=userInput['time'],port=userInput['port'],ssl=userInput['ssl']) #check internet connection is avaible if netIsOn() == False: print("there is no Internet Connection") sys.exit() #initialize resource information with 1 requests primaryTime = host1.period host1.period = 1 try: host1.checkStatus() print("OK") except KeyError: print("can't connect to Host! :(") sys.exit() if 'data' not in host1.getResource(justData=False): raise CantConnect("cant connect and fetch resource usage Information") #check resource detail in background every X second with below thread host1.period = primaryTime checkStatusOnlineThread = Thread(target=host1.checkStatus, args=(), daemon=True) checkStatusOnlineThread.start() def __windowShow(topWindow): curses.curs_set(0) h, w = topWindow.getmaxyx() if h < 24 or w < 78: topWindow.addstr( 0, 0, 'console size is not enough must be greater than 24*78') topWindow.getch() sys.exit() topWindow.nodelay(True) topWindow.timeout(500) curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_YELLOW) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) while True: topWindow.clear() topWindow.refresh() table = createTable(host1.getResource()) lineStr = str(table).split("\n") headStr = " CpanelTop >>> "+"Host: "+host1.getDomain()+" "+"user: "******" "+"port: "+str(host1.getPort())+" "+'request: '+str(host1.getRequestNumber())+" " topWindow.attron(curses.color_pair(1)) topWindow.addstr(0, 0, headStr) topWindow.attroff(curses.color_pair(1)) tableWidth = len(lineStr[0]) tableHeight = len(lineStr) for index, row in enumerate(lineStr, 1): topWindow.addstr(index, 2, row) topWindow.refresh() topWindow.attron(curses.color_pair(2)) textpad.rectangle(topWindow, 1, 2, tableHeight, tableWidth + 1) topWindow.attron(curses.color_pair(2)) topWindow.refresh() key = topWindow.getch() if str(key) == "113" or str(key) == "813": sys.exit() topWindow.nodelay(False) curses.curs_set(1) sys.exit() curses.wrapper(__windowShow) sys.exit()
""".format(IP, port_no) out_file.write(core_line) os.system("sudo hadoop-daemon.sh start datanode") os.system("clear") os.system("tput setaf 1") print("\t\t\tWelcome To The TUI Program") os.system("tput setaf 7") print("\t\t\t--------------------------") #To set password i = 0 while i < 2: passwd = getpass.getpass("Enter the Password : "******"Pass@123" if passwd == apass: os.system("tput setaf 4") print("Logged in successfully") os.system("tput setaf 7") break else: os.system("tput setaf 1") print("Wrong Password. Please retry") os.system("tput setaf 7") i += 1 else: os.system("tput setaf 1") print("Authentication failed\nexiting........") os.system("tput setaf 7")