forked from stay-sharp/hosts_for_google_service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lhosts
executable file
·127 lines (102 loc) · 2.53 KB
/
lhosts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/bin/sh
site=https://github.com/racaljk/hosts
thisname=${0##*/}
HOSTS=/etc/hosts
REMOTE="/tmp/hosts.rmt"
MAIN="https://raw.githubusercontent.com/racaljk/hosts/master/hosts"
MIRROR="https://coding.net/u/scaffrey/p/hosts/git/raw/master/hosts"
HOSTS_URL="$MAIN"
NET_TOOL="curl"
QWGET=
QCURL=
usage() {
cat >&2 <<EOL
提示:
可使用 crontab 定时执行脚本 (请确保 sudo 无需输入密码)
用法: $thisname [选项]...
默认从 $site 获取 hosts 文件,
并更新其中的 localhost 为 `hostname`
更新前,原 hosts 备份至 /etc/hosts.bak
选项:
-w, --wget 使用 wget 下载
-m, --mirror 使用 hosts 镜像地址
-q, --quiet 静默模式
-u, --url 自定义 hosts 源地址
-h, -1, --help 显示帮助信息并退出
退出状态:
0 正常
1 一般问题 (例如:命令行参数错误)
2 严重问题 (例如:文件下载失败)
参考:
$thisname -mq
自定义源:
$thisname -qu $MIRROR
EOL
}
hosts_get() {
if [ "$NET_TOOL" = "wget" ]; then
"$NET_TOOL" $QWGET "$HOSTS_URL" -O "$REMOTE"
else
# use curl
if [ "$QCURL" = "" ]; then
echo "正在更新 hosts ..."
fi
"$NET_TOOL" -# $QCURL "$HOSTS_URL" -o "$REMOTE"
fi
if [ "$?" -ne 0 ]; then
echo -e "\nhosts 下载失败" >&2
exit 2
fi
}
hosts_update() {
local loc="$1"
local rmt="$2"
local swp="hosts.swp"
local bak="/etc/hosts.bak"
local begin="# Copyright (c) 2014"
local end="# Modified hosts end"
sed -e "s/localhost/`hostname`/g" "$rmt" > "$swp"
rm -f "$rmt"
sudo cp "$loc" "$bak"
# check if racaljk hosts, or do nothing
if grep -q racaljk "$loc"; then
sed -e "/$begin/,/$end/d" "$loc" >> "$swp"
fi
sudo sh -c "cat $swp > $loc"
rm -f "$swp"
}
CMD=`getopt -o wmqu:h1 --long wget,mirror,quiet,url:,help -n \
"$thisname" -- "$@"` || exit 1
eval set -- "$CMD"
while true; do
case "$1" in
-w|--wget)
NET_TOOL="wget"
shift
;;
-m|--mirror)
HOSTS_URL="$MIRROR"
shift
;;
-q|--quiet)
QWGET=-q
QCURL=-s
shift
;;
-u|--url)
HOSTS_URL="$2"
shift 2
;;
-h|-1|--help)
usage
exit 0
shift
;;
--)
shift
break
;;
esac
done
hosts_get
hosts_update "$HOSTS" "$REMOTE"