2015-08-15 67 views
0

你能告诉我的输入,以便检查语句与输入引脚的try..except一起传递比较字符串以一些数字相当于

#!/usr/bin/python 
# Secure Pin system 
import sys 

users = {'admin': '<REDACTED>'} 

def register(username, password): 
    if username in users: 
      return "User already exits." 
    users[username] = password 
    return "Registered Successfully."   

def login(username, password): 
    if username not in users: 
      return "Wrong pin/password" 
    if password != users[username]: 
      return "Wrong pin/password" 
    if username == "admin": 
      return "The FLAG is what you entered in the \"Pin\" field to get here!" 
    return "You must login as admin to get the flag" 

def handle_command(command): 
    if command not in ["REG", "LOGIN"]: 
      return "Invalid Command!" 
    print "Username:", 
    sys.stdout.flush() 
    username = raw_input() 

    try: 
      print "Pin ([0-9]+):", 
      sys.stdout.flush() 
      password = input() # we only support numbers in password 

    except: 
      return "Please enter a valid password. Pin can only contain digits."   
    if command == 'REG': 
      return register(username, password) 
    if command == 'LOGIN': 
      return login(username, password) 

if __name__=="__main__": 
    print "Hey welcome to the admin panel"     
    print "Commands: REG, LOGIN" 
    try: 
      print ">", 
      sys.stdout.flush() 
      command = raw_input() 
      print handle_command(command) 
      sys.stdout.flush() 
    except: 
      pass 

的代码是好的,但是唯一是要绕过输入检查 有一个缺陷是要确定的

回答

1

如果你想检查用户输入是否只有数字,那么你可以使用方法 - str.isnumeric(),检查字符串是否只包含数字。

示例 -

>>> "123".isnumeric() 
True 
>>> "123.21".isnumeric() 
False 
>>> "abcd".isnumeric() 
False 

你可以做到这一点,而不是检查一试的/ except块(因为你真的不使用密码作为该块后的数字)。

+0

的问题是,给定的代码,我比较字符串 – goodperson

+0

比较字符串什么/ –

+0

是通过上面的代码中的数字或东西 – goodperson

0

为了确保用户输入一个号码,你可以转换脚本如下使用功能:

def get_input_number(prompt): 
    while True: 
     try: 
      user_num = int(raw_input(prompt)) 
      return user_num 
     except ValueError: 
      print "Please enter a valid password. Pin can only contain digits." 

password = get_input_number("Pin ([0-9]+): ") 

这将然后继续提示,直到输入一个数字。