你能告诉我输入,以便check语句与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
代码没问题,但唯一的办法是绕过输入检查 有一个要识别的错误
答案 0 :(得分:1)
如果要检查来自用户的输入是否只有数字,那么您可以使用方法 - str.isnumeric()
来检查字符串是否只包含数字。
示例 -
>>> "123".isnumeric()
True
>>> "123.21".isnumeric()
False
>>> "abcd".isnumeric()
False
您可以执行此检查而不是try / except块(因为在此块之后您实际上并未将密码用作数字)。
答案 1 :(得分: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]+): ")
这将继续提示,直到输入一个数字。