Skip to content

Instantly share code, notes, and snippets.

Forked from ceilfors/
Last active October 7, 2019 13:47
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
ssh-copy-id for Windows with custom port
"""ssh-copy-id for Windows.
Example usage: python ceilfors@my-remote-machine
This script is dependent on msysgit by default as it requires scp and ssh.
For convenience you can also try that comes
import argparse, os
from subprocess import call
def winToPosix(win):
"""Converts the specified windows path as a POSIX path in msysgit.
win: C:\\home\\user
posix: /c/home/user
posix = win.replace('\\', '/')
return "/" + posix.replace(':', '', 1)
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--identity_file", help="identity file, default to ~\\.ssh\\", default=os.environ['HOME']+"\\.ssh\\")
parser.add_argument("-d", "--dry", help="run in the dry run mode and display the running commands.", action="store_true")
parser.add_argument("-p", "--port", help="custom port (22 by default)", default="22")
parser.add_argument("remote", metavar="user@machine")
args = parser.parse_args()
local_key = winToPosix(args.identity_file)
remote_key = "~/"
# Copy the public key over to the remote temporarily
scp_command = "scp -P {} {} {}:{}".format(args.port, local_key, args.remote, remote_key)
if not args.dry:
# Append the temporary copied public key to authorized_key file and then remove the temporary public key
ssh_command = ("ssh {} -p {} "
"mkdir -p ~/.ssh;"
"touch ~/.ssh/authorized_keys;"
"cat {} >> ~/.ssh/authorized_keys;"
"rm {};").format(args.remote, args.port, remote_key, remote_key)
if not args.dry:
Copy link

seems a little risky: .format(args.remote, args.port, remote_key, remote_key) - you can format every individual command

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment