-
Notifications
You must be signed in to change notification settings - Fork 2
/
ztdisable
executable file
·65 lines (54 loc) · 2.13 KB
/
ztdisable
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
#!/bin/bash
#
# A QAD script to disable zerotier hosts via the zerotier API
# $1 is a (comma-separated list of) FQDN(s) or an ansible group name
SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}")
# shellcheck disable=SC1090,SC1091
. "$SCRIPT_DIR/poshlib/poshlib.sh" || exit 1
use strict
use utils
CURL_ARGS=-SsfL
if [[ ! ${ZT_TOKEN_FILE:-} ]]; then
ZT_TOKEN_FILE=/root/.zerotier-token
fi
[[ "${1:-}" ]] || die 99 "Usage: $0 <target> [<remote_user>]"
target="$1"
REMOTE_USER="${2:-}"
: "${REMOTE_USER:="$USER"}"
# If the target contains FQDNs, coerce it to the form:
# "[host_list], -i [host_list],"
# This lets us pass targets to ansible without adding them to an inventory
# file in advance.
if [[ "${target%.*}" != "$target" && "${target% -i *}" == "${target}" ]]; then
# $target contains '.' but does not contain ' -i ', so let's mangle it
target_a=("${target%,}," "-i" "${target%,},")
else
#shellcheck disable=SC2206
target_a=($target)
fi
ZT_TOKEN=$(sudo cat "$ZT_TOKEN_FILE")
if ! curl $CURL_ARGS -H "$ZT_TOKEN" https://my.zerotier.com/api/status|jq .online | grep -q true; then
die 1 "Zerotier is offline. Aborting!"
fi
NETWORKS=$(curl $CURL_ARGS -H "$ZT_TOKEN" https://my.zerotier.com/api/network|jq .|awk '/nwid/ {print $2}'|tr -d '",')
hosts=$(ansible "${target_a[@]}" -m command -u "$REMOTE_USER" -b -a \
'perl -e "open(IN, q[-|], q[zerotier-cli status]); while(<IN>) { if(s/^.*200 info ([0-9a-fA-F]+) .*$/$1/){print qq[RESULT;{{ inventory_hostname }};$_]} }"')
for network in $NETWORKS; do
for word in $hosts; do
host=${word#RESULT;}
if [[ $word == $host ]]; then
continue
fi
hostid=${host#*;}
[[ -z $( curl $CURL_ARGS \
-H "$ZT_TOKEN" \
https://my.zerotier.com/api/network/${network}/member/${hostid} ) ]] && continue
echo "Deauthorizing $host_id ($host) from network $network_id" >&2
curl -XPOST $CURL_ARGS \
-H "$ZT_TOKEN" \
-d '{"config": {"authorized": false}}' \
https://my.zerotier.com/api/network/${network}/member/${hostid} \
| jq . \
|| die 2 "Could not deauthorize"
done
done