怎么用脚本获取动态密码

wen 实用脚本 1

本文目录导读:

怎么用脚本获取动态密码

  1. 基于时间的一次性密码(TOTP)
  2. 华为/思科等设备的动态密码
  3. 从短信或邮箱提取验证码
  4. 生成随机动态密码(一次性使用)
  5. 命令行版本(使用脚本)
  6. 自动化刷新和通知
  7. 使用建议

我来介绍几种获取动态密码的脚本方法,主要针对常见的场景:

基于时间的一次性密码(TOTP)

import pyotp
import time
# 获取动态密码
def get_totp(secret_key):
    """
    获取基于时间的动态密码
    :param secret_key: 密钥(通常由服务商提供)
    :return: 6位动态密码
    """
    totp = pyotp.TOTP(secret_key)
    return totp.now()
# 示例:使用密钥生成密码
secret = "JBSWY3DPEHPK3PXP"  # 你的TOTP密钥
password = get_totp(secret)
print(f"当前动态密码: {password}")
# 每秒获取
while True:
    print(f"密码: {get_totp(secret)}")
    time.sleep(1)

华为/思科等设备的动态密码

import hmac
import hashlib
import base64
import time
def get_hotp(secret_key, counter):
    """
    HOTP(计数器型)动态密码
    """
    key = base64.b32decode(secret_key)
    msg = counter.to_bytes(8, 'big')
    h = hmac.new(key, msg, hashlib.sha1).digest()
    offset = h[-1] & 0x0F
    code = (h[offset] & 0x7F) << 24
    code |= (h[offset+1] & 0xFF) << 16
    code |= (h[offset+2] & 0xFF) << 8
    code |= (h[offset+3] & 0xFF)
    return code % 1000000  # 生成6位数密码
# 使用示例
secret = "JBSWY3DPEHPK3PXP"
counter = 12345
password = get_hotp(secret, counter)
print(f"HOTP密码: {password:06d}")

从短信或邮箱提取验证码

import re
import imaplib
import email
def extract_code_from_email(email_address, password, imap_server="imap.gmail.com"):
    """
    从邮箱中提取验证码
    """
    # 连接邮箱
    mail = imaplib.IMAP4_SSL(imap_server)
    mail.login(email_address, password)
    mail.select('inbox')
    # 搜索最近邮件
    status, messages = mail.search(None, 'ALL')
    # 获取最新邮件
    latest = messages[0].split()[-1]
    status, msg_data = mail.fetch(latest, '(RFC822)')
    # 解析邮件内容
    msg = email.message_from_bytes(msg_data[0][1])
    # 提取验证码
    for part in msg.walk():
        if part.get_content_type() == "text/plain":
            body = part.get_payload(decode=True).decode()
            # 用正则提取验证码
            code_pattern = r'\b[0-9]{6}\b'
            codes = re.findall(code_pattern, body)
            if codes:
                return codes[0]
    mail.logout()
    return None
# 使用示例
# code = extract_code_from_email("youremail@gmail.com", "password")
# print(f"获取的验证码: {code}")

生成随机动态密码(一次性使用)

import random
import string
def generate_dynamic_password(length=8, use_digits=True, use_special=True):
    """
    生成随机动态密码
    """
    chars = string.ascii_letters
    if use_digits:
        chars += string.digits
    if use_special:
        chars += string.special
    password = ''.join(random.choice(chars) for _ in range(length))
    return password
# 生成6位数字验证码
code = generate_dynamic_password(6, use_special=False)
print(f"验证码: {code}")

命令行版本(使用脚本)

#!/bin/bash
# get_otp.sh
SECRET_KEY="JBSWY3DPEHPK3PXP"
get_totp() {
    python3 -c "
import pyotp
import sys
totp = pyotp.TOTP('${SECRET_KEY}')
print(totp.now())
"
}
echo "当前动态密码: $(get_totp)"

自动化刷新和通知

import pyotp
import time
import subprocess
def auto_refresh_totp(secret_key, refresh_interval=30):
    """
    自动刷新动态密码并在终端显示
    """
    totp = pyotp.TOTP(secret_key)
    while True:
        current_time = int(time.time())
        time_remaining = 30 - (current_time % 30)
        # 清屏
        subprocess.run('clear' if os.name == 'posix' else 'cls', shell=True)
        print("=" * 40)
        print(f"动态密码: {totp.now()}")
        print(f"剩余时间: {time_remaining} 秒")
        print("=" * 40)
        time.sleep(1)
# 使用
# auto_refresh_totp("JBSWY3DPEHPK3PXP")

使用建议

  1. 安全性:不要在脚本中硬编码密钥,可以使用环境变量或加密存储
  2. 错误处理:添加异常处理机制
  3. 实时性:根据实际需求选择刷新频率
  4. 合规性:确保获取动态密码的方式符合平台使用条款

需要哪种类型更详细的代码?

抱歉,评论功能暂时关闭!