使用Python修改本地hosts文件

最近有个需求,需要修改本地的hosts文件,把某个域名的IP替换为另一个IP。

比如原记录为

192.168.0.1 www.test.com

需要改为

192.168.0.2 www.test.com

其它的记录不变。

首先想到的是用Python来修改,特地写了个脚本。

import os

def change_ip(domain, new_ip):
    hosts = "/etc/hosts"

    # 按行读取
    with open(hosts, 'r') as file1:
        lines = file1.readlines()

    new_content = ""

    for line in lines:
        line = line.replace("\n", "")
        # 跳过空行和注释
        if not line:
            new_content += "\n"
            continue
        if line[0] == "#":
            new_content += line + "\n"
            continue
        else:
            # 多个空格替换为一个
            line = ' '.join(line.split())
            # 按空格分隔
            line_arr = line.split(' ')
            # 数组为2说明是host
            if len(line_arr) == 2:
                # 0是ip 1是域名
                arg1 = line_arr[1]
                if arg1 == domain:
                    new_line = new_ip + ' ' +  domain
                else:
                    new_line = line
            else:
                new_line = line

        new_content += new_line + "\n"

    # print(new_content)
    file_new = open(hosts, 'w+')
    file_new.write(new_content)
    file_new.close()

    return True

change_ip('www.test.com', '192.168.0.2')

因为/etc/hosts的权限问题,执行的时候要加sudo

sudo python3 xxx.py

Leave a Comment

豫ICP备19001387号-1