Preferred way to automatically update SSH configuration file using Python?

I use Fabric to automate some of my workflows, most of which involve manipulating EC2 instances.

I am looking for a way to keep my .ssh/config file updated, as I regularly start and close EC2 instances, and it is very useful for me if I can easily debug them easily for debugging and so on.

The entries in my SSH configuration file are as follows

 Host ins_id Hostname xxxxxxxx.com User ubuntu IdentityFile ~/.ssh/kp.pem 

boto now I am doing something like the following (using Fabric and boto ), which is an openly junk approach:

 def my_cool_spin_up_function(self): . . . . . . ssh_conf = os.path.join(homedir, '.ssh/config') ssh_info = '\n'.join(['Host %s' % name, 'Hostname %s' % ins.dns_name, 'User %s' % env.user, 'IdentityFile %s' % kp_loc, '\n']) w_com = 'echo %s | cat - %s | tee %s > /dev/null' % (ssh_info, ssh_conf, ssh_conf) local(w_com) 

As you can see, this will simply continue to be added to my configuration file every time it is called, and this is normal because SSH occupies the first partition for each host in the configuration, but that means the file grows up.

I am wondering if there are any Python libraries that allow you to treat .ssh/config as more of a configuration file whose corresponding parts can be updated as and when. For example, it would be great if you could just consider .ssh/config as a dictionary and abstract from reading / writing the file.,.

Thanks for any suggestions!

+6
source share
2 answers

What we do for this type of configuration is to maintain a directory of configuration fragments that you can add / remove as needed, and then do something line by line:

 cat .ssh/config.d/* > .ssh/config 

This will add things in lexical order, which means that the order depends on how you select the file names. This simplifies obsolescence of old configurations, deletion of certain elements and, otherwise, management of the configuration file.

+7
source

How about something like this:

 class SSHConfig(object): def __init__(self, filename=None): if filename is not None: self.read(filename) else: self.conf = dict() def read(self, filename): self.conf = dict(line.decode("utf-8").rstrip().split(" ", 1) for line in open(filename)) def write(self, filename): with open(filename, "w") as f: for key, value in self.conf.items(): f.write("%s %s\n".encode("utf-8") % (key, value)) def set(self, key, value): self.conf[key] = value def get(self, key): return self.conf.get(key, None) 
0
source

Source: https://habr.com/ru/post/903203/


All Articles