Good morning, thank you for your reply! I finally did some experiments for my solution and everything works.
I bring the complete example below if maybe it can be useful for someone:
OSX: iMac (Intel, 2017) with MacOS Mojave 10.14.6
Problem: I need to find a basic solution that allows me to disable an internet network (wifi/ethernet/vpn) before a possible "lock screen" or "sleep mode".
1 - CREATE A BASH SCRIPT
cd /usr/local/bin
sudo touch script.sh
sudo chmod +x touch.sh
sudo chown root:wheel com.script.plist
sudo nano touch.sh
Inside the script i write this code (it works but I would like some suggestion/improvements)
while true; do
scriptdate=$(date -j)
scriptstatus=$(networksetup -showpppoestatus "MyVPN")
if tail -n 1 /var/log/system.log | grep "com.apple.xpc.launchd.unmanaged.loginwindow"; then
if [ "$scriptstatus" = "connected" ]; then
echo "$scriptdate >> script_force_disconnection" >> /tmp/script.log
networksetup -disconnectpppoeservice "MyVPN"
fi
else
echo "$scriptdate >> $scriptstatus" >> /tmp/script.log
fi
sleep 1
done
2 - CREATE THE .PLIST FILE
cd /Library/LaunchDaemons
sudo touch com.script.plist
sudo chmod +x com.script.plist
sudo chown root:wheel com.script.plist
sudo nano com.script.plist
Inside this file i write this code to activate it at the login and leave it always on:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple/DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.script</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/script.sh</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
</dict>
</plist>
3 - LOAD THE .PLIST FILE
sudo launchctl load -w /Library/LaunchAgents/com.script.plist
# if you want to unload it, you can use the following command line
sudo launchctl unload /Library/LaunchAgents/com.script.plist
4 - CHECK IF THE .PLIST IS LOAD
# get all the process and manually find "com.script"
sudo launchctl list
# or filter all the process with the process name
sudo launchctl list | grep "com.script"
if you did everything correctly you should get output similar to this:
PID Status Label
56 0 com.script
If you get an output like this:
PID Status Label
- 78 com.script
probably there is a problem in your script/.plist or file/directory permissions/owners in use
5 - RESTART & CONCLUSIONS
Restart your computer and do some testing with your Internet connection (I tried with a VPN).
When the computer goes into standby/sleep mode with the lock screen the script will proceed with disconnecting from the VPN.
This can be useful for corporate network accounts because the VPN can restrict access to corporate network resources and login.