def run(self, dryrun): ensure_sudo() icv = InteractiveConfigValidation() icv.run() config = icv.get() network = Network(config['server'], config['port'], config['secret'], config['verify_ssl']) resp = network.get_ips() if resp == 'connection_error': print 'connection error' sys.exit(2) domains = [ d.split(' ') for d in resp.split('\n')] updated_hosts = [] PD_BEGIN = '### PRIVATE DOMAINS BEGIN ###' PD_END = '### PRIVATE DOMAINS END ###' if isfile('/etc/hosts'): PD_NOTSTARTED = 1 PD_STARTED = 2 PD_ENDED = 3 state = PD_NOTSTARTED with open('/etc/hosts') as f: for line in f: line = line[:-1] # remove \n if state == PD_NOTSTARTED: assert line not in [PD_END] if line == PD_BEGIN: state = PD_STARTED else: updated_hosts.append(line) elif state == PD_STARTED: assert line not in [PD_BEGIN] if line == PD_END: state = PD_ENDED elif state == PD_ENDED: assert line not in [PD_BEGIN, PD_END] updated_hosts.append(line) else: # hosts did not exists create new one pass updated_hosts.append(PD_BEGIN) for domain, ip in domains: updated_hosts.append('%s\t%s' % (ip, domain)) updated_hosts.append(PD_END) # adding a newline at the end of file updated_hosts.append('') updated_hosts_string = '\n'.join(updated_hosts) if dryrun: print updated_hosts_string else: with open('/etc/hosts', "w+") as f: f.write(updated_hosts_string)
def run(self): icv = InteractiveConfigValidation() icv.run() config = icv.get() network = Network(config['server'], config['port'], config['secret'], config['verify_ssl']) resp = network.get_ips() if resp == 'connection_error': print 'connection error' sys.exit(2) else: print resp