将字符串与一些数字等价项进行比较

2024-04-20 10:37:51 发布

您现在位置:Python中文网/ 问答频道 /正文

你能告诉我输入是什么吗?这样check语句就可以和try一起传递了,除了输入pin

#!/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

代码是正确的,但唯一的事情是绕过输入检查 有一个bug需要识别


Tags: inreturnifadminstdoutsyspinusername
2条回答

为了确保用户输入一个数字,可以将脚本转换为使用以下函数:

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]+): ")

然后会一直提示,直到输入一个数字。你知道吗

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

示例-

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

您可以执行此检查,而不是try/except块(因为您实际上不使用密码作为此块后面的数字)。你知道吗

相关问题 更多 >