4 from optparse
import OptionParser
5 from urllib2
import urlopen
6 from urlparse
import urlparse
, urlunparse
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")
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
)
25 class ArgumentException(Exception):
27 There was a bad argument, or something like that.
30 class BadMimetype(Exception):
32 There was a bad MIME type, or something like that.
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
,
42 path
= "/cluster/%s/keys/%s/" % (cluster_slug
, api_key
)
44 path
= "/keys/%s/" % api_key
46 split
= urlparse(hostname
)
47 self
.url
= urlunparse(split
._replace
(path
=path
))
51 Gets the page specified in __init__
54 content
= urlopen(self
.url
)
55 if content
.info()["Content-Type"] != "application/json":
56 raise BadMimetype("It's not JSON")
59 def parse(self
, content
):
61 Parses returned results from JSON into Python list
64 return json
.loads(content
)
66 def printout(self
, data
):
68 Returns string with authorized_keys file syntax and some comments
71 s
= ["%s added automatically for ganeti web manager user: %s" % i
77 Combines get, parse and printout methods.
80 s
= self
.printout(self
.parse(self
.get()))
82 sys
.stderr
.write("Errors occured, could not retrieve informations.\n")
83 sys
.stderr
.write(str(e
)+"\n")
87 if __name__
== "__main__":