Skip to content

Instantly share code, notes, and snippets.

@frabarz
Last active September 16, 2019 15:23
Show Gist options
  • Save frabarz/008357e2af08c785cd424a28b4f20bac to your computer and use it in GitHub Desktop.
Save frabarz/008357e2af08c785cd424a28b4f20bac to your computer and use it in GitHub Desktop.
Loads SSH Agent on Windows so you have to input a passphrase only once.

For PowerShell on Windows 10.

When starting a new PowerShell terminal for the first time in a session, this function inits and loads an instance of the SSH Agent. On subsequent terminals, the script loads the info for the same instance previously created, so you don't have to input the passphrase on each window.

To persist the SSH Agent PID for the session, it uses the Volatile Environment registry key for the current logged in user. I'm not sure how safe this is, so don't use this script on a shared computer.

This script presumes the ssh-agent command is available on your $env:PATH, otherwise you can add the full path to the executable on line 8.

function Load-SSHAgent {
$registryPath = "HKCU:\Volatile Environment"
$registryItem = Get-ItemProperty -Path $registryPath
if ( !$registryItem.SSH_AGENT_PID ) {
Write-Host "Initiating a new SSH Agent instance"
[string]$output = ssh-agent
$lines = $output.Replace("/", "\").Replace("\tmp", $env:TEMP).Split(";")
$dict = @{}
foreach ($line in $lines) {
if (([string]$line).Trim() -match "(.+)=(.*)") {
$dict[$matches[1]] = $matches[2]
}
}
New-ItemProperty -Path $registryPath -Name "SSH_AGENT_PID" -Value $dict["SSH_AGENT_PID"] -PropertyType DWORD -Force | Out-Null
New-ItemProperty -Path $registryPath -Name "SSH_AUTH_SOCK" -Value $dict["SSH_AUTH_SOCK"] -PropertyType STRING -Force | Out-Null
[Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $dict["SSH_AGENT_PID"], "User")
[Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $dict["SSH_AUTH_SOCK"], "User")
}
$env:SSH_AGENT_PID = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "User")
$env:SSH_AUTH_SOCK = [Environment]::GetEnvironmentVariable("SSH_AUTH_SOCK", "User")
}
Load-SSHAgent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment