Skip to content

Instantly share code, notes, and snippets.

@nqbao
Created December 16, 2014 22:47
Show Gist options
  • Save nqbao/bfd275c0a078a556bd7d to your computer and use it in GitHub Desktop.
Save nqbao/bfd275c0a078a556bd7d to your computer and use it in GitHub Desktop.
# install ssh key on server
@task
def add_public_key(key_file="default.pub",key_type="openssh"):
with hide("running"):
key_abs_file = key_file
# 1st try
if not os.path.isfile(key_abs_file):
key_abs_file = os.getcwd() + "/" + key_file
# 2nd try
if not os.path.isfile(key_abs_file):
key_abs_file = os.path.dirname(env.fabfile) + "/" + key_file
if not os.path.isfile(key_abs_file):
print(colors.red("Key file does not exist: " + key_abs_file))
return
tmp_localkey = "/tmp/" + str(uuid.uuid1())
if key_type == "putty":
local("ssh-keygen -i -f %s >> %s" % (key_abs_file, tmp_localkey))
else:
local("cp %s %s" % (key_abs_file, tmp_localkey))
tmp_file = "/tmp/" + str(uuid.uuid1())
# avoid duplication
with hide("stdout"):
if utils.exists("~/.ssh/authorized_keys"):
with open(tmp_localkey, "r") as f:
this_key = f.read().strip()
current_keys = run("cat ~/.ssh/authorized_keys")
if current_keys.find(this_key) != -1:
local("rm %s" % tmp_localkey)
print(colors.green("Key %s is already installed on server." % key_file))
return
print(colors.green("Install %s to %s." % (key_file, env.host)))
run("mkdir -p ~/.ssh")
run("chmod 0700 ~/.ssh")
put(tmp_localkey, tmp_file)
run("printf \"\" >> ~/.ssh/authorized_keys")
run("cat " + tmp_file + " >> ~/.ssh/authorized_keys ", False, False)
run("chmod go-rwx ~/.ssh ~/.ssh/authorized_keys")
run("rm " + tmp_file)
local("rm %s" % tmp_localkey)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment