Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3.  
  4. # $Id: $
  5. import socket
  6. import sys
  7. import os
  8. import getpass
  9.  
  10. import paramiko
  11. from storm import Storm
  12.  
  13. sconfig = Storm(os.path.expanduser("~/.ssh/config"))
  14. sconfig.backup(os.path.expanduser("~/.ssh/config.bak"))
  15. if len(sys.argv) < 2:
  16. username = raw_input("Enter username: ")
  17. host = raw_input("Enter host: ")
  18. else:
  19. username, host = sys.argv[1].split('@')
  20. name = host.split('.')[0]
  21.  
  22. if sconfig.is_host_in(name):
  23. print "Host %s already exists in .ssh/config, removing." % name
  24. sconfig.delete_entry(name)
  25. print "Creating new entry for %s" % name
  26. keyfile = os.path.expanduser("~/.ssh/id_dsa")
  27. opts = "StrictHostKeyChecking=no"
  28. sconfig.add_entry(name, host, username, 22, keyfile, opts)
  29.  
  30. print "Fix known_hosts"
  31. known_hosts = os.path.expanduser('~/.ssh/known_hosts')
  32. host_keys = paramiko.hostkeys.HostKeys(known_hosts)
  33. new_host_keys = paramiko.hostkeys.HostKeys()
  34.  
  35. ip = socket.gethostbyname(host)
  36.  
  37. entries = host_keys.lookup(host)
  38. entries = entries._entries if entries else []
  39.  
  40. ip_entries = host_keys.lookup(ip)
  41. entries += ip_entries._entries if ip_entries else []
  42.  
  43. for entry in host_keys._entries:
  44. if entry in entries:
  45. print "removing %s" % entry
  46. continue
  47. new_host_keys._entries.append(entry)
  48.  
  49. new_host_keys.save(known_hosts)
  50.  
  51.  
  52. print "Uploading authorized_keys"
  53.  
  54. password = getpass.getpass('Enter ssh password: ')
  55.  
  56. key = open(os.path.expanduser("~/.ssh/id_dsa.pub")).read()
  57. ssh = paramiko.SSHClient()
  58. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  59. ssh.connect(host, 22, username, password, allow_agent=False, look_for_keys=False)
  60. print "mkdir -p .ssh"
  61. ssh.exec_command('mkdir -p ~/.ssh/')
  62. print "echo..."
  63. ssh.exec_command('echo "%s" > ~/.ssh/authorized_keys' % key)
  64. print "chmod..."
  65. ssh.exec_command('chmod 644 ~/.ssh/authorized_keys')
  66. ssh.exec_command('chmod 700 ~/.ssh/')
  67. print "Done."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement