You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python 3.6开发命令行密码生成工具遇瓶颈求指导

Guidance for Your Python Password Generator CLI

Great start setting up the mutually exclusive modes with argparse! Let’s break down the next steps to turn this skeleton into a functional tool, tailored to Python 3.6.

1. Capture and Act on Parsed Arguments

Right now you’re parsing arguments but not using them. First, store the parsed args and branch your logic based on which mode the user selects. Add this after your existing parser code:

args = parser.parse_args()

if args.a:
    generate_auto_password()
elif args.m:
    generate_manual_password(args)
else:
    # Force the user to pick a mode by making the group required (see step 3)
    parser.print_help()

2. Build the Auto Mode Logic

Auto mode should generate a secure password with sensible defaults (e.g., 12 characters, mix of uppercase, lowercase, digits, and symbols). Here’s a robust implementation:

import random
import string

def generate_auto_password(length=12):
    # Define character sets
    lowercase = string.ascii_lowercase
    uppercase = string.ascii_uppercase
    digits = string.digits
    symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?"
    
    # Ensure at least one character from each category (for complexity)
    password = [
        random.choice(lowercase),
        random.choice(uppercase),
        random.choice(digits),
        random.choice(symbols)
    ]
    
    # Fill the rest with random characters from all sets
    password += random.choices(lowercase + uppercase + digits + symbols, k=length-4)
    
    # Shuffle to avoid predictable order
    random.shuffle(password)
    
    # Output the final password
    print("Generated password:", ''.join(password))

3. Enhance Manual Mode with Customizable Options

For manual mode, let users tweak password length and exclude character types. Update your parser to add these optional arguments (they’ll only matter when -m is used):

parser = argparse.ArgumentParser(description="Generate secure passwords")
# Make mode selection required so users can't run the tool without choosing
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-a", "--auto", help="Generate password with default settings", action="store_true")
group.add_argument("-m", "--manual", help="Customize password generation", action="store_true")

# Manual mode-specific options
parser.add_argument("--length", type=int, default=12, help="Password length (default: 12)")
parser.add_argument("--no-uppercase", action="store_true", help="Exclude uppercase letters")
parser.add_argument("--no-lowercase", action="store_true", help="Exclude lowercase letters")
parser.add_argument("--no-digits", action="store_true", help="Exclude numbers")
parser.add_argument("--no-symbols", action="store_true", help="Exclude special characters")

Then implement the manual mode function to respect these choices:

def generate_manual_password(args):
    # Build the character set based on user preferences
    allowed_chars = ""
    if not args.no_lowercase:
        allowed_chars += string.ascii_lowercase
    if not args.no_uppercase:
        allowed_chars += string.ascii_uppercase
    if not args.no_digits:
        allowed_chars += string.digits
    if not args.no_symbols:
        allowed_chars += "!@#$%^&*()_+-=[]{}|;:,.<>?"
    
    # Add error handling for invalid inputs
    if args.length < 1:
        print("Error: Password length must be at least 1!")
        return
    if not allowed_chars:
        print("Error: You must include at least one character type!")
        return
    
    # Generate and print the password
    password = ''.join(random.choices(allowed_chars, k=args.length))
    print("Generated password:", password)

4. Test the Tool

Try these commands to validate your work:

  • Auto mode: python password_gen.py -a
  • Manual mode (16 characters, no symbols): python password_gen.py -m --length 16 --no-symbols

Optional Improvements

  • Add a flag to save the password to a file (with proper permissions)
  • Let users specify custom symbols in manual mode
  • Add password strength feedback (e.g., "This password is very secure")

内容的提问来源于stack exchange,提问作者Jason 'Slingshot' Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:01:18