Skip to content

Instantly share code, notes, and snippets.

@samdfonseca
Created December 26, 2017 06:02
Show Gist options
  • Save samdfonseca/74fba9296f98c7c2b853e424c64c7701 to your computer and use it in GitHub Desktop.
Save samdfonseca/74fba9296f98c7c2b853e424c64c7701 to your computer and use it in GitHub Desktop.
Ubuntu 16.04 WiFi Restarter
#!/bin/sh
LOGFILE=$(dirname $BASH_SOURCE)/restart-$(date +'%m-%d-%Y').log
echo_log() {
local msg=$1
echo "[$(date +'%m-%d-%Y %T')] - $msg" | tee -a $LOGFILE
}
check_ip_address_is_reachable() {
local check_ip="$1"
ping -c 1 ${check_ip} >/dev/null
local is_reachable=$?
if [[ ${is_reachable} -eq 0 ]]; then
echo_log "${check_ip} is reachable"
else
echo_log "${check_ip} is not reachable"
fi
return ${is_reachable}
}
check_port_is_open() {
local network_address="$1"
local check_port="$2"
nc -z ${network_address} ${check_port} >/dev/null
local is_open=$?
if [[ ${is_open} -eq 0 ]]; then
echo_log "${network_address}:${check_port} is open"
else
echo_log "${network_address}:${check_port} is not open"
fi
return ${is_open}
}
reconnect_wifi() {
echo_log "Restarting netowork-manager.service"
sudo systemctl restart network-manager.service
# local wifi_device="$1"
# echo_log "Bringing up ${wifi_device} device"
# nmcli c up ifname ${wifi_device} >/dev/null
# echo_log "Connecting ${wifi_device}"
# nmcli d wifi connect wlp2s0
# echo_log "Finished bringing up ${wifi_device}"
}
compress_previous_log() {
yesterday=$(date --date="1 day ago" '+%m-%d-%Y')
yesterday_log="$(dirname ${BASH_SOURCE})/restart-${yesterday}.log"
yesterday_log_archive="${yesterday_log}.tar.gz"
if [[ -f $yesterday_log ]]; then
if [[ ! -f $yesterday_log_archive ]]; then
tar -zcf $yesterday_log_archive $yesterday_log
fi
rm $yesterday_log
fi
}
main() {
local wifi_device="wlp2s0"
local google_dns_ip="8.8.8.8"
local static_network_ip="192.168.0.8"
compress_previous_log
check_ip_address_is_reachable ${google_dns_ip}
if [[ $? -ne 0 ]]; then
reconnect_wifi ${wifi_device}
else
check_ip_address_is_reachable ${static_network_ip}
if [[ $? -ne 0 ]]; then
reconnect_wifi ${wifi_device}
else
check_port_is_open ${static_network_ip} 22
if [[ $? -ne 0 ]]; then
reconnect_wifi ${wifi_device}
fi
fi
fi
}
main
# vim: set ts=2 sw=2 tw=120 ft=sh et :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment