-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathhosts
executable file
·70 lines (64 loc) · 1.59 KB
/
hosts
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
#!/bin/bash
help() {
echo 'usage: hosts allow|block|status FQDN'
echo ' hosts --help'
echo
echo ' adds or comments out an entry in /etc/hosts like this:'
echo
echo ' $ grep FQDN /etc/hosts'
echo ' 127.0.0.2 FQDN'
echo
echo ' thereby blockin or allowing access to the FQDN'
echo
echo ' ATTENTION: no checks are made on well-formed-ness of the'
echo ' provided FQDN'
exit 1
}
[ "$1" == "--help" ] && help
set -e # stop on error
#set -u # stop on undefined variable
set -o pipefail # stop part of pipeline failing
enforce_FQDN_arg() {
# "$1" must be set
#
if [ "$1" == "" ]; then
echo 'ERROR: you need to pass a FQDN hostname as parameter' >&2
exit 1
fi
# if "$2" is given then the status of "$1" must be equal to "$2"
#
if [ "$2" != "" ]; then
if [ "$2" != "$( hosts status "$1" )" ]; then
echo "ERROR: $1 was not in state '$2' as it should have been"
exit 1
fi
fi
}
case "$1" in
allow)
enforce_FQDN_arg "$2" 'blocked'
sed --in-place \
"s/^127.0.0.2 $2$/#127.0.0.2 $2/" \
/etc/hosts
;;
block)
enforce_FQDN_arg "$2" 'allowed'
sed --in-place \
"s/^#127.0.0.2 $2$/127.0.0.2 $2/" \
/etc/hosts
;;
status)
enforce_FQDN_arg "$2"
if grep -q -E "^#127.0.0.2 $2$" /etc/hosts; then
echo 'allowed'
elif grep -q -E "^127.0.0.2 $2$" /etc/hosts; then
echo 'blocked'
else
echo 'unknown'
fi
;;
*)
echo "ERROR: you need to pass either 'block' or 'allow' as an argument" >&2
exit 1
;;
esac