想省去重复输入密码的麻烦?这个自动登录脚本你会写吗?

wen 实用脚本 44

本文目录导读:

想省去重复输入密码的麻烦?这个自动登录脚本你会写吗?

  1. 基础版:文件存储的自动登录脚本
  2. 进阶版:浏览器保存密码的脚本
  3. 配置文件模板
  4. 安装依赖
  5. 注意事项
  6. 使用场景

我来分享一个实用的自动登录脚本,使用Python编写,通过保存和自动填充凭证来省去重复输入密码的麻烦。

基础版:文件存储的自动登录脚本

import json
import os
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from cryptography.fernet import Fernet
import base64
import getpass
class AutoLogin:
    def __init__(self, config_file='login_config.json'):
        self.config_file = config_file
        self.key_file = 'secret.key'
        self.load_or_create_key()
    def load_or_create_key(self):
        """加载或创建加密密钥"""
        if os.path.exists(self.key_file):
            with open(self.key_file, 'rb') as f:
                self.key = f.read()
        else:
            self.key = Fernet.generate_key()
            with open(self.key_file, 'wb') as f:
                f.write(self.key)
        self.cipher = Fernet(self.key)
    def encrypt_password(self, password):
        """加密密码"""
        return self.cipher.encrypt(password.encode()).decode()
    def decrypt_password(self, encrypted_password):
        """解密密码"""
        return self.cipher.decrypt(encrypted_password.encode()).decode()
    def save_credentials(self, url, username, password):
        """保存登录凭证"""
        credentials = {
            url: {
                'username': username,
                'password': self.encrypt_password(password)
            }
        }
        # 读取现有配置
        existing = {}
        if os.path.exists(self.config_file):
            with open(self.config_file, 'r') as f:
                existing = json.load(f)
        # 更新并保存
        existing.update(credentials)
        with open(self.config_file, 'w') as f:
            json.dump(existing, f, indent=2)
        print(f"✅ 登录凭证已保存到 {self.config_file}")
    def get_saved_credentials(self, url):
        """获取已保存的凭证"""
        if not os.path.exists(self.config_file):
            return None, None
        with open(self.config_file, 'r') as f:
            credentials = json.load(f)
        if url in credentials:
            username = credentials[url]['username']
            password = self.decrypt_password(credentials[url]['password'])
            return username, password
        return None, None
    def auto_login(self, url, username_field_id='username', 
                   password_field_id='password', login_button_id='login'):
        """自动登录"""
        # 获取保存的凭证
        saved_username, saved_password = self.get_saved_credentials(url)
        if saved_username and saved_password:
            print("🔑 找到已保存的登录凭证...")
            username = saved_username
            password = saved_password
        else:
            print("📝 未找到凭证,请手动输入...")
            # 获取用户输入
            username = input("请输入用户名/邮箱: ")
            password = getpass.getpass("请输入密码: ")
            # 询问是否保存
            save_choice = input("是否保存登录凭证?(y/n): ").lower()
            if save_choice == 'y':
                self.save_credentials(url, username, password)
        # 启动浏览器
        print("🚀 启动浏览器...")
        driver = webdriver.Chrome()  # 需要安装chromedriver
        driver.get(url)
        try:
            # 等待页面加载
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.ID, username_field_id))
            )
            # 填充表单
            username_field = driver.find_element(By.ID, username_field_id)
            password_field = driver.find_element(By.ID, password_field_id)
            username_field.clear()
            username_field.send_keys(username)
            password_field.clear()
            password_field.send_keys(password)
            # 点击登录按钮
            login_button = driver.find_element(By.ID, login_button_id)
            login_button.click()
            print("✅ 登录成功!")
            return driver
        except Exception as e:
            print(f"❌ 登录失败: {str(e)}")
            driver.quit()
            return None
# 使用示例
if __name__ == "__main__":
    # 创建自动登录实例
    auto_login = AutoLogin()
    # 登录示例
    driver = auto_login.auto_login(
        url="https://example.com/login",
        username_field_id="username",
        password_field_id="password",
        login_button_id="submit"
    )
    # 保持浏览器打开一段时间
    if driver:
        time.sleep(30)
        driver.quit()

进阶版:浏览器保存密码的脚本

import pickle
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class BrowserAutoLogin:
    def __init__(self):
        self.cookies_file = 'cookies.pkl'
        self.profile_path = os.path.join(os.getcwd(), 'chrome_profile')
    def create_driver_with_profile(self):
        """创建带有用户数据目录的浏览器"""
        chrome_options = Options()
        # 使用自定义用户数据目录
        if not os.path.exists(self.profile_path):
            os.makedirs(self.profile_path)
        chrome_options.add_argument(f'user-data-dir={self.profile_path}')
        chrome_options.add_argument('--disable-blink-features=AutomationControlled')
        return webdriver.Chrome(options=chrome_options)
    def save_cookies(self, driver, url):
        """保存cookies"""
        cookies = driver.get_cookies()
        with open(self.cookies_file, 'wb') as f:
            pickle.dump(cookies, f)
        print(f"💾 已保存 {len(cookies)} 个cookies")
    def load_cookies(self, driver, url):
        """加载cookies"""
        if not os.path.exists(self.cookies_file):
            return False
        with open(self.cookies_file, 'rb') as f:
            cookies = pickle.load(f)
        driver.get(url)
        for cookie in cookies:
            driver.add_cookie(cookie)
        driver.refresh()
        print(f"📋 已加载 {len(cookies)} 个cookies")
        return True
    def auto_login_with_cookies(self, url, login_url=None):
        """使用cookies自动登录"""
        driver = self.create_driver_with_profile()
        # 尝试加载已保存的cookies
        if self.load_cookies(driver, url):
            print("✅ 使用cookies自动登录成功!")
            return driver
        # 如果没有cookies,手动登录并保存
        if login_url:
            print("🔑 需要手动登录一次...")
            driver.get(login_url)
            input("请在浏览器中完成登录,然后按Enter键继续...")
            # 保存cookies
            self.save_cookies(driver, url)
            print("✅ Cookies已保存,下次将自动登录!")
            return driver
        else:
            print("❌ 未找到cookies且未提供登录URL")
            driver.quit()
            return None
# 使用示例
if __name__ == "__main__":
    # 使用浏览器自动登录
    auto_login = BrowserAutoLogin()
    # 自动登录
    driver = auto_login.auto_login_with_cookies(
        url="https://example.com/dashboard",
        login_url="https://example.com/login"
    )
    if driver:
        input("按Enter键退出...")
        driver.quit()

配置文件模板

{
    "https://example.com": {
        "username": "user@example.com",
        "password": "gAAAAABn..."  # 加密后的密码
    },
    "https://another-site.com": {
        "username": "another_user",
        "password": "gAAAAABm..."
    }
}

安装依赖

pip install selenium cryptography

注意事项

  1. 安全性:密码加密存储,主密钥在本地
  2. 兼容性:需要安装对应浏览器的WebDriver
  3. 隐私保护:建议定期更换主密钥
  4. 错误处理:添加了基本的异常处理

使用场景

  • 网站每天登录
  • 内部系统登录
  • 测试环境自动登录
  • 批量账号管理

这个脚本可以根据你的具体需求进行定制,比如添加GUI界面、支持多账号切换等功能。

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