本文目录导读:

我来教你编写一个自动备份无线密码的脚本。
Windows 系统(PowerShell 脚本)
# WiFi密码备份脚本 - Windows版本
# 保存为 Backup-WiFi.ps1
# 设置备份目录
$backupDir = "$env:USERPROFILE\Desktop\WiFiBackup"
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$backupFile = "$backupDir\WiFiPasswords_$timestamp.txt"
# 创建备份目录
if (!(Test-Path $backupDir)) {
New-Item -ItemType Directory -Path $backupDir
}
# 获取所有WiFi配置文件
Write-Host "正在获取WiFi配置..." -ForegroundColor Green
$profiles = netsh wlan show profiles | Select-String "所有用户配置文件" | ForEach-Object {
$_ -replace ".*:\s+", ""
}
# 导出密码到文件
$results = @()
foreach ($profile in $profiles) {
try {
# 获取WiFi密码
$passwordInfo = netsh wlan show profile name="$profile" key=clear
$password = $passwordInfo | Select-String "关键内容" | ForEach-Object {
$_ -replace ".*:\s+", ""
}
if ($password) {
$results += "SSID: $profile"
$results += "密码: $password"
$results += "------------------------"
}
} catch {
Write-Host "获取 $profile 的密码失败" -ForegroundColor Red
}
}
# 保存到文件
$results | Out-File -FilePath $backupFile -Encoding UTF8
Write-Host "备份完成!文件保存在: $backupFile" -ForegroundColor Green
Linux 系统(Bash 脚本)
#!/bin/bash
# WiFi密码备份脚本 - Linux版本
# 保存为 backup_wifi.sh
# 设置备份文件路径
BACKUP_DIR="$HOME/wifi_backup"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="$BACKUP_DIR/wifi_passwords_$TIMESTAMP.txt"
# 创建备份目录
mkdir -p "$BACKUP_DIR"
echo "正在备份WiFi密码..."
# 检查操作系统类型
if [ -f "/etc/NetworkManager/system-connections/" ]; then
# 使用 NetworkManager 的系统(Ubuntu/Debian/Fedora等)
for file in /etc/NetworkManager/system-connections/*; do
if [ -f "$file" ]; then
ssid=$(basename "$file")
password=$(sudo cat "$file" | grep "psk=" | cut -d'=' -f2)
echo "SSID: $ssid" >> "$BACKUP_FILE"
echo "密码: $password" >> "$BACKUP_FILE"
echo "------------------------" >> "$BACKUP_FILE"
fi
done
else
# 使用 wpa_supplicant 的系统
if [ -f "/etc/wpa_supplicant/wpa_supplicant.conf" ]; then
sudo cat "/etc/wpa_supplicant/wpa_supplicant.conf" >> "$BACKUP_FILE"
echo "" >> "$BACKUP_FILE"
fi
fi
# 设置权限
chmod 600 "$BACKUP_FILE"
echo "备份完成!文件保存在: $BACKUP_FILE"
跨平台 Python 脚本
#!/usr/bin/env python3
# WiFi密码备份脚本 - 跨平台版本
# 保存为 backup_wifi.py
import os
import platform
import subprocess
import json
from datetime import datetime
class WiFiBackup:
def __init__(self):
self.backup_dir = os.path.join(os.path.expanduser("~"), "wifi_backup")
self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
self.backup_file = os.path.join(self.backup_dir, f"wifi_passwords_{self.timestamp}.txt")
# 创建备份目录
os.makedirs(self.backup_dir, exist_ok=True)
def backup_windows(self):
"""Windows系统备份"""
results = []
# 获取所有WiFi配置
output = subprocess.check_output("netsh wlan show profiles", shell=True, text=True)
profiles = [line.split(":")[1].strip() for line in output.split("\n") if "所有用户配置文件" in line]
for profile in profiles:
try:
# 获取密码
cmd = f'netsh wlan show profile name="{profile}" key=clear'
output = subprocess.check_output(cmd, shell=True, text=True)
for line in output.split("\n"):
if "关键内容" in line:
password = line.split(":")[1].strip()
results.append(f"SSID: {profile}")
results.append(f"密码: {password}")
results.append("-" * 30)
except:
print(f"获取 {profile} 密码失败")
return results
def backup_linux(self):
"""Linux系统备份"""
results = []
# 尝试不同的配置路径
paths = [
"/etc/NetworkManager/system-connections/",
"/etc/wpa_supplicant/"
]
for path in paths:
if os.path.exists(path):
if "NetworkManager" in path:
for file in os.listdir(path):
filepath = os.path.join(path, file)
if os.path.isfile(filepath):
try:
with open(filepath, 'r') as f:
content = f.read()
# 提取密码
for line in content.split("\n"):
if "psk=" in line and "identity" not in line:
password = line.split("=")[1]
results.append(f"SSID: {file}")
results.append(f"密码: {password}")
results.append("-" * 30)
except:
print(f"读取 {file} 失败")
return results
def run_backup(self):
"""执行备份"""
system = platform.system()
print(f"检测到操作系统: {system}")
results = []
if system == "Windows":
results = self.backup_windows()
elif system == "Linux":
results = self.backup_linux()
else:
print(f"不支持的操作系统: {system}")
return
# 保存到文件
with open(self.backup_file, 'w', encoding='utf-8') as f:
f.write(f"WiFi密码备份 - {self.timestamp}\n")
f.write("=" * 30 + "\n\n")
f.write("\n".join(results))
print(f"备份完成!文件保存在: {self.backup_file}")
# 设置文件权限
os.chmod(self.backup_file, 0o600) # 仅所有者可读写
if __name__ == "__main__":
backup = WiFiBackup()
backup.run_backup()
使用说明
Windows 脚本使用:
# 以管理员身份运行 PowerShell # 执行脚本 .\Backup-WiFi.ps1
Linux 脚本使用:
# 给脚本添加执行权限 chmod +x backup_wifi.sh # 以 sudo 运行(需要读取系统配置文件) sudo ./backup_wifi.sh
Python 脚本使用:
# 安装依赖(如果需要) pip install -r requirements.txt # 运行脚本 python backup_wifi.py
自动定时备份
Windows 任务计划程序:
# 创建每日备份任务 $action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\Backup-WiFi.ps1" $trigger = New-ScheduledTaskTrigger -Daily -At "03:00AM" Register-ScheduledTask -TaskName "WiFiBackup" -Action $action -Trigger $trigger -RunLevel Highest
Linux crontab:
# 编辑 crontab crontab -e # 添加定时任务(每天凌晨3点执行) 0 3 * * * /path/to/backup_wifi.sh
注意事项
- 权限问题:读取WiFi密码需要管理员/root权限
- 安全存储:建议将备份文件加密保存
- 隐私保护:妥善保管备份文件,不要随意分享
需要我详细解释某个特定功能或添加其他特性吗?