Last active
February 17, 2017 19:04
-
-
Save rgbkrk/6994544 to your computer and use it in GitHub Desktop.
Rebuilding an arbitrary server with an SSH Key.
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
#!/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