#!/usr/bin/env python from __future__ import print_function class Interfaces(): "Manage /etc/network/interfaces file" def __init__(self): # Open file fd = open("interfaces") # Make iterator of contents self.iterator = iter( [ line.strip() for line in fd.read().splitlines() if line.strip() ] ) # Close file fd.close() # Parsed directives self.directives = [] # Do the needful self.parse() def parse(self): "Parse super- and sub-directives, and return nested results" # For each directive for directive in self.iterator: # If we're on a super, start sub loop while directive.startswith(("iface", "mapping")): sup = None # Clear super-directive subs = [] # Clear sub-directives # For each sub-directive for sub in self.iterator: # If sub is actually a super if sub.startswith( ( "auto", "allow-", "iface", "mapping", "source" ) ): sup = sub # Set new super break # Exit sub loop # Else it's just a sub, so add it else: subs.append(sub) # If we found subs, store them if subs: self.directives.append([directive, subs]) # Else just store directive else: self.directives.append([directive]) # If we didn't find a super, return if not sup: return directive = sup # Store super for next inner loop check # Not a super here so just add directive self.directives.append([directive]) # End of iterator, return return # TODO: -> save def prettyPrint(self): "Pretty-print interface directives" for directive in self.directives: # Print directive print(directive[0]) # If has subs if len(directive) > 1: # Print indented subs for sub in directive[1]: print(" {}".format(sub)) # If super, add a blank line for spacing if directive[0].startswith(("iface", "mapping")): print() def swapDirective(self, one, two): "Swap one directive with another" for index, directive in enumerate(self.directives): if one in directive[0]: self.directives[index][0] = directive[0].replace(one, two) def addSubs(self, sup, subs): "Add sub-directives to super-directive" for index, directive in enumerate(self.directives): if sup == directive[0] and len(directive) > 1: self.directives[index][1].extend(subs) interfaces = Interfaces() interfaces.swapDirective("eth3", "lxb-mgmt") interfaces.addSubs( "iface lxb-mgmt inet manual", [ "pre-up ip link add name phy-lxb-mgmt " "type veth peer name ovs-lxb-mgmt || true", "bridge_ports eth3 phy-lxb-mgmt" ] ) interfaces.prettyPrint()