2015-08-15 62 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]+): ") 

這將然後繼續提示,直到輸入一個數字。