Unlocking Secure Passcodes: A Python3 Script for One-Time Password Challenges
2 min readApr 16, 2024
Discover how to automate the generation of one-time passwords (OTPs) with Python.
The script simplifies the process of creating and displaying secure passcodes, ideal for enhancing authentication systems and bolstering cybersecurity measures. Dive into the world of OTP challenges and streamline your security protocols effortlessly within the command line environment.
#!/usr/bin/env python3
# Script to generate OTP through CLI
# Author: Ananda Raj
# Date: 16 Apr 2024
'''
Shows your OTP challenge
The first time the script will create a configuration file
'''
import platform
import subprocess
import time
import os
try:
import onetimepass as otp
except ImportError:
print("Please install onetimepass library: Try pip3 install onetimepass\n")
quit()
# Constants
# Replace the OTP secret file here. It should in a below format:
# cat ~/scripts/.otp-secret
#OTP SECRET
#otp_secret='asbcddfdfkadkjadjiusdhiquhdiqsdxxx'
OTP_CONFIG_PATH = os.path.join(os.environ['HOME'], 'scripts', '.otp-secret')
TIME_RANGES = range(3, 33, 3)
def check_otp_config():
"""Check if otp_secret is properly set"""
if not os.path.isfile(OTP_CONFIG_PATH):
with open(OTP_CONFIG_PATH, 'w') as f:
f.write("# OTP Secret\notp_secret = 'XXXXXXXXXXXXXX'\n")
print(f"Could not open {OTP_CONFIG_PATH}\nA sample file was created.\n"
"Please put your secret there")
quit(1)
def get_otp_secret():
"""Retrieve otp_secret from config file"""
otp_secret = None # Initialize otp_secret variable
with open(OTP_CONFIG_PATH) as f:
for line in f:
if line.startswith("otp_secret"):
otp_secret = line.split("=")[1].strip().strip("'")
return otp_secret
print("\nNo otp_secret found in the config file\n")
quit(1)
def show_otp(token, time_raise, time_decimal):
"""Display OTP token"""
print(token.decode())
def main():
"""Main function"""
check_otp_config()
otp_secret = get_otp_secret()
otp_token = otp.get_totp(otp_secret, as_string=True)
time_raise = 0
# We need to countdown the first cycle
time_decimal = int(time.strftime('%S'))
if time_decimal > 30:
time_decimal -= 30
if time_decimal:
time_decimal = 100 * time_decimal / 30
show_otp(otp_token, time_raise, time_decimal)
quit()
if __name__ == "__main__":
main()