怎么用脚本管理密码

wen 实用脚本 1

本文目录导读:

怎么用脚本管理密码

  1. 基础脚本方案(简单实用)
  2. Python 密码管理脚本
  3. 命令行工具方案(功能丰富)
  4. 进阶方案(安全增强)
  5. 自动化密码轮换
  6. 推荐的使用建议

我来介绍几种用脚本管理密码的方法,从简单到复杂:

基础脚本方案(简单实用)

Bash + GPG 加密

#!/bin/bash
# 密码管理器
PASS_DIR="$HOME/.passwords"
mkdir -p "$PASS_DIR"
# 添加密码
pass_add() {
    read -sp "输入密码: " pass
    echo "$pass" | gpg -c > "$PASS_DIR/$1.gpg"
}
# 获取密码
pass_get() {
    gpg -d "$PASS_DIR/$1.gpg" 2>/dev/null
}
# 使用示例
case "$1" in
    add) pass_add $2 ;;
    get) pass_get $2 ;;
    list) ls "$PASS_DIR" ;;
esac

Python 密码管理脚本

简单版本(SQLite + 加密)

#!/usr/bin/env python3
import sqlite3
import getpass
from cryptography.fernet import Fernet
import base64
import hashlib
import os
class PasswordManager:
    def __init__(self, db_path='~/.pm.db'):
        self.db_path = os.path.expanduser(db_path)
        self.init_db()
    def init_db(self):
        conn = sqlite3.connect(self.db_path)
        conn.execute('''CREATE TABLE IF NOT EXISTS passwords
                       (service TEXT PRIMARY KEY, 
                        username TEXT,
                        encrypted_pass TEXT)''')
        conn.close()
    def get_key(self, master_pass):
        return base64.urlsafe_b64encode(
            hashlib.sha256(master_pass.encode()).digest()
        )
    def add_password(self, service, username, password, master):
        key = self.get_key(master)
        f = Fernet(key)
        enc_pass = f.encrypt(password.encode()).decode()
        conn = sqlite3.connect(self.db_path)
        conn.execute("INSERT OR REPLACE INTO passwords VALUES (?,?,?)",
                    (service, username, enc_pass))
        conn.commit()
        conn.close()
    def get_password(self, service, master):
        key = self.get_key(master)
        f = Fernet(key)
        conn = sqlite3.connect(self.db_path)
        row = conn.execute("SELECT * FROM passwords WHERE service=?",
                          (service,)).fetchone()
        conn.close()
        if row:
            dec_pass = f.decrypt(row[2].encode()).decode()
            return row[1], dec_pass
        return None

命令行工具方案(功能丰富)

使用 pass(标准工具)

# 安装 pass
sudo apt install pass   # Ubuntu/Debian
brew install pass       # macOS
# 初始化
pass init your-gpg-key-id
# 常用命令
pass insert email/gmail        # 添加密码
pass show email/gmail          # 查看密码
pass generate website/example  # 生成随机密码
pass edit email/gmail          # 编辑密码
pass rm email/gmail            # 删除密码
pass ls                        # 列出所有密码

自定义 Python CLI

#!/usr/bin/env python3
# simple-pass.py
import argparse
import json
import os
import secrets
import string
from getpass import getpass
class SimplePassManager:
    def __init__(self):
        self.data_file = os.path.expanduser("~/.simple_pass.json")
        self.data = self.load_data()
    def load_data(self):
        if os.path.exists(self.data_file):
            with open(self.data_file, 'r') as f:
                return json.load(f)
        return {}
    def save_data(self):
        with open(self.data_file, 'w') as f:
            json.dump(self.data, f, indent=2)
    def add(self, service, username, password):
        self.data[service] = {
            'username': username,
            'password': password
        }
        self.save_data()
    def get(self, service):
        return self.data.get(service, None)
    def generate(self, length=16):
        chars = string.ascii_letters + string.digits + "!@#$%^&*"
        return ''.join(secrets.choice(chars) for _ in range(length))
