PowerShell 使用 ssh 驗證本地與遠端檔案的 SHA256 是否一致
要驗證傳輸到底有沒有傳對用的函式
function Get-RemoteFileHash {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline)]
[string]$Path,
[Parameter(Mandatory)]
[string]$RemoteLoginInfo,
[Parameter(Mandatory)]
[string]$IdentityFile,
[Parameter(Mandatory)]
[ValidateSet('Windows', 'Linux')]
[string]$RemoteOS
) begin {
if (-not (Test-Path $IdentityFile)) {
Write-Error "Cannot find path '$IdentityFile' because it does not exist."
}
$hashCommands = @{
'Windows' = "powershell `"(Get-FileHash -Path ([WildcardPattern]::Escape('$Path')) -Algorithm SHA256 -EA 1).Hash`""
'Linux' = "sha256sum '$Path' 2>&1 >/dev/null && sha256sum '$Path' | cut -d' ' -f1 | tr '[:lower:]' '[:upper:]'"
}
$sshParams = @(
'-oBatchMode=yes'
"-oIdentityFile=$IdentityFile"
$RemoteLoginInfo
)
} process {
$hash = & ssh @sshParams $hashCommands[$RemoteOS] 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Error "ssh command failed: $hash"
return $null
}
if (-not ($hash -match '^[A-F0-9]{64}$')) {
Write-Error "The hash value '$hash' returned from command '$hashCommand' is not a valid SHA-256 format"
return $null
}
return $hash
}
}
使用範例
Get-RemoteFileHash "/home/chg/work/Tester.bats" `
-RemoteLoginInfo "chg@192.168.3.53" `
-IdentityFile "${env:USERPROFILE}\.ssh\id_ed25519" `
-RemoteOS "Linux"
執行完會自動返回遠端檔案的哈希值,再來比較本地端即可知道是否一致了。
如果是要從 sftp 指令獲取位址可以參考這個
function ParseSftpCommandPath {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)]
[string]$CommandText
)
process {
if (-not ($CommandText -match '\S') -or $CommandText -match '^\s*#') { return }
$tokens = [regex]::Matches(
$CommandText.Trim(), '"[^"]+"|[^\s"]+'
).Value.Trim('"')
if ($tokens[0] -in 'get','put') {
$paths = $tokens[1..($tokens.Count-1)].Where({ $_ -notmatch '^-' })
$idx = @{
'get' = @{local=-1; remote=0}
'put' = @{local=0; remote=-1}
}[$tokens[0]]
[PSCustomObject]@{
Command = $tokens[0]
LocalPath = $paths[$idx.local]
RemotePath = $paths[$idx.remote]
}
}
}
}