Резервные копии

Бэкап SSH-ключей

Копирует каталог .ssh в защищённую папку с ограниченными правами и manifest.

PowerShell Windows Продвинутый
Скачать Backup-SshKeys.ps1
Описание

Что делает скрипт

Скрипт проверяет пути, создаёт новый каталог и снимает наследование ACL, оставляя доступ только текущему пользователю. Файлы копируются без изменения, для каждого считается SHA-256. Приватные ключи не выводятся в консоль.

Перед запуском
  • В копии лежат приватные ключи, храните её в шифрованном месте.
Запуск

Быстрый старт

powershell -File Backup-SshKeys.ps1 -Destination E:\Backup\Ssh

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.

Примеры

Другие варианты

  • powershell -File Backup-SshKeys.ps1 -Destination E:\Backup\Ssh
  • powershell -File Backup-SshKeys.ps1 -Source C:\Users\user\.ssh -Destination E:\Backup\Ssh
Зависимости

Что понадобится

PowerShell 5.1+ В Windows 10 и 11 уже есть PowerShell 5.1
Windows Встроен в Windows 10/11 (PowerShell 5.1)
Исходник

Backup-SshKeys.ps1

[CmdletBinding(SupportsShouldProcess = $true)]
param(
    [string]$Source = (Join-Path $env:USERPROFILE '.ssh'),
    [Parameter(Mandatory = $true)]
    [string]$Destination
)

$ErrorActionPreference = 'Stop'
$sourceFull = [System.IO.Path]::GetFullPath($Source)
$destFull = [System.IO.Path]::GetFullPath($Destination)
$trimChars = [char[]]@('\', '/')

if (-not (Test-Path -LiteralPath $sourceFull -PathType Container)) {
    throw "SSH folder not found: $sourceFull"
}
if ($destFull.TrimEnd($trimChars) -eq $sourceFull.TrimEnd($trimChars)) {
    throw 'Source and Destination must differ.'
}
if ($destFull.StartsWith($sourceFull.TrimEnd($trimChars) + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
    throw 'Destination must not be inside Source.'
}
if ($sourceFull.StartsWith($destFull.TrimEnd($trimChars) + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
    throw 'Source must not be inside Destination.'
}

$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$targetRoot = Join-Path $destFull ('ssh-keys-' + $stamp)
if (Test-Path -LiteralPath $targetRoot) {
    throw "Destination already exists: $targetRoot"
}
if (-not $PSCmdlet.ShouldProcess($targetRoot, 'Backup SSH keys')) {
    return
}

New-Item -ItemType Directory -Path $targetRoot -Force | Out-Null
try {
    $acl = New-Object System.Security.AccessControl.DirectorySecurity
    $acl.SetAccessRuleProtection($true, $false)
    $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
    $rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
        $identity,
        'FullControl',
        'ContainerInherit,ObjectInherit',
        'None',
        'Allow'
    )
    $acl.AddAccessRule($rule)
    Set-Acl -LiteralPath $targetRoot -AclObject $acl
} catch {
    Write-Warning "Could not restrict ACL: $($_.Exception.Message)"
}

$files = Get-ChildItem -LiteralPath $sourceFull -Recurse -File -Force -ErrorAction SilentlyContinue |
    Where-Object { -not ($_.Attributes -band [System.IO.FileAttributes]::ReparsePoint) }
$manifest = New-Object System.Collections.Generic.List[object]
foreach ($file in $files) {
    $relative = $file.FullName.Substring($sourceFull.TrimEnd($trimChars).Length).TrimStart($trimChars)
    $target = Join-Path $targetRoot $relative
    $parent = Split-Path -Parent $target
    if (-not (Test-Path -LiteralPath $parent -PathType Container)) {
        New-Item -ItemType Directory -Path $parent -Force | Out-Null
    }
    Copy-Item -LiteralPath $file.FullName -Destination $target -Force
    $manifest.Add([pscustomobject]@{
        Name = $relative
        Length = $file.Length
        SHA256 = (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash
    })
}

$manifestPath = Join-Path $targetRoot 'manifest.csv'
if ($manifest.Count -gt 0) {
    $manifest | Export-Csv -LiteralPath $manifestPath -NoTypeInformation -Encoding UTF8
} else {
    Set-Content -LiteralPath $manifestPath -Value 'Name,Length,SHA256' -Encoding UTF8
}
Write-Warning 'Backup contains private keys. Keep it encrypted and offline.'
Write-Host "Files: $($manifest.Count)"
Write-Host "Folder: $targetRoot"

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get backup-ssh-keys
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Резервные копии

Резервное копирование, синхронизация, проверка и восстановление данных.