def main():
    parser = argparse.ArgumentParser(description='简单密码管理器')
    parser.add_argument('action', choices=['add', 'get', 'gen', 'list'])
    parser.add_argument('arg', nargs='?', help='服务名')
    parser.add_argument('-l', '--length', type=int, default=16, help='密码长度')
    args = parser.parse_args()
    pm = SimplePassManager()
    if args.action == 'add':
        service = input("服务名: ")
        username = input("用户名: ")
        password = getpass("密码: ")
        pm.add(service, username, password)
        print(f"已保存 {service}")
    elif args.action == 'get':
        data = pm.get(args.arg)
        if data:
            print(f"服务: {args.arg}")
            print(f"用户名: {data['username']}")
            print(f"密码: {data['password']}")
        else:
            print(f"未找到 {args.arg}")
    elif args.action == 'gen':
        gen_pwd = pm.generate(args.length)
        print(f"生成的密码: {gen_pwd}")
    elif args.action == 'list':
        for service in pm.data:
            print(f"- {service}")
if __name__ == "__main__":
    main()

进阶方案(安全增强)

结合 KeepassXC 命令行

#!/bin/bash
# 通过 keepassxc-cli 管理密码
KDBX_FILE="$HOME/Passwords.kdbx"
# 添加密码
kp_add() {
    echo "服务: " ; read service
    echo "用户名: " ; read username
    read -sp "密码: " password
    echo
    keepassxc-cli add -u "$username" "$KDBX_FILE" "$service" <<< "$password"
}
# 获取密码复制到剪贴板
kp_get() {
    keepassxc-cli show -q -a Password "$KDBX_FILE" "$1" | xclip -selection clipboard
    echo "已复制到剪贴板"
}
# 生成强密码
kp_gen() {
    keepassxc-cli generate -l 20 --lower --upper --numeric --special
}

自动化密码轮换

#!/usr/bin/env python3
# 自动轮换密码
import subprocess
import secrets
import string
from datetime import datetime
def generate_strong_password(length=20):
    alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
    while True:
        password = ''.join(secrets.choice(alphabet) for _ in range(length))
        if (any(c.islower() for c in password) and
            any(c.isupper() for c in password) and
            any(c.isdigit() for c in password) and
            any(c in "!@#$%^&*" for c in password)):
            return password
def rotate_passwords(services):
    """定时轮换密码"""
    for service in services:
        new_pass = generate_strong_password()
        # 更新到密码管理器
        subprocess.run(['pass', 'insert', '-f', service], 
                      input=new_pass, text=True)
        # 记录日志
        with open('rotation.log', 'a') as f:
            f.write(f"{datetime.now()}: {service} 密码已轮换\n")
        print(f"✓ {service} 密码已更新")

推荐的使用建议

日常使用流程

# 在 ~/.bashrc 添加别名
echo 'alias pm="python3 ~/scripts/pass_manager.py"' >> ~/.bashrc
echo 'alias ps="pass show"' >> ~/.bashrc
source ~/.bashrc
# 使用示例
pm add           # 添加新密码
pm get github    # 获取github密码
pm gen 32        # 生成32位随机密码

安全提醒

  1. 主密码要强:建议20+位,混合大小写字母、数字、特殊字符
  2. 定期备份数据库文件
  3. 不要明文存储敏感信息
  4. 使用密钥文件替代密码输入
  5. 多因素认证配合使用

定时任务示例

# crontab 每周自动备份
0 2 * * 0 tar -czf ~/backup/passwords_$(date +%Y%m%d).tar.gz ~/.passwords
# 每90天提醒更换密码
0 9 * * * if [ $(( ($(date +%s) - $(stat -c %Y ~/.last_rotated)) / 86400 )) -gt 90 ]; then notify-send "密码需要轮换了"; fi

选择哪种方案取决于你的需求:

  • 简单实用:Bash + GPG
  • 功能完整:Python 脚本 + SQLite
  • 标准方案:使用 pass 或 KeepassXC
  • 企业级:Vault 或 Kubernetes Secrets

建议从简单的开始,根据需求逐步增强,记得做好备份和加密!

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