python脚本修改hosts文件

使用说明:
    PATH :HOSTS文件路径
    NEW_PATH :新HOSTS文件路径
     
    在change_host_file.py所在目录打开cmd运行以下命令
                                     方法   IP        网址
    添加:python host_file.py add 8.8.8.8 www.google.com
    删除:python host_file.py del 126.125.66.198   删除整行
    修改:python host_file.py change www.cnblogs.com www.google.com
                                        old              new
'''
import sys,os,re
 
PATH = '/etc/hosts'
NEW_PATH = '/etc/hosts_new'
def run():
    try:
        if sys.argv[1] == 'add':
            with open(PATH,'a+',encoding='utf-8') as f:
                new_IP = sys.argv[2] + ' '+ sys.argv[3]
                f.write('\n')
                f.write(new_IP)
                sys.exit('添加成功,请查看源文件')
        elif sys.argv[1] == 'del':
            with open(PATH, 'r+', encoding='utf-8') as f,open(NEW_PATH, 'a+', encoding='utf-8') as f2:
                data = f.readlines()
                for line in data:
                    if sys.argv[2] in line:
                        continue
                    f2.write(line)
            os.remove(PATH)
            os.rename(NEW_PATH,PATH)
            sys.exit('删除成功,请查看源文件')
        elif sys.argv[1] == 'change':
            open(NEW_PATH, 'a+').write(re.sub(r'%s'% sys.argv[2],'%s'% sys.argv[3],open(PATH).read()))
            os.remove(PATH)
            os.rename(NEW_PATH,PATH)
            sys.exit('修改成功,请查看源文件')
    except Exception as e:
        print(e)
if __name__ == '__main__':
    run()

 

posted @ 2018-12-29 13:39  小学弟-  阅读(605)  评论(0编辑  收藏  举报