Skip to content

Instantly share code, notes, and snippets.

@thislight
Last active March 6, 2019 11:58
Show Gist options
  • Save thislight/3a171d1cf4535626bc67de7d8458f8d4 to your computer and use it in GitHub Desktop.
Save thislight/3a171d1cf4535626bc67de7d8458f8d4 to your computer and use it in GitHub Desktop.
自动下载并合并Hosts文件,在Fedora23上测试通过

自动下载并合并Hosts文件

hosts.py [--download] [--apply] [--addhosts url] [--pid]

  • --download 下载Hosts文件(合并至hosts.tmp)
  • --apply 应用至系统(/etc/hosts)
  • --addhosts url 添加URL到HOSTS源列表(hosts.json)
  • --pid 显示pid

默认携带的HOSTS源:

还有一个要强调的: 没有自动备份!没有自动备份!没有自动备份!

ChangeLog:

  • Revision 5
    • 修复readall方法部分平台没有的问题
  • Revision 4
    • 添加ChangLog和提示
  • Revision 3
    • 添加README.md
  • Revision 2
    • 修改注解
  • Revision 1
    • 首次发布
#!python3
#coding=utf-8
"""
Download and apply hosts.
@anthor: thislight
"""
import os
import sys
import json
import os.path as path
import urllib.request as request
cmdline = {}
SYS_HOSTS_PATH = "/etc/hosts"
TMP_HOSTS_PATH = "./hosts.tmp"
arg_map = {
"--addlist" : "add_list",
"--apply" : "apply",
"--download" : "download",
"--addhosts" : "add_hosts",
"--removechange" : "remove_change",
"--pid" : "show_pid",
"-d" : "download",
"-r" : "remove_change",
"-a" : "apply"
}
CONFIG_PATH = "./hosts.json"
DEFAULT_HOSTS = [
"https://coding.net/u/Elaine_ni/p/hosts/git/raw/master/hosts.txt",
"https://raw.githubusercontent.com/lack006/Android-Hosts-L/master/hosts_files/2016_hosts/RE_full",
"https://raw.githubusercontent.com/racaljk/hosts/master/hosts",
"https://raw.githubusercontent.com/sy618/hosts/master/ADFQ"
]
global config
config = []
def is_arg_op(s):
return s.startswith("--") or s.startswith("-")
def get_true_op(s):
return arg_map[s]
def parse_cmdline():
"""
Parse cmd line arg.
"""
ops = [ v for v in sys.argv if (is_arg_op(v) and (v in arg_map)) ]
for v in ops:
index = sys.argv.index(v)
if len(sys.argv)>index+1:
tmp = sys.argv[index+1]
else:
tmp = 'True'
if not is_arg_op(tmp):
cmdline[get_true_op(v)] = tmp
else:
cmdline[get_true_op(v)] = True
def when_error(e,*arg):
print("A Error happened!\n",e,"\n",repr(arg))
def get_file(url):
"""
download file.
@param url: file url
"""
try:
with request.urlopen(url) as f:
return f.read()
except request.HTTPError as e:
when_error(e,url)
except request.URLError as e:
when_error(e,url)
except ValueError as e:
when_error(e,url)
def _save_config(l):
json.dump(l,open(CONFIG_PATH,mode="w"))
def save_config():
"""
Save config to disk.
"""
_save_config(config)
def read_config():
"""
Read config to disk.
"""
return json.load(open(CONFIG_PATH,mode="r"))
def load_config():
"""
Load config
"""
global config
config = read_config()
def check_has_file():
"""
Check config file exists.
"""
if not path.exists(CONFIG_PATH):
_save_config(DEFAULT_HOSTS)
config = DEFAULT_HOSTS
def join_hosts(*args):
"""
@return: str
"""
return ''.join(args)
def write_hosts(s):
"""
Write to system hosts.
Need root permission.
"""
with open(SYS_HOSTS_PATH,mode="wb") as f:
f.write(s)
def onload():
"""
Call when start
"""
parse_cmdline()
check_has_file()
load_config()
def onexit():
"""
Call when exit.
"""
save_config()
def add_list():
pass
def apply():
with open(TMP_HOSTS_PATH,mode="rb") as f:
write_hosts(f.read())
print("Apply to %s finished." % SYS_HOSTS_PATH)
def download():
print("Start download..")
with open(TMP_HOSTS_PATH,mode="wb") as f:
for v in config:
print("Downloading file %s from %s." % (path.split(v)[-1],v))
f.write(get_file(v))
f.write(b"\n")
print("Downloaded file %s from %s." % (path.split(v)[-1],v))
print("-"*6)
print("Finished")
def add_hosts():
config.append(cmdline.get("add_hosts"))
print("Added %s" % cmdline.get("add_hosts"))
def remove_change():
write_hosts("")
print("Removed.")
def show_pid():
print("Pid : %s" % os.getpid())
def main():
for k in cmdline: print("%s -> %s" % (k,cmdline[k]))
for k in cmdline:
eval("%s()" % k,globals())
if __name__ == "__main__":
onload()
main()
onexit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment