Skip to content

Instantly share code, notes, and snippets.

@rgbkrk
Last active February 17, 2017 19:04
Show Gist options
  • Save rgbkrk/6994544 to your computer and use it in GitHub Desktop.
Save rgbkrk/6994544 to your computer and use it in GitHub Desktop.
Rebuilding an arbitrary server with an SSH Key.
#!/usr/bin/env python
'''
Builds a server with no SSH key then rebuilds it with an SSH Key.
'''
import os
import getpass
import pyrax
import paramiko
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_credential_file(os.path.expanduser("~/.rackspace_cloud_credentials"))
# Shorthand cloudservers
cs = pyrax.cloudservers
flavor_512 = [flavor for flavor in cs.flavors.list() if flavor.ram == 512][0]
ubu_image = [img for img in cs.images.list() if "Ubuntu 12.04" in img.name][0]
# Build a brand new server, no SSH key
server = cs.servers.create("demo_6994544", ubu_image.id, flavor_512.id)
server = pyrax.utils.wait_for_build(server, verbose=True)
# This time rebuild it with an SSH key
server.rebuild(ubu_image, key_name="mac")
server = pyrax.utils.wait_for_build(server, verbose=True)
print(server.accessIPv4)
# Now use paramiko to set up an SSH connection and read authorized_keys
ssh_client = paramiko.SSHClient()
ssh_client.load_system_host_keys()
# Paramiko, by default, has strict checking of known_hosts
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Require user input for the passphrase to the key (can also use keyring)
keyfile = os.path.expanduser('~/.ssh/id_rsa')
password = getpass.getpass("Passphrase: ")
key = paramiko.RSAKey.from_private_key_file(keyfile, password=password)
ssh_client.connect(server.accessIPv4, username="root", pkey=key)
sftp_client = ssh_client.open_sftp()
authorized_keys_file = stfp_client.open('/root/.ssh/authorized_keys')
authorized_keys = authorized_keys_file.read()
print(authorized_keys)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment