Advertisement
Guest User

dsh example

a guest
Apr 7th, 2011
635
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. #!/usr/bin/python
  2. import urllib
  3. import paramiko
  4. import json
  5.  
  6. from optparse import OptionParser
  7.  
  8. def main():
  9.         parser = OptionParser(conflict_handler="resolve")
  10.         parser.set_usage("ddsh [options] 'command'")
  11.         parser.add_option("-p", dest="puppetclass", help="Use instances from the following puppet class")
  12.  
  13.         (options, args) = parser.parse_args()
  14.         command = args[0]
  15.  
  16.         query = '[[Resource Type::instance]][[Puppet Class::%s]]|?FQDN|format=json' % (options.puppetclass)
  17.         query = ask_encode(query)
  18.         askaddress = 'http://nova-controller.tesla.usability.wikimedia.org/trunk.1/Special:Ask/'
  19.         query = askaddress + query
  20.         f = urllib.urlopen(query)
  21.         results = f.read()
  22.         results = json.loads(results)
  23.         for result in results['items']:
  24.                 fqdn = result['fqdn']
  25.                 print 'Running "%s" on instance "%s"' % (command, fqdn)
  26.                 success = run_command(fqdn, command)
  27.  
  28. def ask_encode(query):
  29.         matches = {'[': '-5B', ']': '-5D', ' ': '-20', '|': '/', '=': '%3D', '?': '-3F'}
  30.         for match,replace in matches.iteritems():
  31.                 query = query.replace(match, replace)
  32.  
  33.         return query
  34.  
  35. def run_command(server, command):
  36.         try:
  37.                 ssh = paramiko.SSHClient()
  38.                 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  39.                 try:
  40.                         ssh.connect(server)
  41.                 except (paramiko.SSHException, socket.error):
  42.                         print "Failed to connect to %s." % server
  43.                         return False
  44.                 stdin, stdout, stderr = ssh.exec_command(command)
  45.                 for line in stdout.readlines():
  46.                         line = line.strip()
  47.                         print line
  48.                 return True
  49.         except Exception:
  50.                 print "Couldn't connect to %s" % (server)
  51.                 return False
  52.  
  53. if __name__ == "__main__":
  54.         main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement