Advertisement
Guest User

Untitled

a guest
Feb 17th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. '''
  4. Builds a server with no SSH key then rebuilds it with an SSH Key.
  5. '''
  6.  
  7. import os
  8. import getpass
  9.  
  10. import pyrax
  11. import paramiko
  12.  
  13. pyrax.set_setting("identity_type", "rackspace")
  14. pyrax.set_credential_file(os.path.expanduser("~/.rackspace_cloud_credentials"))
  15.  
  16. # Shorthand cloudservers
  17. cs = pyrax.cloudservers
  18.  
  19. flavor_512 = [flavor for flavor in cs.flavors.list() if flavor.ram == 512][0]
  20. ubu_image = [img for img in cs.images.list() if "Ubuntu 12.04" in img.name][0]
  21.  
  22. # Build a brand new server, no SSH key
  23. server = cs.servers.create("demo_6994544", ubu_image.id, flavor_512.id)
  24. server = pyrax.utils.wait_for_build(server, verbose=True)
  25.  
  26. # This time rebuild it with an SSH key
  27. server.rebuild(ubu_image, key_name="mac")
  28. server = pyrax.utils.wait_for_build(server, verbose=True)
  29.  
  30. print(server.accessIPv4)
  31.  
  32. # Now use paramiko to set up an SSH connection and read authorized_keys
  33.  
  34. ssh_client = paramiko.SSHClient()
  35. ssh_client.load_system_host_keys()
  36. # Paramiko, by default, has strict checking of known_hosts
  37. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  38.  
  39. # Require user input for the passphrase to the key (can also use keyring)
  40. keyfile = os.path.expanduser('~/.ssh/id_rsa')
  41. password = getpass.getpass("Passphrase: ")
  42. key = paramiko.RSAKey.from_private_key_file(keyfile, password=password)
  43. ssh_client.connect(server.accessIPv4, username="root", pkey=key)
  44.  
  45. sftp_client = ssh_client.open_sftp()
  46. authorized_keys_file = stfp_client.open('/root/.ssh/authorized_keys')
  47.  
  48. authorized_keys = authorized_keys_file.read()
  49.  
  50. print(authorized_keys)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement