-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhostblock
More file actions
executable file
·97 lines (85 loc) · 1.92 KB
/
hostblock
File metadata and controls
executable file
·97 lines (85 loc) · 1.92 KB
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
#!/bin/bash
HOSTFILE=/etc/hosts
BLOCKFILE=~/.hostblock
UNBLOCK=false
WHO=`whoami`
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
VERBOSE=true
function OUTPUT()
{
if $VERBOSE ; then
echo $@
fi
}
function USAGE()
{
echo "Bad usage."
}
function READ_OPTS()
{
# read flags
while getopts ":u" OPTION; do
case $OPTION in
u)
UNBLOCK=true
;;
?)
USAGE
exit 1
;;
esac
done
shift $((OPTIND - 1))
# read args
BLOCKSITES=$1
}
function BLOCKSITE()
{
site=$1
if $UNBLOCK ; then
OUTPUT "un blocking $1"
# remove if exists
sed -i -r "s/(^127\.0\.0\.1 $site www.$site hostblock$)/#HOSTUNBLOCK: \1/g" $HOSTFILE
else
OUTPUT "blocking $1"
# this could be written better...
# check if already blocked
grep -qE "^127\.0\.0\.1 $site www.$site hostblock$" $HOSTFILE
if [ $? = 0 ]; then
OUTPUT ' `- already blocked'
else
# check if unblocked
grep -qE "^#HOSTUNBLOCK: 127\.0\.0\.1 $site www.$site hostblock$" $HOSTFILE
if [ $? = 0 ]; then
# yes was blocked, unblock
sed -i -r "s/^#HOSTUNBLOCK: (127\.0\.0\.1 $site www.$site hostblock$)/\1/g" $HOSTFILE
else
# not blocked before, add it
echo "127.0.0.1 $site www.$site hostblock" >> $HOSTFILE
fi
fi
fi
}
#
# Start script.
#
# Run as root.
if [ "$WHO" != "root" ]; then
OUTPUT "Running as root"
sudo $DIR/hostblock $@
exit $?
fi
# Read cmd opts.
READ_OPTS $@
# Check for block sites.
if [ -z "$BLOCKSITES" ]; then
if [ ! -f $BLOCKFILE ]; then
echo "$BLOCKFILE does not exist"
exit 1
fi
BLOCKSITES=`cat $BLOCKFILE`
fi
# Block each site.
for site in $BLOCKSITES; do
BLOCKSITE $site
done