-
Notifications
You must be signed in to change notification settings - Fork 1
/
reconnect-wifi
executable file
·72 lines (63 loc) · 1.82 KB
/
reconnect-wifi
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
#!/bin/bash
set -e -f -u -o pipefail
# Run this command to configure the network to keep trying if connecting to the
# network fails.
# $ dir="/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A"
# $ sudo "${dir}/Resources/airport" \
# prefs joinmode=Preferred joinmodefallback=KeepLooking
# Run "airport prefs" to check current preferences.
readonly ATTEMPTS="${1:-10}" SLEEP_TIME="${2:-20}"
readonly DRYRUN="no"
# Figure out which network interface is wifi from the output of
# networksetup -listnetworkserviceorder
readonly WIFI_DEV="en1"
readonly SSID="burrow"
readonly INTERNAL_IP="192.168.86.1"
readonly LOG_FILE="${HOME}/tmp/logs/reconnect-wifi.log"
log() {
local now
now="$(date)"
echo "${now} $*" >> "${LOG_FILE}"
}
check_wifi() {
log "Starting checks"
# Make separate attempts with delays between then to cope with some transient
# failures.
for ((i = 0; i < ATTEMPTS; i++)); do
if ping -c 5 -o -q "${INTERNAL_IP}" >& /dev/null; then
log "attempt ${i}: internal ping succeeded"
exit 0
fi
log "attempt ${i}: internal ping failed"
sleep "${SLEEP_TIME}"
done
}
reset_wifi() {
ping -c 5 "${INTERNAL_IP}"
echo "Reconnecting wifi"
# Sometimes disabling the wifi is necessary to make everything work again :/
networksetup -setairportpower "${WIFI_DEV}" off
sleep 10
networksetup -setairportpower "${WIFI_DEV}" on
sleep 10
networksetup -setairportnetwork "${WIFI_DEV}" "${SSID}" - \
< "${HOME}/Documents/${SSID}-password.txt"
sleep 30
ping -c 5 "${INTERNAL_IP}"
}
main() {
check_wifi
log "All ${ATTEMPTS} attempts failed :("
if [ "${DRYRUN}" == "no" ]; then
set -x
for i in 1 2 3; do
if reset_wifi; then
exit 0
fi
done
log "All reset_wifi attempts failed"
else
echo "Dryrun is true, not making changes."
fi
}
main "$@"