Network WiFi Battery Sleep Wake VPN – How to Keep WiFi Alive When on Battery and Lid Closed

batteryNetworksleep-wakevpnwifi

We're using a VPN to access certain parts of internal infrastructure from the office; the VPN uses 2FA, so saving credentials and bringing it up with the network when the machine wakes up is not an option.

People take their Macbooks to meetings, and when they do they

  • lose power (battery mode)
  • close the lid

That combination causes the Mac to shut down WiFi, which subsequently frequently tears down the VPN connection (it survives when there's no TLS handshake while the interface is down). Is there a way to stop the Mac from going to sleep (turn off WiFi) when the lid gets closed?

Edit (adding script per request in comments):

#!/bin/bash
export PID=$(pgrep Tunnelblick)
CAFPID=""
while true
do
        if $(pgrep -q Tunnelblick && ifconfig | grep -q 172.30 && [[ $( pmset -g ac | wc -l ) -le 1 ]] && [[ $(ps -ef | grep -v grep | grep -c "caffeinate -t 300 -w $PID") -eq 0 ]]) ; then
                echo "need coffee"
                caffeinate -t 300 -w $PID >/dev/null 2>&1 &
        CAFPID=$(echo $!)
        else
                CAFPID=""
        fi
        if [[ $( pmset -g ac | wc -l ) -gt 1 ]] && [[ -z $CAFPID ]] ; then
                echo "no coffee"
                kill -TERM
                $CAFPID >/dev/null 2>&1
        fi
        sleep 60
done

Best Answer

You could try this, no need to install extra sofyware

Open Terminal and use

$ caffeinate -s  

or

$ caffeinate -w PID

When used with the -w argument, sleep will be inhibited as long as the process ID PID is active. Once the the process exits, the assertion is released, and the configured sleep behavior will resume when appropriate.

Note also that Process ID's are available from Activity Monitor, or can be listed in the terminal by entering ps -Al