A voir, si l'on a confiance dans le site.
Je me suis également fait mon petit script de mise à jour, les goûts et les couleurs hein 🙂
J'utilise un fichier /etc/hosts.local pour conserver les préférences locales.
Et je ne change pas le fichier /etc/hosts si son contenu n'a pas changé.
Le travail se fait silencieusement et il n'affiche quelque chose qu'en cas d'erreur.
EDIT: J'ai changé ma procédure de mise à jour.
Nouvelle version :
#! /usr/bin/env python
#######################################################################
##
## Mise a jour de /etc/hosts a partir de http://www.adzhosts.com
##
## Decouvert via http://forum.ubuntu-fr.org/viewtopic.php?id=371304
##
## - Les preferences locales du fichier /etc/hosts sont contenues
## dans /etc/hosts.local
## - Les mises a jour sont ignorees si elles redirigent vers un ip
## autre que 127.0.0.1 ou ::1
##
#######################################################################
## Online host file, with associated valid ips
hosts_provider = "http://kosvocore.free.fr/AdZHosts/HOSTS.txt"
provider_allowed_ips = "127.0.0.1","::1"
## Host file
hosts = "/etc/hosts"
## Local host customization
localconfig = "/etc/hosts.local"
#######################################################################
import sys
import os
import shutil
import urllib2
import re
import time
#######################################################################
def url_exception_handler(exc) :
"""Handle exceptions while fetching data from url"""
print >>sys.stderr, "Error while retrieving data from "+url+", aborting ("+str(exc)+")"
sys.exit(1)
def load_hosts(url) :
"""Load a hosts file into data and ips global vars"""
global data
global ips
if url.startswith("/") :
handler = file(url)
islocal = True
else :
try : handler = urllib2.urlopen(url)
except Exception, exc : url_exception_handler(exc)
islocal = False
data.append("####")
data.append("## Beginning of "+url)
while True :
try : line = handler.readline()
except Exception, exc :
if not islocal : url_exception_handler(exc)
raise
## Handle windows line-termination gracefully
line = line.replace("\r", "")
if line == "" : break
line = line.rstrip("\n")
if re.search(r"^\s*(?:#.*)?$", line) :
data.append(line)
continue
m = re.search(r"^(?P<ip>\S+)\s+(?P<hostnames>[^#]*?)\s*(?P<comment>#.*?)?\s*$", line)
if not m :
if url == localconfig :
data.append(line)
continue
else :
print >>sys.stderr, "Ignoring malformed line "+line
continue
ip = m.group("ip")
hostnames = re.split(r"\s+", m.group("hostnames"))
## Ignore ip redirections update if they are deemed unsafe
if url != localconfig and ip not in provider_allowed_ips :
print >>sys.stderr, "Warning: ignoring unsafe update: "+line
continue
## Remove hostnames duplicates
newhostnames = []
for h in hostnames :
if ips.has_key(h) : continue
ips[h] = ip
newhostnames.append(h)
if len(newhostnames) == 0 : continue
if m.group("comment") is not None :
data.append(m.group("comment"))
## Only put one hostname per line when using external sources
if url == localconfig :
data.append(ip+"\t"+" ".join(newhostnames))
else :
data.extend([ ip+"\t"+hostname for hostname in newhostnames ])
data.append("## End of "+url)
data.append("####")
data.append("")
#######################################################################
## Program name
prog = os.path.basename(sys.argv[0])
## New data for /etc/hosts
data = [
"##",
"## Autogenerated by "+prog+" at "+time.asctime(),
"## DO NOT MODIFY, edit "+localconfig+" and rerun "+prog+" instead",
"##",
"",
]
## Hostname -> ip associations
ips = {}
## Backup /etc/hosts the first time we run
if not os.path.exists(localconfig) :
shutil.copy2(hosts, localconfig)
## Build new hosts file
for url in localconfig, hosts_provider :
load_hosts(url)
## Don't update config file if hasn't changed
rawdata = "\n".join(data)+"\n"
if os.path.exists(hosts) and file(hosts).read() == rawdata :
sys.exit(0)
## Change hosts file
tmp = hosts + os.extsep + "tmp"
f = file(tmp, "w")
f.write(rawdata)
f.flush()
f.close()
try : shutil.copymode(local, tmp)
except Exception : os.chmod(tmp, 00644)
os.rename(tmp,hosts)
#######################################################################
Ancienne version :
#! /usr/bin/env bash
#######################################################################
## Online host file
url="http://kosvocore.free.fr/AdZHosts/HOSTS.txt"
## Host file
hosts="/etc/hosts"
## Local host customization
local="$hosts.local"
## Temporary build location
tmp="$hosts.tmp"
#######################################################################
## Backup /etc/hosts the first time we run
test -e "$local" || cp -a "$hosts" "$local" || exit 1
## Build new hosts
! test -e "$tmp" || rm -f "$tmp" || exit 1
{ { ! test -e "$local" || cat "$local"; } && wget -q -O- "$url"; } >"$tmp" || exit 1
chmod 00644 "$tmp" || exit 1
## Don't update config file if it hasn't changed
if test -e "$hosts" && diff -q "$hosts" "$tmp" >/dev/null; then
rm -f "$tmp" &>/dev/null
exit 0
fi
## Change hosts file
mv -f "$tmp" "$hosts"
#######################################################################