The Ops Community ⚙️

Kai Walter
Kai Walter

Posted on • Edited on

Remove entries from known_hosts with PowerShell

This small snippet I use to remove entries from $HOME\.ssh\known_hosts with PowerShell. I use this in cases when I redeploy an VM in the cloud and want to "ssh" into the VM, e.g. with a script, right after deployment is concluded. I know there is the ssh -o StrictHostKeyChecking=no option, but this is not how I roll.

disclaimer: tested on Windows with CR/LF and LF line endings; Linux and macOS needs to be validated

[CmdletBinding()]
param (
    [Parameter(Position = 1, Mandatory = $true)]
    [string]
    $ComputerName
)

$knownhosts = Join-Path $HOME ".ssh" "known_hosts"

if (Test-Path $knownhosts -PathType Leaf) {

    $contents = Get-Content $knownhosts -Raw

    if ($contents) {

        if ($contents -match "^[^\n]+\r\n") {
            $splitter = "\r\n"
            $joiner = "`r`n"
        }
        else {
            $splitter = "\n"
            $joiner = "`n"
        }

        $listIn = [regex]::Split($contents, $splitter ) | Where-Object { $_ -ne "" }
        $listOut = $listIn | Select-String $("^(?!$computerName)") -List

        if ($listOut.Count -ne $listIn.Count) {
            Write-Host "removed" $($listIn.Count - $listOut.Count) "lines"
            $listOut -join $joiner | Set-Content $knownhosts -NoNewline
        }
    }
    else {
        throw "file $knownhosts has no content"
    }

}
else {
    throw "file $knownhosts not found"
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
patrick_londa profile image
Patrick Londa

Thanks for sharing this code, @kaiwalter!