前言
- 由于近期公司网络访问github特别不稳定,经常无法访问,然后就查找github的dns手动修改hosts,但是作为开发人员怎能每次手动修改,于是乎就写了python自动更新hosts脚本,废话不多说直接上代码。
创建auto_update_hosts.py文件
- 新建类 AutoUpdateHosts,init函数添加获取更新的
class AutoUpdateHosts(object): def __init__(self): self.new_hosts_url = 'Github项目521xueweihan/GitHub520获取'
- 新建is_admin,判断当前是否是管理员用户
def is_admin(): ''' Check whether the user is an administrator. :return: ''' try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False
- 新建get_default_contents,获取windows下hosts文件默认内容,可选添加自定义内容
def get_default_contents(custom=''): ''' Obtain the default contents of the hosts file. :param custom: Custom content :return: ''' contents = f''' # Copyright (c) 1993-2009 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a '#' symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost ''' if custom != '': contents += f''' # Customizing content start {custom.strip()} # Customizing content stop ''' return contents.replace(' ', '').strip()
- 新建get_new_contests,获取新的hosts内容
def get_new_contents(self): ''' Obtain the contents of the new hosts file :return: ''' resp = requests.get(self.new_hosts_url) return resp.text
- 新建save_hosts_contents,存储最终的hosts文件内容
def save_hosts_contents(self, custom=''): ''' Stores the final hosts file contents. :param custom: Custom content :return: ''' now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(round(time.time() * 1000) / 1000)) hosts_contents = f'{self.get_default_contents(custom=custom)}\n\n# Updated at {now_time}\n{self.get_new_contents()}' admin = self.is_admin() if admin: with open('C:\\Windows\\System32\\drivers\\etc\\hosts', 'w+') as fp: fp.write(hosts_contents) dnsFlush = "ipconfig /flushdns" os.system(dnsFlush) print("github DNS刷新成功") time.sleep(3) else: # Re-run the program with admin rights ctypes.windll.shell32.ShellExecuteW( None, "runas", sys.executable, __file__, None, 1)
- 效果图
创建定时任务
- 由于windows下无crontab,需使用
任务计划程序
来定时执行脚本。 - 创建定时任务过程不在演示,可自行搜索即可。
结语
- 因办公电脑是windows所以本脚本暂时只支持在windows下使用。
- 本教程有使用
521xueweihan/GitHub520
的开源项目,在此特别感谢。 - 以上就是自动刷新hosts文件的全部代码,希望能帮助一些小伙伴。
- 如果在类Unix运行本脚本代码则需稍做修改,如操作有问题欢迎去我的博客(www.loganjin.cn)留言或者微信公众号(Python技术交流圈)留言交流哦。
版权声明:如无特殊说明,文章均为本站原创,转载请注明出处
本文链接:https://www.loganjin.cn/article/auto-update-hosts/
许可协议:署名-非商业性使用 4.0 国际许可协议