问题
So I have access to a number of EC2 instances, some of which have been running for years. We have a special repository of the private keys to all of these; thus I can, for most of our instances, get into them as root (or the 'ubuntu' user in some cases) to administer them.
While playing with boto I noticed the EC2 .get_keypair() and get_all_keypairs methods and was wondering if this could be used to recover any SSH keys which have slipped through the cracks of our procedures and been lost.
When I inspect the resulting boto.ec2.keypair.KeyPair objects, however, I see that the .material attribute seems to be empty and when I try to use the keypair's .save() method I get an exception complaining that the materials haven't been fetched.
(Other operations, such as .get_all_instances() and .run_instances() are working during that session).
So, what am I missing? Are there some other operations for which I have to provide the X.509 cert. in addition to my normal AWS key/secret pair?
(Note: I don't actually need this yet. I'm just familiarizing myself with the API and preparing for such eventualities).
回答1:
It is not possible to recover SSH keys like so, the get_all_key_pairs() method name is a bit misleading in this regard, though properly documented by means of the return object of class boto.ec2.keypair.KeyPair at least, see e.g. the save() method:
Save the material (the unencrypted PEM encoded RSA private key) of a newly created KeyPair to a local file. [emphasis mine]
This is not a limitation of boto, but a result of the security architecture of Amazon EC2: you can only retrieve a complete key pair (i.e. including the private key) during the initial creation of a key pair, the private key is never stored by EC2 and cannot be recovered, if you ever loose it (but see below for a workaround).
Eric Hammond's recent answer to the related question consequences of deleted key pair on ec2 instance provides another angle to this topic, including a pointer to his article Fixing Files on the Root EBS Volume of an EC2 Instance, explaining how to get access to the instance regardless eventually.
Given some of your instances have been running for years, this might not work though, insofar This process is only available with an EBS boot instance (which haven't been available back then), and, as Eric stresses as well, is one of the many reasons why You Should Use EBS Boot Instances on Amazon EC2 nowadays.
来源:https://stackoverflow.com/questions/10569653/boto-get-all-keypairs-method-and-the-save-of-its-results