Deploy ssh public key to multiple servers using python and paramiko
This is a little snippet I wrote to install my publickey onto multiple servers at once. The actual script I use automatically detects all the servers. It is using paramiko to do the actual ssh work.
#!/usr/bin/python import os from getpass import getpass import paramiko def deploy_key(key, server, username, password): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(server, username=username, password=password) client.exec_command('mkdir -p ~/.ssh/') client.exec_command('echo "%s" > ~/.ssh/authorized_keys' % key) client.exec_command('chmod 644 ~/.ssh/authorized_keys') client.exec_command('chmod 700 ~/.ssh/') key = open(os.path.expanduser('~/.ssh/id_rsa.pub')).read() username = os.getlogin() password = getpass() hosts = ["hostname1", "hostname2", "hostname3"] for host in hosts: deploy_key(key, host, username, password)
Jonas Wagner
Is getpass() from a package that you have defined?
Comment by airborne — 10/28/10 4:39 PM | # - re
nope, it's from the stdlib:
docs.python.org/library/getpass.html
Comment by Jonas Wagner — 10/29/10 12:04 AM | # - re
It is a nice idea to write a python script, which propagates ssh public keys to the target servers. It would be even better, if the script would be written more generalised, compared of what you are typing on the command line. Get people the opportunity to set the ssh port for each host, allow “dsa” beside “rsa”, check, if a key is already propagated and don't overwrite the file if it exist, and allow to get “host” “port” and “login” data from some sort of list or service. There is now need to let follow “mkdir” the “-p” option, and use “600” as the “chmod” parameter in “chmod 644 ~/.ssh/authorized_keys”.
Tanks for the first step. I didn't know about paramiko, Stephan
Comment by Stephan Wagner — 11/30/10 7:57 PM | # - re
This is actually a watered down version, the actual one gets the host information directly from the loadbalancer. The -p is for the odd case where your home directory doesn't exist. I don't see any harm in the 644, those are public keys after all. Changing the > to >> would append the key.
Cheers,
Jonas
Comment by Jonas Wagner — 12/1/10 3:58 PM | # - re