Source

woocode / sa-auto / sh / change_hosts.py

#!/usr/bin/env python

import random

etc_host = '/etc/hosts'

qzone_hosts = {'drift.qzone.qq.com': ['119.147.74.93', '119.147.15.36','183.60.3.249']}

def write(filename, lines):
    with open(filename, 'wb') as fb:
        fb.write('\n'.join(lines))

def main():
    k = 'drift.qzone.qq.com'
    ip = random.choice(qzone_hosts[k])
    with open(etc_host, 'rb') as fb:
        new_lines = []
        for line in fb:
            line = line.strip()
            if line.startswith('#'): 
                new_lines.append(line)
                continue
            li = line.split(' ', 1)
            if len(li) < 2:
                new_lines.append(line)
                continue
            domain = li[1].strip()
            if domain == k:
                line = ' '.join([ip, k])
            new_lines.append(line)
    print '\n'.join(new_lines)
    write(etc_host, new_lines)
    print 'updated hosts'


if __name__ == "__main__":
    main()