Keep WiFi alive when on battery and lid closed? 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 &amp;&amp; ifconfig | grep -q 172.30 &amp;&amp; [[ $( pmset -g ac | wc -l ) -le 1 ]] &amp;&amp; [[ $(ps -ef | grep -v grep | grep -c "caffeinate -t 300 -w $PID") -eq 0 ]]) ; then
                echo "need coffee"
                caffeinate -t 300 -w $PID &gt;/dev/null 2&gt;&amp;1 &amp;
        CAFPID=$(echo $!)
        else
                CAFPID=""
        fi
        if [[ $( pmset -g ac | wc -l ) -gt 1 ]] &amp;&amp; [[ -z $CAFPID ]] ; then
                echo "no coffee"
                kill -TERM
                $CAFPID &gt;/dev/null 2&gt;&amp;1
        fi
        sleep 60
done
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