4 from optparse
import OptionParser
5 from urllib2
import urlopen
6 from urlparse
import urlparse
, urlunparse
9 from django
.utils
import simplejson
as json
11 parser
= OptionParser()
12 parser
.add_option("-c", "--cluster", help="cluster to retrieve keys from")
13 parser
.add_option("-i", "--instance", help="instance to retrieve keys from")
17 options
, arguments
= parser
.parse_args()
18 if len(arguments
) < 2:
19 parser
.error("an API key and hostname are required")
20 if options
.instance
and not options
.cluster
:
21 parser
.error("instances cannot be specified without a cluster")
23 app
= Application(arguments
[0], arguments
[1],
24 cluster_slug
=options
.cluster
, vm_name
=options
.instance
)
28 class ArgumentException(Exception):
30 There was a bad argument, or something like that.
34 class BadMimetype(Exception):
36 There was a bad MIME type, or something like that.
40 class Application(object):
41 def __init__(self
, api_key
, hostname
, cluster_slug
=None, vm_name
=None):
42 if cluster_slug
is not None:
43 if vm_name
is not None:
44 path
= "/cluster/%s/%s/keys/%s/" % (cluster_slug
, vm_name
,
47 path
= "/cluster/%s/keys/%s/" % (cluster_slug
, api_key
)
49 path
= "/keys/%s/" % api_key
51 split
= urlparse(hostname
)
52 self
.url
= urlunparse(split
._replace
(path
=path
))
56 Gets the page specified in __init__
59 content
= urlopen(self
.url
)
60 if content
.info()["Content-Type"] != "application/json":
61 raise BadMimetype("It's not JSON")
64 def parse(self
, content
):
66 Parses returned results from JSON into Python list
69 return json
.loads(content
)
71 def printout(self
, data
):
73 Returns string with authorized_keys file syntax and some comments
76 s
= ["%s added automatically for ganeti web manager user: %s" % i
82 Combines get, parse and printout methods.
85 s
= self
.printout(self
.parse(self
.get()))
87 sys
.stderr
.write("Errors occured, could not "
88 "retrieve informations.\n")
89 sys
.stderr
.write(str(e
)+"\n")
93 if __name__
== "__main__":