Skip to main content
  1. Posts/

ssh-copy-id for Windows (Powershell)

·993 words·5 mins· loading · loading ·
Sysadmin Windows Powershell

RSA key-based authentication has long become the standard — a good, convenient, logical, and correct one. It’s both secure and reliable. While Unix-like systems continue to embrace this standard, with SSH management becoming deeply integrated and an ecosystem of SSH-based infrastructure tools flourishing, Windows remains somewhat on the sidelines.

On Windows, it’s still a challenge: finding a decent SSH client and terminal isn’t easy, and the situation with agents is far from perfect — but that’s a topic for another article. Here, we’ll focus on simplifying the very first step in setting up a new server: uploading your RSA public key.

Users of *nix systems are likely familiar with the ssh-copy-id command. It’s essentially just a Bash script that looks something like this:

 1#!/bin/sh
 2
 3# Shell script to install your public key on a remote machine
 4# Takes the remote machine name as an argument.
 5# Obviously, the remote machine must accept password authentication,
 6# or one of the other keys in your ssh-agent, for this to work.
 7
 8ID_FILE="${HOME}/.ssh/id_rsa.pub"
 9
10if [ "-i" = "$1" ]; then
11  shift
12  # check if we have 2 parameters left, if so the first is the new ID file
13  if [ -n "$2" ]; then
14    if expr "$1" : ".*\.pub" > /dev/null ; then
15      ID_FILE="$1"
16    else
17      ID_FILE="$1.pub"
18    fi
19    shift         # and this should leave $1 as the target name
20  fi
21else
22  if [ x$SSH_AUTH_SOCK != x ] && ssh-add -L >/dev/null 2>&1; then
23    GET_ID="$GET_ID ssh-add -L"
24  fi
25fi
26
27if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
28  GET_ID="cat \"${ID_FILE}\""
29fi
30
31if [ -z "`eval $GET_ID`" ]; then
32  echo "$0: ERROR: No identities found" >&2
33  exit 1
34fi
35
36if [ "$#" -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
37  echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
38  exit 1
39fi
40
41# strip any trailing colon
42host=`echo $1 | sed 's/:$//'`
43
44{ eval "$GET_ID" ; } | ssh $host "umask 077; test -d ~/.ssh || mkdir ~/.ssh ; cat >> ~/.ssh/authorized_keys && (test -x /sbin/restorecon && /sbin/restorecon ~/.ssh ~/.ssh/authorized_keys >/dev/null 2>&1 || true)" || exit 1
45
46cat <<EOF
47Now try logging into the machine, with "ssh '$host'", and check in:
48
49  ~/.ssh/authorized_keys
50
51to make sure we haven't added extra keys that you weren't expecting.
52
53EOF

What this script does is upload the user’s public key (by default, ~/.ssh/id_rsa.pub) to the specified server for the specified user. Sure, it’s just a couple of lines of code — but they make life much easier.

But what if you’re on Windows? As usual: time to write your own workaround.

I’m not the first person to run into this. Here, for example, someone proposes a one-liner batch script that does the exact same thing:

1type  public_id | plink.exe username@hostname "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys"

There is another option also, bigger script, which can take the server address, password and key as inputs:

 1:: from http://serverfault.com/questions/224810/is-there-an-equivalent-to-ssh-copy-id-for-windows
 2:: expected parameters
 3:: [email protected] password [id_ras.pub]
 4::usage: ssh-copy-id [email protected] password [identity file]
 5::@echo off
 6IF "%~3"=="" GOTO setdefault
 7set /p id=<%3
 8GOTO checkparams
 9:setdefault
10set /p id=<id_rsa.pub
11:checkparams
12IF "%~1"=="" GOTO promptp
13IF "%~2"=="" GOTO promptp2
14:exec
15:: To accept the signature the first time
16echo y | plink.exe %1 -pw %2 "exit"
17:: now to actually copy the key
18echo %id% | plink.exe %1 -pw %2 "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys"
19GOTO end
20:promptp
21set /p 1="Enter [email protected]: "
22:promptp2
23set /p 2="Enter password: "
24GOTO exec
25:end
26pause

I went a bit further and wrote a PowerShell implementation.

The key difference: when launched, it shows a dialog window where you can select the public key file. After that, there’s a basic check to ensure the file is valid and looks like a proper public key that can be used for authentication.

From there, the rest is standard: it connects to the server and appends the key content to the appropriate location.

 1# ssh-copy-id analog for Windows systems
 2# Script to install your public key on a remote machine
 3# The remote machine must accept password authentication,
 4# or one of the other keys in your Putty Agent, for this to work.
 5#
 6# (c) soar - http://soar.name
 7
 8# Dialog for public key selection
 9Function Select-File()
10{
11    [void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms");
12
13    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog;
14    $OpenFileDialog.Filter = "Public Keys (*.pub) | *.pub";
15    $OpenFileDialog.ShowHelp = $true; # Without this line - dialog not appears.. I don't understand why.
16    [void] $OpenFileDialog.ShowDialog();
17    $OpenFileDialog.filename;
18}
19
20Function ShowMessage($title, $content, $type)
21{
22    [void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms");
23    [void][Windows.Forms.Messagebox]::show($content, $title, $type);
24}
25
26# Returns current script directory, plink.exe must be in same place
27Function Get-ScriptDirectory
28{
29    $Invocation = (Get-Variable MyInvocation -Scope 1).Value;
30    Split-Path $Invocation.MyCommand.Path;
31}
32
33$pubKeyFile = Select-File
34if (! $pubKeyFile) {
35    ShowMessage 'Need to select file' 'Please, select public key file for upload to remote host' 'OK';
36    Exit;
37}
38
39$pubKey = Get-Content -LiteralPath $pubKeyFile;
40if (! ($pubKey -is [string]) -or ! $pubKey.StartsWith("ssh-")) {
41    ShowMessage "Wrong file?" "Selected file not looks like valid SSH public key. It must starts with `"ssh-`" and contain one line." "OK"
42    Exit;
43}
44
45$plinkExecutable = Join-Path (Get-ScriptDirectory) "plink.exe";
46
47if ($args.Length) {
48    foreach ($arg in $args) {
49        & $plinkExecutable -ssh $arg "umask 077; test -d ~/.ssh || mkdir ~/.ssh ; echo `"$pubKey`" >> ~/.ssh/authorized_keys"
50    }
51} else {
52    $hostname = Read-Host "Please enter target hostname (user@hostname):";
53    if ($hostname) {
54        & $plinkExecutable -ssh $hostname "umask 077; test -d ~/.ssh || mkdir ~/.ssh ; echo `"$pubKey`" >> ~/.ssh/authorized_keys"
55    }
56}
57
58Write-Host "Press any key to continue ..."
59$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

It uses plink, so plink.exe should be in the same directory.

GitHub Gist   BitBucket

@soar
Author
@soar
Senior SRE/DevOps engineer

Related

Windows, VPN and routes
·490 words·3 mins· loading · loading
Sysadmin Windows
Inno Setup Archive Manager
·553 words·3 mins· loading · loading
Sysadmin Delphi Innosetup Windows
Plugin to pack archives on the fly
HTTP Stream Benchmark
·18 words·1 min· loading · loading
Sysadmin Delphi Http Benchmark Windows
Win32 app for HTTP benchmarking by downloading files