如何使用Python构建OTP验证系统?
创始人
2025-07-01 20:31:04
0

译者 | 布加迪

审校 | 重楼

即使您的密码被盗,OTP验证系统也可以充当安全的关键要素。它让您无需记住密码,充当额外的安全层,并降低了网络钓鱼的风险。

不妨学习用Python建立一个OTP验证系统,它会向您的手机号码发送一个OTP,有效期只有两分钟,如果您连续三次输错OTP,账户会被锁住。

安装Tkinter、Twilio和Random模块

Tkinter允许您创建桌面应用程序。它提供了各种小组件,比如按钮、标签和文本框,使开发应用程序变得更容易。

Twilio模块帮助您把短信、彩信和电话呼叫等通信功能与验证径直整合到应用程序中。它有一个基于云的基础设施,以及令人惊叹的功能,比如号码配置、消息模板和呼叫记录。

要安装Twilio模块和Tkinter模块,在终端执行如下命令:

pip install twilio tk

Random模块是内置的Python模块,用于生成伪随机数。有了该模块,您可以生成随机数、从列表中选择随机元素、打乱列表内容等。您可以用它来构建掷骰子模拟、列表打乱器或随机密码生成器。

生成Twilio API并获取电话号码

要使用Twilio并向您的手机发送OTP请求,您需要身份验证凭据以及Twilio电话号码。为此:

1. 注册一个Twilio账户,访问Twilio控制台。

2. 向下滚动并点击“获取电话号码”按钮。复制已生成的电话号码。

3. 向下滚动到“账户信息”部分。复制“账户SID”和“身份验证令牌”。

构建应用程序的结构

事先声明一下,您可以在这个GitHub代码仓库中找到使用Python构建OTP验证系统的完整源代码。

导入必要的模块,并设置身份验证凭据。初始化Twilio客户软件以验证身份,并作为API调用的入口点。将到期失效时间设为两分钟。

定义一个类:OTPVerification,并初始化构造函数以设置变量的默认值,同时初始化根窗口,并设置应用程序的标题和维度。

import tkinter as tk
from tkinter import messagebox
from twilio.rest import Client
import random
import threading
import time

account_sid = "YOUR_ACCOUNT_SID"
auth_token = "YOUR_AUTH_TOKEN"
client = Client(account_sid, auth_token)
expiration_time = 120

class OTPVerification:
 def __init__(self, master):
 self.master = master
 self.master.title('OTP Verification')
 self.master.geometry("600x275")
 self.otp = None
 self.timer_thread = None
 self.resend_timer = None
 self.wrong_attempts = 0
 self.locked = False
 self.stop_timer = False

定义三个标签来请求手机号码和OTP,并在程序发送OTP后显示计时器。设置父元素、它应该显示的文本以及该有的字体样式。同样,创建两个输入小组件以获取用户输入。设置父元素、宽度和字体样式。

创建三个按钮来发送OTP、重新发送OTP和验证OTP。设置父元素、它应该显示的文本、点击时执行的命令及其字体样式。使用pack方法组织这些元素。

self.label1 = tk.Label(self.master, 
 text='Enter your mobile number:',
 fnotallow=('Arial', 14))
 self.label1.pack()

 self.mobile_number_entry = tk.Entry(self.master, 
 width=20,
 fnotallow=('Arial', 14))
 self.mobile_number_entry.pack()

 self.send_otp_button = tk.Button(self.master, 
 text='Send OTP', 
 command=self.send_otp,
 fnotallow=('Arial', 14))
 self.send_otp_button.pack()

 self.timer_label = tk.Label(self.master, 
 text='', 
 fnotallow=('Arial', 12, 'bold'))
 self.timer_label.pack()

 self.resend_otp_button = tk.Button(self.master, 
 text='Resend OTP', 
 state=tk.DISABLED, 
 command=self.resend_otp,
 fnotallow=('Arial', 14))
 self.resend_otp_button.pack()

 self.label2 = tk.Label(self.master, 
 text='Enter OTP sent to your mobile:',
 fnotallow=('Arial', 14))
 self.label2.pack()

 self.otp_entry = tk.Entry(self.master, 
 width=20,
 fnotallow=('Arial', 14))
 self.otp_entry.pack()

 self.verify_otp_button = tk.Button(self.master, 
 text='Verify OTP', 
 command=self.verify_otp,
 fnotallow=('Arial', 14))
 self.verify_otp_button.pack()

构建应用程序的功能

定义一个方法start_timer(),它在单独的线程中运行timer_countdown。

def start_timer(self):
 self.timer_thread = threading.Thread(target=self.timer_countdown)
 self.timer_thread.start()

定义一个方法timer_countdown()。记录开始时间,并运行一个无限循环,该循环获取当前时间并计算已流逝的时间和剩余时间。如果stop_timer为true,终止循环。如果剩余时间小于或等于0,显示错误消息框,表明OTP已过期。

激活重新发送OTP按钮,将OTP设置为none,并终止。否则,计算剩余的分钟和秒,将其显示在计时器标签上,并休眠一秒钟。

def timer_countdown(self):
 start_time = time.time()
 while True:
 current_time = time.time()
 elapsed_time = current_time - start_time
 remaining_time = expiration_time - elapsed_time
 if self.stop_timer:
 break
 if remaining_time <= 0:
 messagebox.showerror('Error', 'OTP has expired.')
 self.resend_otp_button.config(state=tk.NORMAL)
 self.otp = None
 break
 minutes = int(remaining_time // 60)
 seconds = int(remaining_time % 60)
 timer_label = f'Time Remaining: {minutes:02d}:{seconds:02d}'
 self.timer_label.config(text=timer_label)
 time.sleep(1)

定义一个方法send_otp()。如果locked为true,显示相应的消息。否则提取并验证电话号码,生成一个随机的OTP。提供之前获取的手机号码,使用客户软件将OTP发送到您的电话号码。显示消息框,启动计时器,禁用按钮,并完全清除输入内容。

def send_otp(self):
   if self.locked:
 messagebox.showinfo('Account Locked', 'Your account is locked. Try  again later.')
 return
 mobile_number = self.mobile_number_entry.get()
 if not mobile_number:
 messagebox.showerror('Error', 'Please enter your mobile number.')
 return

 self.otp = random.randint(1000, 9999)
 message = client.messages.create(
 body=f'Your OTP is {self.otp}.',
 from_='TWILIO_MOBILE_NUMBER',
 to=mobile_number
 )
 messagebox.showinfo('OTP Sent', f'OTP has been sent to {mobile_number}.')
 self.start_timer()
 self.send_otp_button.config(state=tk.DISABLED) 
 self.resend_otp_button.config(state=tk.DISABLED) 
 self.otp_entry.delete(0, tk.END)
def send_otp(self):
   if self.locked:
 messagebox.showinfo('Account Locked', 'Your account is locked. Try  again later.')
 return
 mobile_number = self.mobile_number_entry.get()
 if not mobile_number:
 messagebox.showerror('Error', 'Please enter your mobile number.')
 return

 self.otp = random.randint(1000, 9999)
 message = client.messages.create(
 body=f'Your OTP is {self.otp}.',
 from_='TWILIO_MOBILE_NUMBER',
 to=mobile_number
 )
 messagebox.showinfo('OTP Sent', f'OTP has been sent to {mobile_number}.')
 self.start_timer()
 self.send_otp_button.config(state=tk.DISABLED) 
 self.resend_otp_button.config(state=tk.DISABLED) 
 self.otp_entry.delete(0, tk.END)

定义一个方法resend_otp()。如果锁住,显示相应的消息。否则获取并验证电话号码,重新生成随机的OTP,重新发送OTP,显示消息框,启动计时器,并禁用重新发送OTP按钮。

def resend_otp(self):
 if self.locked:
 messagebox.showinfo('Account Locked', 'Your account is locked. Try  
again later.')
 return
 mobile_number = self.mobile_number_entry.get()
 if not mobile_number:
 messagebox.showerror('Error', 'Please enter your mobile number.')
 return

 self.otp = random.randint(1000, 9999)
 message = client.messages.create(
 body=f'Your OTP is {self.otp}.',
 from_='TWILIO_MOBILE_NUMBER',
 to=mobile_number
 )
 messagebox.showinfo('OTP Sent', f'New OTP has been sent to {mobile_number}.')
 self.start_timer()
 self.resend_otp_button.config(state=tk.DISABLED)

定义一个方法verify_otp()。获取OTP,并检查用户是否没有输入任何内容。如果存储的OTP为None,要求用户先生成OTP。如果用户输入的OTP与存储的OTP匹配,显示OTP验证成功,停止计时器,并退出程序。否则检查错误的输入尝试。如果输错次数超过3次,锁住账户。

def verify_otp(self):
 user_otp = self.otp_entry.get()
 if not user_otp:
 messagebox.showerror('Error', 'Please enter OTP.')
 return
 if self.otp is None:
 messagebox.showerror('Error', 'Please generate OTP first.')
 return
 if int(user_otp) == self.otp:
 messagebox.showinfo('Success', 'OTP verified successfully.')
 self.stop_timer = True 
 exit()
 else:
 self.wrong_attempts += 1
 if self.wrong_attempts == 3:
 self.lock_account()
 else:
 messagebox.showerror('Error', 'OTP does not match.')

定义一个方法lock_account()。设置锁住状态为true,显示标签为“账户已锁住”。禁用所有标签、条目和按钮。停止现有的计时器,启动新的计时器(10分钟)。

def lock_account(self):
 self.locked = True
 self.label1.config(text='Account Locked')
 self.mobile_number_entry.config(state=tk.DISABLED)
 self.send_otp_button.config(state=tk.DISABLED)
 self.timer_label.config(text='')
 self.resend_otp_button.config(state=tk.DISABLED)
 self.label2.config(text='')
 self.otp_entry.config(state=tk.DISABLED)
 self.verify_otp_button.config(state=tk.DISABLED)
 self.stop_timer = True 
 countdown_time = 10 * 60 
 self.start_countdown(countdown_time)

定义一个方法start_countdown()。如果剩余时间小于等于0,重置账户。否则显示程序已锁住账户,并在剩余时间内使用回调再试一次。

def start_countdown(self, remaining_time):
 if remaining_time <= 0:
 self.reset_account()
 return

 minutes = int(remaining_time // 60)
 seconds = int(remaining_time % 60)
 timer_label = f'Account Locked. Try again in: 
{minutes:02d}:{seconds:02d}'
 self.timer_label.config(text=timer_label)
 self.master.after(1000, self.start_countdown, remaining_time - 1)

定义一个函数reset_account()。像前面一样重置所有小组件和变量的状态。

def reset_account(self):
 self.locked = False
 self.wrong_attempts = 0
 self.label1.config(text='Enter your mobile number:')
 self.mobile_number_entry.config(state=tk.NORMAL)
 self.send_otp_button.config(state=tk.NORMAL)
 self.timer_label.config(text='')
 self.resend_otp_button.config(state=tk.DISABLED)
 self.label2.config(text='Enter OTP sent to your mobile:')
 self.otp_entry.config(state=tk.NORMAL)
 self.verify_otp_button.config(state=tk.NORMAL)
 self.stop_timer = False

创建根窗口和类的实例,并运行Tkinter应用程序。

if __name__ == '__main__':
 root = tk.Tk()
 otp_verification = OTPVerification(root)
 root.mainloop()

使用OTP验证的输出示例

在运行OTP验证程序时,您会看到一个窗口,要求输入手机号码。输入手机号码以及所在国家代号,然后点击“发送OTP”按钮。您会收到一条消息,表明程序已成功发送OTP,按钮会停用两分钟。检查手机是否收到了OTP,并在过期前输入它。

在计时器过期前输入正确的OTP后,您将收到一条消息,表明程序已成功验证了OTP,退出程序。如果您没有及时输入,会收到消息框,表明OTP已过期。可以点击“重新发送OTP”按钮以生成新的OTP,并发送到您的手机。

如果您输错了OTP,程序将显示一个消息框,表明“OTP不匹配”。

如果OTP输错三次,所有字段将被禁用,账户将被锁住十分钟。

结合使用Twilio与Python

使用Twilio,您可以为各种事件构建短信通知系统。您可以将其与物联网设备一起使用,当设备的数值高于或低于某个阈值或者检测到入侵者时发送短信。您还可以构建具有双因素身份验证的安全登录系统,构建WhatsApp聊天机器人和约会提醒系统。

除此之外,您还可以用它进行电话号码验证、营销活动、发送调查表和收集反馈。在构建任何应用程序时,始终留意Twilio API的定价,以免遭遇意外成本。

原文标题:How to Build an OTP Verification System Using Python,作者:Sai Ashish Konchada


相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...