美文网首页玩耍PythonPython
实践中学python:hosts文件

实践中学python:hosts文件

作者: 十一岁的加重 | 来源:发表于2017-08-25 19:14 被阅读53次

    场景:想上谷歌,又没有花钱买VPN,只能靠hosts上谷歌。所以每次上不了谷歌了都会从github上(https://github.com/racaljk/hosts)找到hosts文件,然后复制其中的内容到一个文件,然后再放到private/etc下面去,操作久了,人是会累的,用python来试试吧,不难

    #!/usr/bin/python
    # coding=utf-8
    import requests
    import os
    import getpass
    import shutil
    
    # 抓取这里的hosts文件内容
    hostsFilehtml = requests.get('https://raw.githubusercontent.com/racaljk/hosts/master/hosts')
    hostsText = hostsFilehtml.text
    if len(hostsText) <= 0:
        print ('抓取失败')
    else:
        print ('抓取成功')
    # 拿到当前的用户名,不能写成~/Desktop/hosts
        userName = getpass.getuser()
        localHostFilePath = '/Users/%s/Desktop/hosts'%userName
        isLocalHostFileExist = os.path.isfile(localHostFilePath)
        if not isLocalHostFileExist:
            print('桌面hosts文件不存在,开始创建hosts文件,并写入')
        else:
            print('桌面hosts文件存在,开始写入')
        mode = 'a' if isLocalHostFileExist else 'w'
        with open(localHostFilePath, mode) as f:
            f.write(hostsText)
        destPath = "/private/etc/hosts"
        print ('开始复制文件桌面的hosts文件至%s'%destPath)
        shutil.copyfile(localHostFilePath, destPath)
    
    
    

    以后更新hosts文件就方便多了

    相关文章

      网友评论

      本文标题:实践中学python:hosts文件

      本文链接:https://www.haomeiwen.com/subject/xwlpdxtx.html