Skip to content

Instantly share code, notes, and snippets.

@Stef16Robbe
Last active October 19, 2023 13:31
Show Gist options
  • Save Stef16Robbe/77feb5dffc8b223baa0612f40d6c4799 to your computer and use it in GitHub Desktop.
Save Stef16Robbe/77feb5dffc8b223baa0612f40d6c4799 to your computer and use it in GitHub Desktop.
Automated Windows to Windows SSH copy-id
# UPDATE, VIEW: https://code.visualstudio.com/docs/remote/troubleshooting#_configuring-key-based-authentication
# SSH copy-id is not existent in win32 openssh (https://github.com/PowerShell/Win32-OpenSSH)
# So we need to do it ourselves.
# literally all I could find on Google was Windows to Unix:
# - https://www.chrisjhart.com/Windows-10-ssh-copy-id/
# - https://stackoverflow.com/a/9971617/10503012 ('cat source | ssh user@host "cat >> /path/to/target"' --> the 'cat >> ' part does not work on Windows, the variable is not properly piped through
# I do not have enough experience on (Windows) piping to fix this in a proper way.
# Special shoutout to useless Stack answers:
# - https://stackoverflow.com/questions/65656813/copying-ssh-key-from-windows-machine-to-windows-server-2019
# - https://stackoverflow.com/a/67541732/10503012
# So here we go, it's disgusting, uses `Invoke-Expression` but it works:
function Copy-SSHKey {
param(
[Parameter(Position=0)]
[string] $RemoteName,
[Parameter(Position=1)]
[string] $RemoteIp
)
$address = -join($RemoteName, "@", $RemoteIp)
$key = Get-Content $env:USERPROFILE\.ssh\id_ed25519.pub
$dir = -join('C:\Users\', $RemoteName, '\.ssh\authorized_keys')
$cmd1 = 'ssh.exe ' + $address
$cmd2 = [string]::Format("'echo $key >> {0}'", $dir)
$expr = -join($cmd1, " ", $cmd2)
Invoke-Expression $expr
# Results in following expression being executed:
# ssh.exe {RemoteName}@{RemoteIp} 'echo {key} >> C:\Users\{Remotename}\.ssh\authorized_keys'
# This solution also APPENDS to authorized_keys instead of overwriting, which I saw in some solutions
# Obvious code cleanup appreciated...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment