-
-
Save strayge/4411e9b84c54d364e97893f8eb8a4e9e to your computer and use it in GitHub Desktop.
ssh-copy-id for Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""ssh-copy-id for Windows. | |
Example usage: python ssh-copy-id.py 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 http://bliker.github.io/cmder/. | |
origin url: https://gist.github.com/ceilfors/fb6908dc8ac96e8fc983 | |
""" | |
import argparse, os | |
from subprocess import call, PIPE | |
def winToPosix(win): | |
"""Converts the specified windows path as a POSIX path in msysgit. | |
Example: | |
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\\id_rsa.pub", | |
default=os.path.join(os.environ['HOME'], '.ssh', 'id_rsa.pub'), | |
) | |
parser.add_argument("-d", "--dry", | |
help="run in the dry run mode and display the running commands.", | |
action="store_true", | |
) | |
parser.add_argument("remote", | |
metavar="user@machine", | |
) | |
parser.add_argument("-p", "--port", | |
default=22, | |
help="custom SSH port", | |
) | |
args = parser.parse_args() | |
local_key = args.identity_file # winToPosix(args.identity_file) | |
remote_key = "~/temp_id_rsa.pub" | |
# Copy the public key over to the remote temporarily | |
scp_command = "scp -P {} {} {}:{}".format(args.port, local_key, args.remote, remote_key) | |
print(scp_command) | |
if not args.dry: | |
status = call(scp_command) | |
if status != 0: | |
print('scp returned {} code'.format(status)) | |
exit(1) | |
# 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.port, args.remote, remote_key, remote_key) | |
print(ssh_command) | |
if not args.dry: | |
status = call(ssh_command) | |
if status != 0: | |
print('ssh returned {} code'.format(status)) | |
exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment