flnxi-Wu/secure_ssh.ps1
WuYongJie f646b71813
Some checks failed
CI Check / check (push) Has been cancelled
chore: 初始化本地仓库并同步最近改动
2025-11-18 17:50:16 +08:00

128 lines
4.8 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 安全SSH密钥自动登录脚本
param(
[string]$Server = "45.249.208.118",
[string]$Username = "root",
[string]$KeyPath = "$env:USERPROFILE\.ssh\id_rsa",
[string]$Command = "pwd",
[switch]$GenerateKey
)
Write-Host "=== 安全SSH密钥自动登录工具 ===" -ForegroundColor Cyan
# 检查是否需要生成密钥
if ($GenerateKey) {
Write-Host "🔑 正在生成SSH密钥对..." -ForegroundColor Yellow
# 确保.ssh目录存在
$sshDir = "$env:USERPROFILE\.ssh"
if (-not (Test-Path $sshDir)) {
New-Item -ItemType Directory -Path $sshDir -Force | Out-Null
Write-Host "✓ 创建.ssh目录: $sshDir" -ForegroundColor Green
}
# 生成密钥(如果不存在)
if (-not (Test-Path $KeyPath)) {
Write-Host "生成新的ED25519密钥..." -ForegroundColor Yellow
& ssh-keygen -t ed25519 -f $KeyPath -N "" -C "auto-login-$(Get-Date -Format 'yyyyMMdd')" 2>&1 | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-Host "✅ SSH密钥生成成功!" -ForegroundColor Green
Write-Host "私钥位置: $KeyPath" -ForegroundColor Cyan
Write-Host "公钥位置: $KeyPath.pub" -ForegroundColor Cyan
} else {
Write-Host "❌ SSH密钥生成失败" -ForegroundColor Red
exit 1
}
} else {
Write-Host "✓ 密钥已存在: $KeyPath" -ForegroundColor Green
}
# 显示公钥内容
$pubKeyPath = "$KeyPath.pub"
if (Test-Path $pubKeyPath) {
Write-Host "`n📋 请将以下公钥添加到服务器 ~/.ssh/authorized_keys:" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Gray
Get-Content $pubKeyPath -Raw
Write-Host "========================================" -ForegroundColor Gray
Write-Host "复制上面的公钥,添加到服务器的 ~/.ssh/authorized_keys 文件中" -ForegroundColor Cyan
}
exit 0
}
# 检查密钥文件是否存在
if (-not (Test-Path $KeyPath)) {
Write-Host "❌ 私钥文件不存在: $KeyPath" -ForegroundColor Red
Write-Host "请运行: .\secure_ssh.ps1 -GenerateKey" -ForegroundColor Yellow
Write-Host "或者修改KeyPath参数指向您的私钥文件" -ForegroundColor Gray
exit 1
}
# 检查私钥权限(Windows上使用icacls)
try {
$acl = Get-Acl $KeyPath
$currentUser = "$env:USERDOMAIN\$env:USERNAME"
$hasAccess = $acl.Access | Where-Object { $_.IdentityReference -eq $currentUser }
if (-not $hasAccess) {
Write-Host "⚠ 建议设置私钥权限为仅当前用户可访问" -ForegroundColor Yellow
icacls $KeyPath /inheritance:r /grant:r "$currentUser`:F" | Out-Null
Write-Host "✓ 私钥权限已优化" -ForegroundColor Green
}
} catch {
Write-Host "⚠ 无法检查私钥权限: $($_.Exception.Message)" -ForegroundColor Yellow
}
# 测试SSH连接
Write-Host "🔐 使用密钥进行SSH连接..." -ForegroundColor Yellow
Write-Host "服务器: $Server" -ForegroundColor Gray
Write-Host "用户名: $Username" -ForegroundColor Gray
Write-Host "私钥: $KeyPath" -ForegroundColor Gray
Write-Host "命令: $Command" -ForegroundColor Gray
# 使用ssh执行命令(自动接受主机密钥)
$sshArgs = @(
"-i", $KeyPath,
"-o", "StrictHostKeyChecking=auto", # 自动接受未知主机
"-o", "UserKnownHostsFile=NUL", # 不保存主机密钥
"$Username@$Server",
$Command
)
try {
Write-Host "🚀 正在执行命令..." -ForegroundColor Yellow
$output = & ssh @sshArgs 2>&1
$exitCode = $LASTEXITCODE
Write-Host "📤 命令输出:" -ForegroundColor Cyan
if ($output) {
$output | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
}
if ($exitCode -eq 0) {
Write-Host "✅ SSH命令执行成功!" -ForegroundColor Green
} else {
Write-Host "❌ SSH命令执行失败,退出码: $exitCode" -ForegroundColor Red
# 显示错误信息
$errorLines = $output | Where-Object { $_ -match "(error|Error|ERROR|failed|Failed|FAILED)" }
if ($errorLines) {
Write-Host "🔍 错误详情:" -ForegroundColor Yellow
$errorLines | ForEach-Object { Write-Host " $_" -ForegroundColor Red }
}
}
} catch {
Write-Host "❌ SSH执行异常: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}
Write-Host "`n=== 安全SSH自动登录完成 ===" -ForegroundColor Green
# 提供安全提示
Write-Host "`n💡 安全建议:" -ForegroundColor Cyan
Write-Host " 1. 定期更换SSH密钥对" -ForegroundColor Gray
Write-Host " 2. 为私钥设置密码短语" -ForegroundColor Gray
Write-Host " 3. 限制SSH密钥的使用范围" -ForegroundColor Gray
Write-Host " 4. 监控SSH登录日志" -ForegroundColor Gray