Merge branch 'develop' of git.osuosl.org:ganeti/ganeti_webmgr into release/0.7
[ganeti_webmgr.git] / util / sshkeys.py
blob247d387944f642e2022e17dcea34cfa615cc78d7
1 #!/usr/bin/env python
2 # coding: utf-8
4 from optparse import OptionParser
5 from urllib2 import urlopen
6 from urlparse import urlparse, urlunparse
7 import json
8 import sys
10 parser = OptionParser()
11 parser.add_option("-c", "--cluster", help="cluster to retrieve keys from")
12 parser.add_option("-i", "--instance", help="instance to retrieve keys from")
14 def main():
15 options, arguments = parser.parse_args()
16 if len(arguments) < 2:
17 parser.error("an API key and hostname are required")
18 if options.instance and not options.cluster:
19 parser.error("instances cannot be specified without a cluster")
21 app = Application(arguments[0], arguments[1],
22 cluster_slug=options.cluster, vm_name=options.instance)
23 app.run()
25 class ArgumentException(Exception):
26 """
27 There was a bad argument, or something like that.
28 """
30 class BadMimetype(Exception):
31 """
32 There was a bad MIME type, or something like that.
33 """
35 class Application(object):
36 def __init__(self, api_key, hostname, cluster_slug=None, vm_name=None):
37 if cluster_slug is not None:
38 if vm_name is not None:
39 path = "/cluster/%s/%s/keys/%s/" % (cluster_slug, vm_name,
40 api_key)
41 else:
42 path = "/cluster/%s/keys/%s/" % (cluster_slug, api_key)
43 else:
44 path = "/keys/%s/" % api_key
46 split = urlparse(hostname)
47 self.url = urlunparse(split._replace(path=path))
49 def get(self):
50 """
51 Gets the page specified in __init__
52 """
54 content = urlopen(self.url)
55 if content.info()["Content-Type"] != "application/json":
56 raise BadMimetype("It's not JSON")
57 return content.read()
59 def parse(self, content):
60 """
61 Parses returned results from JSON into Python list
62 """
64 return json.loads(content)
66 def printout(self, data):
67 """
68 Returns string with authorized_keys file syntax and some comments
69 """
71 s = ["%s added automatically for ganeti web manager user: %s" % i
72 for i in data]
73 return "\n".join(s)
75 def run(self):
76 """
77 Combines get, parse and printout methods.
78 """
79 try:
80 s = self.printout(self.parse(self.get()))
81 except Exception, e:
82 sys.stderr.write("Errors occured, could not retrieve informations.\n")
83 sys.stderr.write(str(e)+"\n")
84 else:
85 sys.stdout.write(s)
87 if __name__ == "__main__":
88 main()